/**
* plotly.js (mapbox) v1.37.1
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
* Licensed under the MIT license
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Plotly = f()}})(function(){var define,module,exports;return (function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
'use strict';

var Lib = require('../src/lib');
var rules = {
    "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;",
    "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;",
    "X input:focus,X button:focus": "outline:none;",
    "X a": "text-decoration:none;",
    "X a:hover": "text-decoration:none;",
    "X .crisp": "shape-rendering:crispEdges;",
    "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
    "X svg": "overflow:hidden;",
    "X svg a": "fill:#447adb;",
    "X svg a:hover": "fill:#3c6dc5;",
    "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
    "X .main-svg .draglayer": "pointer-events:all;",
    "X .cursor-default": "cursor:default;",
    "X .cursor-pointer": "cursor:pointer;",
    "X .cursor-crosshair": "cursor:crosshair;",
    "X .cursor-move": "cursor:move;",
    "X .cursor-col-resize": "cursor:col-resize;",
    "X .cursor-row-resize": "cursor:row-resize;",
    "X .cursor-ns-resize": "cursor:ns-resize;",
    "X .cursor-ew-resize": "cursor:ew-resize;",
    "X .cursor-sw-resize": "cursor:sw-resize;",
    "X .cursor-s-resize": "cursor:s-resize;",
    "X .cursor-se-resize": "cursor:se-resize;",
    "X .cursor-w-resize": "cursor:w-resize;",
    "X .cursor-e-resize": "cursor:e-resize;",
    "X .cursor-nw-resize": "cursor:nw-resize;",
    "X .cursor-n-resize": "cursor:n-resize;",
    "X .cursor-ne-resize": "cursor:ne-resize;",
    "X .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);",
    "X .modebar--hover": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;",
    "X:hover .modebar--hover": "opacity:1;",
    "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
    "X .modebar-group:first-child": "margin-left:0px;",
    "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;",
    "X .modebar-btn svg": "position:relative;top:2px;",
    "X .modebar-btn path": "fill:rgba(0,31,95,0.3);",
    "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);",
    "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;",
    "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;",
    "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
    "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
    "X [data-title]:before": "content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
    "X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
    "X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;",
    "X .select-outline-1": "stroke:white;",
    "X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;",
    Y: "font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
    "Y p": "margin:0;",
    "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
    "Y .notifier-close": "color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
    "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
};

for(var selector in rules) {
    var fullSelector = selector.replace(/^,/,' ,')
        .replace(/X/g, '.js-plotly-plot .plotly')
        .replace(/Y/g, '.plotly-notifier');
    Lib.addStyleRule(fullSelector, rules[selector]);
}

},{"../src/lib":164}],2:[function(require,module,exports){
'use strict';

module.exports = {
    'undo': {
        'width': 857.1,
        'path': 'm857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z',
        'ascent': 850,
        'descent': -150
    },
    'home': {
        'width': 928.6,
        'path': 'm786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z',
        'ascent': 850,
        'descent': -150
    },
    'camera-retro': {
        'width': 1000,
        'path': 'm518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z',
        'ascent': 850,
        'descent': -150
    },
    'zoombox': {
        'width': 1000,
        'path': 'm1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z',
        'ascent': 850,
        'descent': -150
    },
    'pan': {
        'width': 1000,
        'path': 'm1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z',
        'ascent': 850,
        'descent': -150
    },
    'zoom_plus': {
        'width': 1000,
        'path': 'm1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z',
        'ascent': 850,
        'descent': -150
    },
    'zoom_minus': {
        'width': 1000,
        'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z',
        'ascent': 850,
        'descent': -150
    },
    'autoscale': {
        'width': 1000,
        'path': 'm250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z',
        'ascent': 850,
        'descent': -150
    },
    'tooltip_basic': {
        'width': 1500,
        'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z',
        'ascent': 850,
        'descent': -150
    },
    'tooltip_compare': {
        'width': 1125,
        'path': 'm187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z',
        'ascent': 850,
        'descent': -150
    },
    'plotlylogo': {
        'width': 1542,
        'path': 'm0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z',
        'ascent': 850,
        'descent': -150
    },
    'z-axis': {
        'width': 1000,
        'path': 'm833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z',
        'ascent': 850,
        'descent': -150
    },
    '3d_rotate': {
        'width': 1000,
        'path': 'm922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z',
        'ascent': 850,
        'descent': -150
    },
    'camera': {
        'width': 1000,
        'path': 'm500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z',
        'ascent': 850,
        'descent': -150
    },
    'movie': {
        'width': 1000,
        'path': 'm938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z',
        'ascent': 850,
        'descent': -150
    },
    'question': {
        'width': 857.1,
        'path': 'm500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z',
        'ascent': 850,
        'descent': -150
    },
    'disk': {
        'width': 857.1,
        'path': 'm214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z',
        'ascent': 850,
        'descent': -150
    },
    'lasso': {
        'width': 1031,
        'path': 'm1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z',
        'ascent': 850,
        'descent': -150
    },
    'selectbox': {
        'width': 1000,
        'path': 'm0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z',
        'ascent': 850,
        'descent': -150
    },
    'spikeline': {
        'width': 1000,
        'path': 'M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z',
        'ascent': 850,
        'descent': -150
    }
};

},{}],3:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = require('../src/core');

},{"../src/core":148}],4:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Plotly = require('./core');

Plotly.register([
    require('./scattermapbox')
]);

module.exports = Plotly;

},{"./core":3,"./scattermapbox":5}],5:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = require('../src/traces/scattermapbox');

},{"../src/traces/scattermapbox":298}],6:[function(require,module,exports){
!function() {
  var d3 = {
    version: "3.5.17"
  };
  var d3_arraySlice = [].slice, d3_array = function(list) {
    return d3_arraySlice.call(list);
  };
  var d3_document = this.document;
  function d3_documentElement(node) {
    return node && (node.ownerDocument || node.document || node).documentElement;
  }
  function d3_window(node) {
    return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
  }
  if (d3_document) {
    try {
      d3_array(d3_document.documentElement.childNodes)[0].nodeType;
    } catch (e) {
      d3_array = function(list) {
        var i = list.length, array = new Array(i);
        while (i--) array[i] = list[i];
        return array;
      };
    }
  }
  if (!Date.now) Date.now = function() {
    return +new Date();
  };
  if (d3_document) {
    try {
      d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
    } catch (error) {
      var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
      d3_element_prototype.setAttribute = function(name, value) {
        d3_element_setAttribute.call(this, name, value + "");
      };
      d3_element_prototype.setAttributeNS = function(space, local, value) {
        d3_element_setAttributeNS.call(this, space, local, value + "");
      };
      d3_style_prototype.setProperty = function(name, value, priority) {
        d3_style_setProperty.call(this, name, value + "", priority);
      };
    }
  }
  d3.ascending = d3_ascending;
  function d3_ascending(a, b) {
    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  }
  d3.descending = function(a, b) {
    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  };
  d3.min = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && a > b) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
    }
    return a;
  };
  d3.max = function(array, f) {
    var i = -1, n = array.length, a, b;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null && b > a) a = b;
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
    }
    return a;
  };
  d3.extent = function(array, f) {
    var i = -1, n = array.length, a, b, c;
    if (arguments.length === 1) {
      while (++i < n) if ((b = array[i]) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = array[i]) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    } else {
      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
        a = c = b;
        break;
      }
      while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
        if (a > b) a = b;
        if (c < b) c = b;
      }
    }
    return [ a, c ];
  };
  function d3_number(x) {
    return x === null ? NaN : +x;
  }
  function d3_numeric(x) {
    return !isNaN(x);
  }
  d3.sum = function(array, f) {
    var s = 0, n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = +array[i])) s += a;
    } else {
      while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
    }
    return s;
  };
  d3.mean = function(array, f) {
    var s = 0, n = array.length, a, i = -1, j = n;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
    }
    if (j) return s / j;
  };
  d3.quantile = function(values, p) {
    var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
    return e ? v + e * (values[h] - v) : v;
  };
  d3.median = function(array, f) {
    var numbers = [], n = array.length, a, i = -1;
    if (arguments.length === 1) {
      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
    } else {
      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
    }
    if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
  };
  d3.variance = function(array, f) {
    var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
    if (arguments.length === 1) {
      while (++i < n) {
        if (d3_numeric(a = d3_number(array[i]))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    } else {
      while (++i < n) {
        if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
          d = a - m;
          m += d / ++j;
          s += d * (a - m);
        }
      }
    }
    if (j > 1) return s / (j - 1);
  };
  d3.deviation = function() {
    var v = d3.variance.apply(this, arguments);
    return v ? Math.sqrt(v) : v;
  };
  function d3_bisector(compare) {
    return {
      left: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
        }
        return lo;
      },
      right: function(a, x, lo, hi) {
        if (arguments.length < 3) lo = 0;
        if (arguments.length < 4) hi = a.length;
        while (lo < hi) {
          var mid = lo + hi >>> 1;
          if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
        }
        return lo;
      }
    };
  }
  var d3_bisect = d3_bisector(d3_ascending);
  d3.bisectLeft = d3_bisect.left;
  d3.bisect = d3.bisectRight = d3_bisect.right;
  d3.bisector = function(f) {
    return d3_bisector(f.length === 1 ? function(d, x) {
      return d3_ascending(f(d), x);
    } : f);
  };
  d3.shuffle = function(array, i0, i1) {
    if ((m = arguments.length) < 3) {
      i1 = array.length;
      if (m < 2) i0 = 0;
    }
    var m = i1 - i0, t, i;
    while (m) {
      i = Math.random() * m-- | 0;
      t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
    }
    return array;
  };
  d3.permute = function(array, indexes) {
    var i = indexes.length, permutes = new Array(i);
    while (i--) permutes[i] = array[indexes[i]];
    return permutes;
  };
  d3.pairs = function(array) {
    var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
    while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
    return pairs;
  };
  d3.transpose = function(matrix) {
    if (!(n = matrix.length)) return [];
    for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
      for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
        row[j] = matrix[j][i];
      }
    }
    return transpose;
  };
  function d3_transposeLength(d) {
    return d.length;
  }
  d3.zip = function() {
    return d3.transpose(arguments);
  };
  d3.keys = function(map) {
    var keys = [];
    for (var key in map) keys.push(key);
    return keys;
  };
  d3.values = function(map) {
    var values = [];
    for (var key in map) values.push(map[key]);
    return values;
  };
  d3.entries = function(map) {
    var entries = [];
    for (var key in map) entries.push({
      key: key,
      value: map[key]
    });
    return entries;
  };
  d3.merge = function(arrays) {
    var n = arrays.length, m, i = -1, j = 0, merged, array;
    while (++i < n) j += arrays[i].length;
    merged = new Array(j);
    while (--n >= 0) {
      array = arrays[n];
      m = array.length;
      while (--m >= 0) {
        merged[--j] = array[m];
      }
    }
    return merged;
  };
  var abs = Math.abs;
  d3.range = function(start, stop, step) {
    if (arguments.length < 3) {
      step = 1;
      if (arguments.length < 2) {
        stop = start;
        start = 0;
      }
    }
    if ((stop - start) / step === Infinity) throw new Error("infinite range");
    var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
    start *= k, stop *= k, step *= k;
    if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
    return range;
  };
  function d3_range_integerScale(x) {
    var k = 1;
    while (x * k % 1) k *= 10;
    return k;
  }
  function d3_class(ctor, properties) {
    for (var key in properties) {
      Object.defineProperty(ctor.prototype, key, {
        value: properties[key],
        enumerable: false
      });
    }
  }
  d3.map = function(object, f) {
    var map = new d3_Map();
    if (object instanceof d3_Map) {
      object.forEach(function(key, value) {
        map.set(key, value);
      });
    } else if (Array.isArray(object)) {
      var i = -1, n = object.length, o;
      if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
    } else {
      for (var key in object) map.set(key, object[key]);
    }
    return map;
  };
  function d3_Map() {
    this._ = Object.create(null);
  }
  var d3_map_proto = "__proto__", d3_map_zero = "\x00";
  d3_class(d3_Map, {
    has: d3_map_has,
    get: function(key) {
      return this._[d3_map_escape(key)];
    },
    set: function(key, value) {
      return this._[d3_map_escape(key)] = value;
    },
    remove: d3_map_remove,
    keys: d3_map_keys,
    values: function() {
      var values = [];
      for (var key in this._) values.push(this._[key]);
      return values;
    },
    entries: function() {
      var entries = [];
      for (var key in this._) entries.push({
        key: d3_map_unescape(key),
        value: this._[key]
      });
      return entries;
    },
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
    }
  });
  function d3_map_escape(key) {
    return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
  }
  function d3_map_unescape(key) {
    return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
  }
  function d3_map_has(key) {
    return d3_map_escape(key) in this._;
  }
  function d3_map_remove(key) {
    return (key = d3_map_escape(key)) in this._ && delete this._[key];
  }
  function d3_map_keys() {
    var keys = [];
    for (var key in this._) keys.push(d3_map_unescape(key));
    return keys;
  }
  function d3_map_size() {
    var size = 0;
    for (var key in this._) ++size;
    return size;
  }
  function d3_map_empty() {
    for (var key in this._) return false;
    return true;
  }
  d3.nest = function() {
    var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
    function map(mapType, array, depth) {
      if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
      var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
      while (++i < n) {
        if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
          values.push(object);
        } else {
          valuesByKey.set(keyValue, [ object ]);
        }
      }
      if (mapType) {
        object = mapType();
        setter = function(keyValue, values) {
          object.set(keyValue, map(mapType, values, depth));
        };
      } else {
        object = {};
        setter = function(keyValue, values) {
          object[keyValue] = map(mapType, values, depth);
        };
      }
      valuesByKey.forEach(setter);
      return object;
    }
    function entries(map, depth) {
      if (depth >= keys.length) return map;
      var array = [], sortKey = sortKeys[depth++];
      map.forEach(function(key, keyMap) {
        array.push({
          key: key,
          values: entries(keyMap, depth)
        });
      });
      return sortKey ? array.sort(function(a, b) {
        return sortKey(a.key, b.key);
      }) : array;
    }
    nest.map = function(array, mapType) {
      return map(mapType, array, 0);
    };
    nest.entries = function(array) {
      return entries(map(d3.map, array, 0), 0);
    };
    nest.key = function(d) {
      keys.push(d);
      return nest;
    };
    nest.sortKeys = function(order) {
      sortKeys[keys.length - 1] = order;
      return nest;
    };
    nest.sortValues = function(order) {
      sortValues = order;
      return nest;
    };
    nest.rollup = function(f) {
      rollup = f;
      return nest;
    };
    return nest;
  };
  d3.set = function(array) {
    var set = new d3_Set();
    if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
    return set;
  };
  function d3_Set() {
    this._ = Object.create(null);
  }
  d3_class(d3_Set, {
    has: d3_map_has,
    add: function(key) {
      this._[d3_map_escape(key += "")] = true;
      return key;
    },
    remove: d3_map_remove,
    values: d3_map_keys,
    size: d3_map_size,
    empty: d3_map_empty,
    forEach: function(f) {
      for (var key in this._) f.call(this, d3_map_unescape(key));
    }
  });
  d3.behavior = {};
  function d3_identity(d) {
    return d;
  }
  d3.rebind = function(target, source) {
    var i = 1, n = arguments.length, method;
    while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
    return target;
  };
  function d3_rebind(target, source, method) {
    return function() {
      var value = method.apply(source, arguments);
      return value === source ? target : value;
    };
  }
  function d3_vendorSymbol(object, name) {
    if (name in object) return name;
    name = name.charAt(0).toUpperCase() + name.slice(1);
    for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
      var prefixName = d3_vendorPrefixes[i] + name;
      if (prefixName in object) return prefixName;
    }
  }
  var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
  function d3_noop() {}
  d3.dispatch = function() {
    var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    return dispatch;
  };
  function d3_dispatch() {}
  d3_dispatch.prototype.on = function(type, listener) {
    var i = type.indexOf("."), name = "";
    if (i >= 0) {
      name = type.slice(i + 1);
      type = type.slice(0, i);
    }
    if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
    if (arguments.length === 2) {
      if (listener == null) for (type in this) {
        if (this.hasOwnProperty(type)) this[type].on(name, null);
      }
      return this;
    }
  };
  function d3_dispatch_event(dispatch) {
    var listeners = [], listenerByName = new d3_Map();
    function event() {
      var z = listeners, i = -1, n = z.length, l;
      while (++i < n) if (l = z[i].on) l.apply(this, arguments);
      return dispatch;
    }
    event.on = function(name, listener) {
      var l = listenerByName.get(name), i;
      if (arguments.length < 2) return l && l.on;
      if (l) {
        l.on = null;
        listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
        listenerByName.remove(name);
      }
      if (listener) listeners.push(listenerByName.set(name, {
        on: listener
      }));
      return dispatch;
    };
    return event;
  }
  d3.event = null;
  function d3_eventPreventDefault() {
    d3.event.preventDefault();
  }
  function d3_eventSource() {
    var e = d3.event, s;
    while (s = e.sourceEvent) e = s;
    return e;
  }
  function d3_eventDispatch(target) {
    var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
    dispatch.of = function(thiz, argumentz) {
      return function(e1) {
        try {
          var e0 = e1.sourceEvent = d3.event;
          e1.target = target;
          d3.event = e1;
          dispatch[e1.type].apply(thiz, argumentz);
        } finally {
          d3.event = e0;
        }
      };
    };
    return dispatch;
  }
  d3.requote = function(s) {
    return s.replace(d3_requote_re, "\\$&");
  };
  var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
  var d3_subclass = {}.__proto__ ? function(object, prototype) {
    object.__proto__ = prototype;
  } : function(object, prototype) {
    for (var property in prototype) object[property] = prototype[property];
  };
  function d3_selection(groups) {
    d3_subclass(groups, d3_selectionPrototype);
    return groups;
  }
  var d3_select = function(s, n) {
    return n.querySelector(s);
  }, d3_selectAll = function(s, n) {
    return n.querySelectorAll(s);
  }, d3_selectMatches = function(n, s) {
    var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
    d3_selectMatches = function(n, s) {
      return d3_selectMatcher.call(n, s);
    };
    return d3_selectMatches(n, s);
  };
  if (typeof Sizzle === "function") {
    d3_select = function(s, n) {
      return Sizzle(s, n)[0] || null;
    };
    d3_selectAll = Sizzle;
    d3_selectMatches = Sizzle.matchesSelector;
  }
  d3.selection = function() {
    return d3.select(d3_document.documentElement);
  };
  var d3_selectionPrototype = d3.selection.prototype = [];
  d3_selectionPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, group, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(subnode = selector.call(node, node.__data__, i, j));
          if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selector(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_select(selector, this);
    };
  }
  d3_selectionPrototype.selectAll = function(selector) {
    var subgroups = [], subgroup, node;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
          subgroup.parentNode = node;
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_selectorAll(selector) {
    return typeof selector === "function" ? selector : function() {
      return d3_selectAll(selector, this);
    };
  }
  var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
  var d3_nsPrefix = {
    svg: "http://www.w3.org/2000/svg",
    xhtml: d3_nsXhtml,
    xlink: "http://www.w3.org/1999/xlink",
    xml: "http://www.w3.org/XML/1998/namespace",
    xmlns: "http://www.w3.org/2000/xmlns/"
  };
  d3.ns = {
    prefix: d3_nsPrefix,
    qualify: function(name) {
      var i = name.indexOf(":"), prefix = name;
      if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
      return d3_nsPrefix.hasOwnProperty(prefix) ? {
        space: d3_nsPrefix[prefix],
        local: name
      } : name;
    }
  };
  d3_selectionPrototype.attr = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node();
        name = d3.ns.qualify(name);
        return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
      }
      for (value in name) this.each(d3_selection_attr(value, name[value]));
      return this;
    }
    return this.each(d3_selection_attr(name, value));
  };
  function d3_selection_attr(name, value) {
    name = d3.ns.qualify(name);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrConstant() {
      this.setAttribute(name, value);
    }
    function attrConstantNS() {
      this.setAttributeNS(name.space, name.local, value);
    }
    function attrFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
    }
    function attrFunctionNS() {
      var x = value.apply(this, arguments);
      if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
    }
    return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
  }
  function d3_collapse(s) {
    return s.trim().replace(/\s+/g, " ");
  }
  d3_selectionPrototype.classed = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") {
        var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
        if (value = node.classList) {
          while (++i < n) if (!value.contains(name[i])) return false;
        } else {
          value = node.getAttribute("class");
          while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
        }
        return true;
      }
      for (value in name) this.each(d3_selection_classed(value, name[value]));
      return this;
    }
    return this.each(d3_selection_classed(name, value));
  };
  function d3_selection_classedRe(name) {
    return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
  }
  function d3_selection_classes(name) {
    return (name + "").trim().split(/^|\s+/);
  }
  function d3_selection_classed(name, value) {
    name = d3_selection_classes(name).map(d3_selection_classedName);
    var n = name.length;
    function classedConstant() {
      var i = -1;
      while (++i < n) name[i](this, value);
    }
    function classedFunction() {
      var i = -1, x = value.apply(this, arguments);
      while (++i < n) name[i](this, x);
    }
    return typeof value === "function" ? classedFunction : classedConstant;
  }
  function d3_selection_classedName(name) {
    var re = d3_selection_classedRe(name);
    return function(node, value) {
      if (c = node.classList) return value ? c.add(name) : c.remove(name);
      var c = node.getAttribute("class") || "";
      if (value) {
        re.lastIndex = 0;
        if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
      } else {
        node.setAttribute("class", d3_collapse(c.replace(re, " ")));
      }
    };
  }
  d3_selectionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
        return this;
      }
      if (n < 2) {
        var node = this.node();
        return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
      }
      priority = "";
    }
    return this.each(d3_selection_style(name, value, priority));
  };
  function d3_selection_style(name, value, priority) {
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleConstant() {
      this.style.setProperty(name, value, priority);
    }
    function styleFunction() {
      var x = value.apply(this, arguments);
      if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
    }
    return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
  }
  d3_selectionPrototype.property = function(name, value) {
    if (arguments.length < 2) {
      if (typeof name === "string") return this.node()[name];
      for (value in name) this.each(d3_selection_property(value, name[value]));
      return this;
    }
    return this.each(d3_selection_property(name, value));
  };
  function d3_selection_property(name, value) {
    function propertyNull() {
      delete this[name];
    }
    function propertyConstant() {
      this[name] = value;
    }
    function propertyFunction() {
      var x = value.apply(this, arguments);
      if (x == null) delete this[name]; else this[name] = x;
    }
    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
  }
  d3_selectionPrototype.text = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.textContent = v == null ? "" : v;
    } : value == null ? function() {
      this.textContent = "";
    } : function() {
      this.textContent = value;
    }) : this.node().textContent;
  };
  d3_selectionPrototype.html = function(value) {
    return arguments.length ? this.each(typeof value === "function" ? function() {
      var v = value.apply(this, arguments);
      this.innerHTML = v == null ? "" : v;
    } : value == null ? function() {
      this.innerHTML = "";
    } : function() {
      this.innerHTML = value;
    }) : this.node().innerHTML;
  };
  d3_selectionPrototype.append = function(name) {
    name = d3_selection_creator(name);
    return this.select(function() {
      return this.appendChild(name.apply(this, arguments));
    });
  };
  function d3_selection_creator(name) {
    function create() {
      var document = this.ownerDocument, namespace = this.namespaceURI;
      return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
    }
    function createNS() {
      return this.ownerDocument.createElementNS(name.space, name.local);
    }
    return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
  }
  d3_selectionPrototype.insert = function(name, before) {
    name = d3_selection_creator(name);
    before = d3_selection_selector(before);
    return this.select(function() {
      return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
    });
  };
  d3_selectionPrototype.remove = function() {
    return this.each(d3_selectionRemove);
  };
  function d3_selectionRemove() {
    var parent = this.parentNode;
    if (parent) parent.removeChild(this);
  }
  d3_selectionPrototype.data = function(value, key) {
    var i = -1, n = this.length, group, node;
    if (!arguments.length) {
      value = new Array(n = (group = this[0]).length);
      while (++i < n) {
        if (node = group[i]) {
          value[i] = node.__data__;
        }
      }
      return value;
    }
    function bind(group, groupData) {
      var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
      if (key) {
        var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
        for (i = -1; ++i < n; ) {
          if (node = group[i]) {
            if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
              exitNodes[i] = node;
            } else {
              nodeByKeyValue.set(keyValue, node);
            }
            keyValues[i] = keyValue;
          }
        }
        for (i = -1; ++i < m; ) {
          if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          } else if (node !== true) {
            updateNodes[i] = node;
            node.__data__ = nodeData;
          }
          nodeByKeyValue.set(keyValue, true);
        }
        for (i = -1; ++i < n; ) {
          if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
            exitNodes[i] = group[i];
          }
        }
      } else {
        for (i = -1; ++i < n0; ) {
          node = group[i];
          nodeData = groupData[i];
          if (node) {
            node.__data__ = nodeData;
            updateNodes[i] = node;
          } else {
            enterNodes[i] = d3_selection_dataNode(nodeData);
          }
        }
        for (;i < m; ++i) {
          enterNodes[i] = d3_selection_dataNode(groupData[i]);
        }
        for (;i < n; ++i) {
          exitNodes[i] = group[i];
        }
      }
      enterNodes.update = updateNodes;
      enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
      enter.push(enterNodes);
      update.push(updateNodes);
      exit.push(exitNodes);
    }
    var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
    if (typeof value === "function") {
      while (++i < n) {
        bind(group = this[i], value.call(group, group.parentNode.__data__, i));
      }
    } else {
      while (++i < n) {
        bind(group = this[i], value);
      }
    }
    update.enter = function() {
      return enter;
    };
    update.exit = function() {
      return exit;
    };
    return update;
  };
  function d3_selection_dataNode(data) {
    return {
      __data__: data
    };
  }
  d3_selectionPrototype.datum = function(value) {
    return arguments.length ? this.property("__data__", value) : this.property("__data__");
  };
  d3_selectionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      subgroup.parentNode = (group = this[j]).parentNode;
      for (var i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_selection(subgroups);
  };
  function d3_selection_filter(selector) {
    return function() {
      return d3_selectMatches(this, selector);
    };
  }
  d3_selectionPrototype.order = function() {
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
        if (node = group[i]) {
          if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
          next = node;
        }
      }
    }
    return this;
  };
  d3_selectionPrototype.sort = function(comparator) {
    comparator = d3_selection_sortComparator.apply(this, arguments);
    for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
    return this.order();
  };
  function d3_selection_sortComparator(comparator) {
    if (!arguments.length) comparator = d3_ascending;
    return function(a, b) {
      return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
    };
  }
  d3_selectionPrototype.each = function(callback) {
    return d3_selection_each(this, function(node, i, j) {
      callback.call(node, node.__data__, i, j);
    });
  };
  function d3_selection_each(groups, callback) {
    for (var j = 0, m = groups.length; j < m; j++) {
      for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
        if (node = group[i]) callback(node, i, j);
      }
    }
    return groups;
  }
  d3_selectionPrototype.call = function(callback) {
    var args = d3_array(arguments);
    callback.apply(args[0] = this, args);
    return this;
  };
  d3_selectionPrototype.empty = function() {
    return !this.node();
  };
  d3_selectionPrototype.node = function() {
    for (var j = 0, m = this.length; j < m; j++) {
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        var node = group[i];
        if (node) return node;
      }
    }
    return null;
  };
  d3_selectionPrototype.size = function() {
    var n = 0;
    d3_selection_each(this, function() {
      ++n;
    });
    return n;
  };
  function d3_selection_enter(selection) {
    d3_subclass(selection, d3_selection_enterPrototype);
    return selection;
  }
  var d3_selection_enterPrototype = [];
  d3.selection.enter = d3_selection_enter;
  d3.selection.enter.prototype = d3_selection_enterPrototype;
  d3_selection_enterPrototype.append = d3_selectionPrototype.append;
  d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
  d3_selection_enterPrototype.node = d3_selectionPrototype.node;
  d3_selection_enterPrototype.call = d3_selectionPrototype.call;
  d3_selection_enterPrototype.size = d3_selectionPrototype.size;
  d3_selection_enterPrototype.select = function(selector) {
    var subgroups = [], subgroup, subnode, upgroup, group, node;
    for (var j = -1, m = this.length; ++j < m; ) {
      upgroup = (group = this[j]).update;
      subgroups.push(subgroup = []);
      subgroup.parentNode = group.parentNode;
      for (var i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
          subnode.__data__ = node.__data__;
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_selection(subgroups);
  };
  d3_selection_enterPrototype.insert = function(name, before) {
    if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
    return d3_selectionPrototype.insert.call(this, name, before);
  };
  function d3_selection_enterInsertBefore(enter) {
    var i0, j0;
    return function(d, i, j) {
      var group = enter[j].update, n = group.length, node;
      if (j != j0) j0 = j, i0 = 0;
      if (i >= i0) i0 = i + 1;
      while (!(node = group[i0]) && ++i0 < n) ;
      return node;
    };
  }
  d3.select = function(node) {
    var group;
    if (typeof node === "string") {
      group = [ d3_select(node, d3_document) ];
      group.parentNode = d3_document.documentElement;
    } else {
      group = [ node ];
      group.parentNode = d3_documentElement(node);
    }
    return d3_selection([ group ]);
  };
  d3.selectAll = function(nodes) {
    var group;
    if (typeof nodes === "string") {
      group = d3_array(d3_selectAll(nodes, d3_document));
      group.parentNode = d3_document.documentElement;
    } else {
      group = d3_array(nodes);
      group.parentNode = null;
    }
    return d3_selection([ group ]);
  };
  d3_selectionPrototype.on = function(type, listener, capture) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof type !== "string") {
        if (n < 2) listener = false;
        for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
        return this;
      }
      if (n < 2) return (n = this.node()["__on" + type]) && n._;
      capture = false;
    }
    return this.each(d3_selection_on(type, listener, capture));
  };
  function d3_selection_on(type, listener, capture) {
    var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
    if (i > 0) type = type.slice(0, i);
    var filter = d3_selection_onFilters.get(type);
    if (filter) type = filter, wrap = d3_selection_onFilter;
    function onRemove() {
      var l = this[name];
      if (l) {
        this.removeEventListener(type, l, l.$);
        delete this[name];
      }
    }
    function onAdd() {
      var l = wrap(listener, d3_array(arguments));
      onRemove.call(this);
      this.addEventListener(type, this[name] = l, l.$ = capture);
      l._ = listener;
    }
    function removeAll() {
      var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
      for (var name in this) {
        if (match = name.match(re)) {
          var l = this[name];
          this.removeEventListener(match[1], l, l.$);
          delete this[name];
        }
      }
    }
    return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
  }
  var d3_selection_onFilters = d3.map({
    mouseenter: "mouseover",
    mouseleave: "mouseout"
  });
  if (d3_document) {
    d3_selection_onFilters.forEach(function(k) {
      if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
    });
  }
  function d3_selection_onListener(listener, argumentz) {
    return function(e) {
      var o = d3.event;
      d3.event = e;
      argumentz[0] = this.__data__;
      try {
        listener.apply(this, argumentz);
      } finally {
        d3.event = o;
      }
    };
  }
  function d3_selection_onFilter(listener, argumentz) {
    var l = d3_selection_onListener(listener, argumentz);
    return function(e) {
      var target = this, related = e.relatedTarget;
      if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
        l.call(target, e);
      }
    };
  }
  var d3_event_dragSelect, d3_event_dragId = 0;
  function d3_event_dragSuppress(node) {
    var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
    if (d3_event_dragSelect == null) {
      d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
    }
    if (d3_event_dragSelect) {
      var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
      style[d3_event_dragSelect] = "none";
    }
    return function(suppressClick) {
      w.on(name, null);
      if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
      if (suppressClick) {
        var off = function() {
          w.on(click, null);
        };
        w.on(click, function() {
          d3_eventPreventDefault();
          off();
        }, true);
        setTimeout(off, 0);
      }
    };
  }
  d3.mouse = function(container) {
    return d3_mousePoint(container, d3_eventSource());
  };
  var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
  function d3_mousePoint(container, e) {
    if (e.changedTouches) e = e.changedTouches[0];
    var svg = container.ownerSVGElement || container;
    if (svg.createSVGPoint) {
      var point = svg.createSVGPoint();
      if (d3_mouse_bug44083 < 0) {
        var window = d3_window(container);
        if (window.scrollX || window.scrollY) {
          svg = d3.select("body").append("svg").style({
            position: "absolute",
            top: 0,
            left: 0,
            margin: 0,
            padding: 0,
            border: "none"
          }, "important");
          var ctm = svg[0][0].getScreenCTM();
          d3_mouse_bug44083 = !(ctm.f || ctm.e);
          svg.remove();
        }
      }
      if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, 
      point.y = e.clientY;
      point = point.matrixTransform(container.getScreenCTM().inverse());
      return [ point.x, point.y ];
    }
    var rect = container.getBoundingClientRect();
    return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
  }
  d3.touch = function(container, touches, identifier) {
    if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
    if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
      if ((touch = touches[i]).identifier === identifier) {
        return d3_mousePoint(container, touch);
      }
    }
  };
  d3.behavior.drag = function() {
    var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
    function drag() {
      this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
    }
    function dragstart(id, position, subject, move, end) {
      return function() {
        var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
        if (origin) {
          dragOffset = origin.apply(that, arguments);
          dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
        } else {
          dragOffset = [ 0, 0 ];
        }
        dispatch({
          type: "dragstart"
        });
        function moved() {
          var position1 = position(parent, dragId), dx, dy;
          if (!position1) return;
          dx = position1[0] - position0[0];
          dy = position1[1] - position0[1];
          dragged |= dx | dy;
          position0 = position1;
          dispatch({
            type: "drag",
            x: position1[0] + dragOffset[0],
            y: position1[1] + dragOffset[1],
            dx: dx,
            dy: dy
          });
        }
        function ended() {
          if (!position(parent, dragId)) return;
          dragSubject.on(move + dragName, null).on(end + dragName, null);
          dragRestore(dragged);
          dispatch({
            type: "dragend"
          });
        }
      };
    }
    drag.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return drag;
    };
    return d3.rebind(drag, event, "on");
  };
  function d3_behavior_dragTouchId() {
    return d3.event.changedTouches[0].identifier;
  }
  d3.touches = function(container, touches) {
    if (arguments.length < 2) touches = d3_eventSource().touches;
    return touches ? d3_array(touches).map(function(touch) {
      var point = d3_mousePoint(container, touch);
      point.identifier = touch.identifier;
      return point;
    }) : [];
  };
  var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
  function d3_sgn(x) {
    return x > 0 ? 1 : x < 0 ? -1 : 0;
  }
  function d3_cross2d(a, b, c) {
    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
  }
  function d3_acos(x) {
    return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  }
  function d3_asin(x) {
    return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  }
  function d3_sinh(x) {
    return ((x = Math.exp(x)) - 1 / x) / 2;
  }
  function d3_cosh(x) {
    return ((x = Math.exp(x)) + 1 / x) / 2;
  }
  function d3_tanh(x) {
    return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  }
  function d3_haversin(x) {
    return (x = Math.sin(x / 2)) * x;
  }
  var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
  d3.interpolateZoom = function(p0, p1) {
    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
    if (d2 < ε2) {
      S = Math.log(w1 / w0) / ρ;
      i = function(t) {
        return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
      };
    } else {
      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
      S = (r1 - r0) / ρ;
      i = function(t) {
        var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
        return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
      };
    }
    i.duration = S * 1e3;
    return i;
  };
  d3.behavior.zoom = function() {
    var view = {
      x: 0,
      y: 0,
      k: 1
    }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
    if (!d3_behavior_zoomWheel) {
      d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
      }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
        return d3.event.wheelDelta;
      }, "mousewheel") : (d3_behavior_zoomDelta = function() {
        return -d3.event.detail;
      }, "MozMousePixelScroll");
    }
    function zoom(g) {
      g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
    }
    zoom.event = function(g) {
      g.each(function() {
        var dispatch = event.of(this, arguments), view1 = view;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.zoom", function() {
            view = this.__chart__ || {
              x: 0,
              y: 0,
              k: 1
            };
            zoomstarted(dispatch);
          }).tween("zoom:zoom", function() {
            var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
            return function(t) {
              var l = i(t), k = dx / l[2];
              this.__chart__ = view = {
                x: cx - l[0] * k,
                y: cy - l[1] * k,
                k: k
              };
              zoomed(dispatch);
            };
          }).each("interrupt.zoom", function() {
            zoomended(dispatch);
          }).each("end.zoom", function() {
            zoomended(dispatch);
          });
        } else {
          this.__chart__ = view;
          zoomstarted(dispatch);
          zoomed(dispatch);
          zoomended(dispatch);
        }
      });
    };
    zoom.translate = function(_) {
      if (!arguments.length) return [ view.x, view.y ];
      view = {
        x: +_[0],
        y: +_[1],
        k: view.k
      };
      rescale();
      return zoom;
    };
    zoom.scale = function(_) {
      if (!arguments.length) return view.k;
      view = {
        x: view.x,
        y: view.y,
        k: null
      };
      scaleTo(+_);
      rescale();
      return zoom;
    };
    zoom.scaleExtent = function(_) {
      if (!arguments.length) return scaleExtent;
      scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.center = function(_) {
      if (!arguments.length) return center;
      center = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.size = function(_) {
      if (!arguments.length) return size;
      size = _ && [ +_[0], +_[1] ];
      return zoom;
    };
    zoom.duration = function(_) {
      if (!arguments.length) return duration;
      duration = +_;
      return zoom;
    };
    zoom.x = function(z) {
      if (!arguments.length) return x1;
      x1 = z;
      x0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    zoom.y = function(z) {
      if (!arguments.length) return y1;
      y1 = z;
      y0 = z.copy();
      view = {
        x: 0,
        y: 0,
        k: 1
      };
      return zoom;
    };
    function location(p) {
      return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
    }
    function point(l) {
      return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
    }
    function scaleTo(s) {
      view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
    }
    function translateTo(p, l) {
      l = point(l);
      view.x += p[0] - l[0];
      view.y += p[1] - l[1];
    }
    function zoomTo(that, p, l, k) {
      that.__chart__ = {
        x: view.x,
        y: view.y,
        k: view.k
      };
      scaleTo(Math.pow(2, k));
      translateTo(center0 = p, l);
      that = d3.select(that);
      if (duration > 0) that = that.transition().duration(duration);
      that.call(zoom.event);
    }
    function rescale() {
      if (x1) x1.domain(x0.range().map(function(x) {
        return (x - view.x) / view.k;
      }).map(x0.invert));
      if (y1) y1.domain(y0.range().map(function(y) {
        return (y - view.y) / view.k;
      }).map(y0.invert));
    }
    function zoomstarted(dispatch) {
      if (!zooming++) dispatch({
        type: "zoomstart"
      });
    }
    function zoomed(dispatch) {
      rescale();
      dispatch({
        type: "zoom",
        scale: view.k,
        translate: [ view.x, view.y ]
      });
    }
    function zoomended(dispatch) {
      if (!--zooming) dispatch({
        type: "zoomend"
      }), center0 = null;
    }
    function mousedowned() {
      var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
      d3_selection_interrupt.call(that);
      zoomstarted(dispatch);
      function moved() {
        dragged = 1;
        translateTo(d3.mouse(that), location0);
        zoomed(dispatch);
      }
      function ended() {
        subject.on(mousemove, null).on(mouseup, null);
        dragRestore(dragged);
        zoomended(dispatch);
      }
    }
    function touchstarted() {
      var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
      started();
      zoomstarted(dispatch);
      subject.on(mousedown, null).on(touchstart, started);
      function relocate() {
        var touches = d3.touches(that);
        scale0 = view.k;
        touches.forEach(function(t) {
          if (t.identifier in locations0) locations0[t.identifier] = location(t);
        });
        return touches;
      }
      function started() {
        var target = d3.event.target;
        d3.select(target).on(touchmove, moved).on(touchend, ended);
        targets.push(target);
        var changed = d3.event.changedTouches;
        for (var i = 0, n = changed.length; i < n; ++i) {
          locations0[changed[i].identifier] = null;
        }
        var touches = relocate(), now = Date.now();
        if (touches.length === 1) {
          if (now - touchtime < 500) {
            var p = touches[0];
            zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
            d3_eventPreventDefault();
          }
          touchtime = now;
        } else if (touches.length > 1) {
          var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
          distance0 = dx * dx + dy * dy;
        }
      }
      function moved() {
        var touches = d3.touches(that), p0, l0, p1, l1;
        d3_selection_interrupt.call(that);
        for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
          p1 = touches[i];
          if (l1 = locations0[p1.identifier]) {
            if (l0) break;
            p0 = p1, l0 = l1;
          }
        }
        if (l1) {
          var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
          p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
          l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
          scaleTo(scale1 * scale0);
        }
        touchtime = null;
        translateTo(p0, l0);
        zoomed(dispatch);
      }
      function ended() {
        if (d3.event.touches.length) {
          var changed = d3.event.changedTouches;
          for (var i = 0, n = changed.length; i < n; ++i) {
            delete locations0[changed[i].identifier];
          }
          for (var identifier in locations0) {
            return void relocate();
          }
        }
        d3.selectAll(targets).on(zoomName, null);
        subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
        dragRestore();
        zoomended(dispatch);
      }
    }
    function mousewheeled() {
      var dispatch = event.of(this, arguments);
      if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), 
      translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
      mousewheelTimer = setTimeout(function() {
        mousewheelTimer = null;
        zoomended(dispatch);
      }, 50);
      d3_eventPreventDefault();
      scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
      translateTo(center0, translate0);
      zoomed(dispatch);
    }
    function dblclicked() {
      var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
      zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
    }
    return d3.rebind(zoom, event, "on");
  };
  var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
  d3.color = d3_color;
  function d3_color() {}
  d3_color.prototype.toString = function() {
    return this.rgb() + "";
  };
  d3.hsl = d3_hsl;
  function d3_hsl(h, s, l) {
    return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
  }
  var d3_hslPrototype = d3_hsl.prototype = new d3_color();
  d3_hslPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, this.l / k);
  };
  d3_hslPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_hsl(this.h, this.s, k * this.l);
  };
  d3_hslPrototype.rgb = function() {
    return d3_hsl_rgb(this.h, this.s, this.l);
  };
  function d3_hsl_rgb(h, s, l) {
    var m1, m2;
    h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
    s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
    l = l < 0 ? 0 : l > 1 ? 1 : l;
    m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
    m1 = 2 * l - m2;
    function v(h) {
      if (h > 360) h -= 360; else if (h < 0) h += 360;
      if (h < 60) return m1 + (m2 - m1) * h / 60;
      if (h < 180) return m2;
      if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
      return m1;
    }
    function vv(h) {
      return Math.round(v(h) * 255);
    }
    return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
  }
  d3.hcl = d3_hcl;
  function d3_hcl(h, c, l) {
    return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
  }
  var d3_hclPrototype = d3_hcl.prototype = new d3_color();
  d3_hclPrototype.brighter = function(k) {
    return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.darker = function(k) {
    return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
  };
  d3_hclPrototype.rgb = function() {
    return d3_hcl_lab(this.h, this.c, this.l).rgb();
  };
  function d3_hcl_lab(h, c, l) {
    if (isNaN(h)) h = 0;
    if (isNaN(c)) c = 0;
    return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
  }
  d3.lab = d3_lab;
  function d3_lab(l, a, b) {
    return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
  }
  var d3_lab_K = 18;
  var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
  var d3_labPrototype = d3_lab.prototype = new d3_color();
  d3_labPrototype.brighter = function(k) {
    return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.darker = function(k) {
    return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  };
  d3_labPrototype.rgb = function() {
    return d3_lab_rgb(this.l, this.a, this.b);
  };
  function d3_lab_rgb(l, a, b) {
    var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
    x = d3_lab_xyz(x) * d3_lab_X;
    y = d3_lab_xyz(y) * d3_lab_Y;
    z = d3_lab_xyz(z) * d3_lab_Z;
    return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
  }
  function d3_lab_hcl(l, a, b) {
    return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
  }
  function d3_lab_xyz(x) {
    return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
  }
  function d3_xyz_lab(x) {
    return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
  }
  function d3_xyz_rgb(r) {
    return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
  }
  d3.rgb = d3_rgb;
  function d3_rgb(r, g, b) {
    return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
  }
  function d3_rgbNumber(value) {
    return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
  }
  function d3_rgbString(value) {
    return d3_rgbNumber(value) + "";
  }
  var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
  d3_rgbPrototype.brighter = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    var r = this.r, g = this.g, b = this.b, i = 30;
    if (!r && !g && !b) return new d3_rgb(i, i, i);
    if (r && r < i) r = i;
    if (g && g < i) g = i;
    if (b && b < i) b = i;
    return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
  };
  d3_rgbPrototype.darker = function(k) {
    k = Math.pow(.7, arguments.length ? k : 1);
    return new d3_rgb(k * this.r, k * this.g, k * this.b);
  };
  d3_rgbPrototype.hsl = function() {
    return d3_rgb_hsl(this.r, this.g, this.b);
  };
  d3_rgbPrototype.toString = function() {
    return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
  };
  function d3_rgb_hex(v) {
    return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
  }
  function d3_rgb_parse(format, rgb, hsl) {
    var r = 0, g = 0, b = 0, m1, m2, color;
    m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
    if (m1) {
      m2 = m1[2].split(",");
      switch (m1[1]) {
       case "hsl":
        {
          return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
        }

       case "rgb":
        {
          return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
        }
      }
    }
    if (color = d3_rgb_names.get(format)) {
      return rgb(color.r, color.g, color.b);
    }
    if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
      if (format.length === 4) {
        r = (color & 3840) >> 4;
        r = r >> 4 | r;
        g = color & 240;
        g = g >> 4 | g;
        b = color & 15;
        b = b << 4 | b;
      } else if (format.length === 7) {
        r = (color & 16711680) >> 16;
        g = (color & 65280) >> 8;
        b = color & 255;
      }
    }
    return rgb(r, g, b);
  }
  function d3_rgb_hsl(r, g, b) {
    var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
    if (d) {
      s = l < .5 ? d / (max + min) : d / (2 - max - min);
      if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
      h *= 60;
    } else {
      h = NaN;
      s = l > 0 && l < 1 ? 0 : h;
    }
    return new d3_hsl(h, s, l);
  }
  function d3_rgb_lab(r, g, b) {
    r = d3_rgb_xyz(r);
    g = d3_rgb_xyz(g);
    b = d3_rgb_xyz(b);
    var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
    return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
  }
  function d3_rgb_xyz(r) {
    return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
  }
  function d3_rgb_parseNumber(c) {
    var f = parseFloat(c);
    return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
  }
  var d3_rgb_names = d3.map({
    aliceblue: 15792383,
    antiquewhite: 16444375,
    aqua: 65535,
    aquamarine: 8388564,
    azure: 15794175,
    beige: 16119260,
    bisque: 16770244,
    black: 0,
    blanchedalmond: 16772045,
    blue: 255,
    blueviolet: 9055202,
    brown: 10824234,
    burlywood: 14596231,
    cadetblue: 6266528,
    chartreuse: 8388352,
    chocolate: 13789470,
    coral: 16744272,
    cornflowerblue: 6591981,
    cornsilk: 16775388,
    crimson: 14423100,
    cyan: 65535,
    darkblue: 139,
    darkcyan: 35723,
    darkgoldenrod: 12092939,
    darkgray: 11119017,
    darkgreen: 25600,
    darkgrey: 11119017,
    darkkhaki: 12433259,
    darkmagenta: 9109643,
    darkolivegreen: 5597999,
    darkorange: 16747520,
    darkorchid: 10040012,
    darkred: 9109504,
    darksalmon: 15308410,
    darkseagreen: 9419919,
    darkslateblue: 4734347,
    darkslategray: 3100495,
    darkslategrey: 3100495,
    darkturquoise: 52945,
    darkviolet: 9699539,
    deeppink: 16716947,
    deepskyblue: 49151,
    dimgray: 6908265,
    dimgrey: 6908265,
    dodgerblue: 2003199,
    firebrick: 11674146,
    floralwhite: 16775920,
    forestgreen: 2263842,
    fuchsia: 16711935,
    gainsboro: 14474460,
    ghostwhite: 16316671,
    gold: 16766720,
    goldenrod: 14329120,
    gray: 8421504,
    green: 32768,
    greenyellow: 11403055,
    grey: 8421504,
    honeydew: 15794160,
    hotpink: 16738740,
    indianred: 13458524,
    indigo: 4915330,
    ivory: 16777200,
    khaki: 15787660,
    lavender: 15132410,
    lavenderblush: 16773365,
    lawngreen: 8190976,
    lemonchiffon: 16775885,
    lightblue: 11393254,
    lightcoral: 15761536,
    lightcyan: 14745599,
    lightgoldenrodyellow: 16448210,
    lightgray: 13882323,
    lightgreen: 9498256,
    lightgrey: 13882323,
    lightpink: 16758465,
    lightsalmon: 16752762,
    lightseagreen: 2142890,
    lightskyblue: 8900346,
    lightslategray: 7833753,
    lightslategrey: 7833753,
    lightsteelblue: 11584734,
    lightyellow: 16777184,
    lime: 65280,
    limegreen: 3329330,
    linen: 16445670,
    magenta: 16711935,
    maroon: 8388608,
    mediumaquamarine: 6737322,
    mediumblue: 205,
    mediumorchid: 12211667,
    mediumpurple: 9662683,
    mediumseagreen: 3978097,
    mediumslateblue: 8087790,
    mediumspringgreen: 64154,
    mediumturquoise: 4772300,
    mediumvioletred: 13047173,
    midnightblue: 1644912,
    mintcream: 16121850,
    mistyrose: 16770273,
    moccasin: 16770229,
    navajowhite: 16768685,
    navy: 128,
    oldlace: 16643558,
    olive: 8421376,
    olivedrab: 7048739,
    orange: 16753920,
    orangered: 16729344,
    orchid: 14315734,
    palegoldenrod: 15657130,
    palegreen: 10025880,
    paleturquoise: 11529966,
    palevioletred: 14381203,
    papayawhip: 16773077,
    peachpuff: 16767673,
    peru: 13468991,
    pink: 16761035,
    plum: 14524637,
    powderblue: 11591910,
    purple: 8388736,
    rebeccapurple: 6697881,
    red: 16711680,
    rosybrown: 12357519,
    royalblue: 4286945,
    saddlebrown: 9127187,
    salmon: 16416882,
    sandybrown: 16032864,
    seagreen: 3050327,
    seashell: 16774638,
    sienna: 10506797,
    silver: 12632256,
    skyblue: 8900331,
    slateblue: 6970061,
    slategray: 7372944,
    slategrey: 7372944,
    snow: 16775930,
    springgreen: 65407,
    steelblue: 4620980,
    tan: 13808780,
    teal: 32896,
    thistle: 14204888,
    tomato: 16737095,
    turquoise: 4251856,
    violet: 15631086,
    wheat: 16113331,
    white: 16777215,
    whitesmoke: 16119285,
    yellow: 16776960,
    yellowgreen: 10145074
  });
  d3_rgb_names.forEach(function(key, value) {
    d3_rgb_names.set(key, d3_rgbNumber(value));
  });
  function d3_functor(v) {
    return typeof v === "function" ? v : function() {
      return v;
    };
  }
  d3.functor = d3_functor;
  d3.xhr = d3_xhrType(d3_identity);
  function d3_xhrType(response) {
    return function(url, mimeType, callback) {
      if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, 
      mimeType = null;
      return d3_xhr(url, mimeType, response, callback);
    };
  }
  function d3_xhr(url, mimeType, response, callback) {
    var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
    if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
    "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
      request.readyState > 3 && respond();
    };
    function respond() {
      var status = request.status, result;
      if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
        try {
          result = response.call(xhr, request);
        } catch (e) {
          dispatch.error.call(xhr, e);
          return;
        }
        dispatch.load.call(xhr, result);
      } else {
        dispatch.error.call(xhr, request);
      }
    }
    request.onprogress = function(event) {
      var o = d3.event;
      d3.event = event;
      try {
        dispatch.progress.call(xhr, request);
      } finally {
        d3.event = o;
      }
    };
    xhr.header = function(name, value) {
      name = (name + "").toLowerCase();
      if (arguments.length < 2) return headers[name];
      if (value == null) delete headers[name]; else headers[name] = value + "";
      return xhr;
    };
    xhr.mimeType = function(value) {
      if (!arguments.length) return mimeType;
      mimeType = value == null ? null : value + "";
      return xhr;
    };
    xhr.responseType = function(value) {
      if (!arguments.length) return responseType;
      responseType = value;
      return xhr;
    };
    xhr.response = function(value) {
      response = value;
      return xhr;
    };
    [ "get", "post" ].forEach(function(method) {
      xhr[method] = function() {
        return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
      };
    });
    xhr.send = function(method, data, callback) {
      if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
      request.open(method, url, true);
      if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
      if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
      if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
      if (responseType != null) request.responseType = responseType;
      if (callback != null) xhr.on("error", callback).on("load", function(request) {
        callback(null, request);
      });
      dispatch.beforesend.call(xhr, request);
      request.send(data == null ? null : data);
      return xhr;
    };
    xhr.abort = function() {
      request.abort();
      return xhr;
    };
    d3.rebind(xhr, dispatch, "on");
    return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
  }
  function d3_xhr_fixCallback(callback) {
    return callback.length === 1 ? function(error, request) {
      callback(error == null ? request : null);
    } : callback;
  }
  function d3_xhrHasResponse(request) {
    var type = request.responseType;
    return type && type !== "text" ? request.response : request.responseText;
  }
  d3.dsv = function(delimiter, mimeType) {
    var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
    function dsv(url, row, callback) {
      if (arguments.length < 3) callback = row, row = null;
      var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
      xhr.row = function(_) {
        return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
      };
      return xhr;
    }
    function response(request) {
      return dsv.parse(request.responseText);
    }
    function typedResponse(f) {
      return function(request) {
        return dsv.parse(request.responseText, f);
      };
    }
    dsv.parse = function(text, f) {
      var o;
      return dsv.parseRows(text, function(row, i) {
        if (o) return o(row, i - 1);
        var a = new Function("d", "return {" + row.map(function(name, i) {
          return JSON.stringify(name) + ": d[" + i + "]";
        }).join(",") + "}");
        o = f ? function(row, i) {
          return f(a(row), i);
        } : a;
      });
    };
    dsv.parseRows = function(text, f) {
      var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
      function token() {
        if (I >= N) return EOF;
        if (eol) return eol = false, EOL;
        var j = I;
        if (text.charCodeAt(j) === 34) {
          var i = j;
          while (i++ < N) {
            if (text.charCodeAt(i) === 34) {
              if (text.charCodeAt(i + 1) !== 34) break;
              ++i;
            }
          }
          I = i + 2;
          var c = text.charCodeAt(i + 1);
          if (c === 13) {
            eol = true;
            if (text.charCodeAt(i + 2) === 10) ++I;
          } else if (c === 10) {
            eol = true;
          }
          return text.slice(j + 1, i).replace(/""/g, '"');
        }
        while (I < N) {
          var c = text.charCodeAt(I++), k = 1;
          if (c === 10) eol = true; else if (c === 13) {
            eol = true;
            if (text.charCodeAt(I) === 10) ++I, ++k;
          } else if (c !== delimiterCode) continue;
          return text.slice(j, I - k);
        }
        return text.slice(j);
      }
      while ((t = token()) !== EOF) {
        var a = [];
        while (t !== EOL && t !== EOF) {
          a.push(t);
          t = token();
        }
        if (f && (a = f(a, n++)) == null) continue;
        rows.push(a);
      }
      return rows;
    };
    dsv.format = function(rows) {
      if (Array.isArray(rows[0])) return dsv.formatRows(rows);
      var fieldSet = new d3_Set(), fields = [];
      rows.forEach(function(row) {
        for (var field in row) {
          if (!fieldSet.has(field)) {
            fields.push(fieldSet.add(field));
          }
        }
      });
      return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
        return fields.map(function(field) {
          return formatValue(row[field]);
        }).join(delimiter);
      })).join("\n");
    };
    dsv.formatRows = function(rows) {
      return rows.map(formatRow).join("\n");
    };
    function formatRow(row) {
      return row.map(formatValue).join(delimiter);
    }
    function formatValue(text) {
      return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
    }
    return dsv;
  };
  d3.csv = d3.dsv(",", "text/csv");
  d3.tsv = d3.dsv("	", "text/tab-separated-values");
  var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
    setTimeout(callback, 17);
  };
  d3.timer = function() {
    d3_timer.apply(this, arguments);
  };
  function d3_timer(callback, delay, then) {
    var n = arguments.length;
    if (n < 2) delay = 0;
    if (n < 3) then = Date.now();
    var time = then + delay, timer = {
      c: callback,
      t: time,
      n: null
    };
    if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
    d3_timer_queueTail = timer;
    if (!d3_timer_interval) {
      d3_timer_timeout = clearTimeout(d3_timer_timeout);
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
    return timer;
  }
  function d3_timer_step() {
    var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
    if (delay > 24) {
      if (isFinite(delay)) {
        clearTimeout(d3_timer_timeout);
        d3_timer_timeout = setTimeout(d3_timer_step, delay);
      }
      d3_timer_interval = 0;
    } else {
      d3_timer_interval = 1;
      d3_timer_frame(d3_timer_step);
    }
  }
  d3.timer.flush = function() {
    d3_timer_mark();
    d3_timer_sweep();
  };
  function d3_timer_mark() {
    var now = Date.now(), timer = d3_timer_queueHead;
    while (timer) {
      if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
      timer = timer.n;
    }
    return now;
  }
  function d3_timer_sweep() {
    var t0, t1 = d3_timer_queueHead, time = Infinity;
    while (t1) {
      if (t1.c) {
        if (t1.t < time) time = t1.t;
        t1 = (t0 = t1).n;
      } else {
        t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
      }
    }
    d3_timer_queueTail = t0;
    return time;
  }
  function d3_format_precision(x, p) {
    return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
  }
  d3.round = function(x, n) {
    return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
  };
  var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
  d3.formatPrefix = function(value, precision) {
    var i = 0;
    if (value = +value) {
      if (value < 0) value *= -1;
      if (precision) value = d3.round(value, d3_format_precision(value, precision));
      i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
      i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
    }
    return d3_formatPrefixes[8 + i / 3];
  };
  function d3_formatPrefix(d, i) {
    var k = Math.pow(10, abs(8 - i) * 3);
    return {
      scale: i > 8 ? function(d) {
        return d / k;
      } : function(d) {
        return d * k;
      },
      symbol: d
    };
  }
  function d3_locale_numberFormat(locale) {
    var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
      var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
      while (i > 0 && g > 0) {
        if (length + g + 1 > width) g = Math.max(1, width - length);
        t.push(value.substring(i -= g, i + g));
        if ((length += g + 1) > width) break;
        g = locale_grouping[j = (j + 1) % locale_grouping.length];
      }
      return t.reverse().join(locale_thousands);
    } : d3_identity;
    return function(specifier) {
      var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
      if (precision) precision = +precision.substring(1);
      if (zfill || fill === "0" && align === "=") {
        zfill = fill = "0";
        align = "=";
      }
      switch (type) {
       case "n":
        comma = true;
        type = "g";
        break;

       case "%":
        scale = 100;
        suffix = "%";
        type = "f";
        break;

       case "p":
        scale = 100;
        suffix = "%";
        type = "r";
        break;

       case "b":
       case "o":
       case "x":
       case "X":
        if (symbol === "#") prefix = "0" + type.toLowerCase();

       case "c":
        exponent = false;

       case "d":
        integer = true;
        precision = 0;
        break;

       case "s":
        scale = -1;
        type = "r";
        break;
      }
      if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1];
      if (type == "r" && !precision) type = "g";
      if (precision != null) {
        if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision));
      }
      type = d3_format_types.get(type) || d3_format_typeDefault;
      var zcomma = zfill && comma;
      return function(value) {
        var fullSuffix = suffix;
        if (integer && value % 1) return "";
        var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
        if (scale < 0) {
          var unit = d3.formatPrefix(value, precision);
          value = unit.scale(value);
          fullSuffix = unit.symbol + suffix;
        } else {
          value *= scale;
        }
        value = type(value, precision);
        var i = value.lastIndexOf("."), before, after;
        if (i < 0) {
          var j = exponent ? value.lastIndexOf("e") : -1;
          if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
        } else {
          before = value.substring(0, i);
          after = locale_decimal + value.substring(i + 1);
        }
        if (!zfill && comma) before = formatGroup(before, Infinity);
        var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
        if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
        negative += prefix;
        value = before + after;
        return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix;
      };
    };
  }
  var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
  var d3_format_types = d3.map({
    b: function(x) {
      return x.toString(2);
    },
    c: function(x) {
      return String.fromCharCode(x);
    },
    o: function(x) {
      return x.toString(8);
    },
    x: function(x) {
      return x.toString(16);
    },
    X: function(x) {
      return x.toString(16).toUpperCase();
    },
    g: function(x, p) {
      return x.toPrecision(p);
    },
    e: function(x, p) {
      return x.toExponential(p);
    },
    f: function(x, p) {
      return x.toFixed(p);
    },
    r: function(x, p) {
      return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
    }
  });
  function d3_format_typeDefault(x) {
    return x + "";
  }
  var d3_time = d3.time = {}, d3_date = Date;
  function d3_date_utc() {
    this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
  }
  d3_date_utc.prototype = {
    getDate: function() {
      return this._.getUTCDate();
    },
    getDay: function() {
      return this._.getUTCDay();
    },
    getFullYear: function() {
      return this._.getUTCFullYear();
    },
    getHours: function() {
      return this._.getUTCHours();
    },
    getMilliseconds: function() {
      return this._.getUTCMilliseconds();
    },
    getMinutes: function() {
      return this._.getUTCMinutes();
    },
    getMonth: function() {
      return this._.getUTCMonth();
    },
    getSeconds: function() {
      return this._.getUTCSeconds();
    },
    getTime: function() {
      return this._.getTime();
    },
    getTimezoneOffset: function() {
      return 0;
    },
    valueOf: function() {
      return this._.valueOf();
    },
    setDate: function() {
      d3_time_prototype.setUTCDate.apply(this._, arguments);
    },
    setDay: function() {
      d3_time_prototype.setUTCDay.apply(this._, arguments);
    },
    setFullYear: function() {
      d3_time_prototype.setUTCFullYear.apply(this._, arguments);
    },
    setHours: function() {
      d3_time_prototype.setUTCHours.apply(this._, arguments);
    },
    setMilliseconds: function() {
      d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
    },
    setMinutes: function() {
      d3_time_prototype.setUTCMinutes.apply(this._, arguments);
    },
    setMonth: function() {
      d3_time_prototype.setUTCMonth.apply(this._, arguments);
    },
    setSeconds: function() {
      d3_time_prototype.setUTCSeconds.apply(this._, arguments);
    },
    setTime: function() {
      d3_time_prototype.setTime.apply(this._, arguments);
    }
  };
  var d3_time_prototype = Date.prototype;
  function d3_time_interval(local, step, number) {
    function round(date) {
      var d0 = local(date), d1 = offset(d0, 1);
      return date - d0 < d1 - date ? d0 : d1;
    }
    function ceil(date) {
      step(date = local(new d3_date(date - 1)), 1);
      return date;
    }
    function offset(date, k) {
      step(date = new d3_date(+date), k);
      return date;
    }
    function range(t0, t1, dt) {
      var time = ceil(t0), times = [];
      if (dt > 1) {
        while (time < t1) {
          if (!(number(time) % dt)) times.push(new Date(+time));
          step(time, 1);
        }
      } else {
        while (time < t1) times.push(new Date(+time)), step(time, 1);
      }
      return times;
    }
    function range_utc(t0, t1, dt) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = t0;
        return range(utc, t1, dt);
      } finally {
        d3_date = Date;
      }
    }
    local.floor = local;
    local.round = round;
    local.ceil = ceil;
    local.offset = offset;
    local.range = range;
    var utc = local.utc = d3_time_interval_utc(local);
    utc.floor = utc;
    utc.round = d3_time_interval_utc(round);
    utc.ceil = d3_time_interval_utc(ceil);
    utc.offset = d3_time_interval_utc(offset);
    utc.range = range_utc;
    return local;
  }
  function d3_time_interval_utc(method) {
    return function(date, k) {
      try {
        d3_date = d3_date_utc;
        var utc = new d3_date_utc();
        utc._ = date;
        return method(utc, k)._;
      } finally {
        d3_date = Date;
      }
    };
  }
  d3_time.year = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setMonth(0, 1);
    return date;
  }, function(date, offset) {
    date.setFullYear(date.getFullYear() + offset);
  }, function(date) {
    return date.getFullYear();
  });
  d3_time.years = d3_time.year.range;
  d3_time.years.utc = d3_time.year.utc.range;
  d3_time.day = d3_time_interval(function(date) {
    var day = new d3_date(2e3, 0);
    day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
    return day;
  }, function(date, offset) {
    date.setDate(date.getDate() + offset);
  }, function(date) {
    return date.getDate() - 1;
  });
  d3_time.days = d3_time.day.range;
  d3_time.days.utc = d3_time.day.utc.range;
  d3_time.dayOfYear = function(date) {
    var year = d3_time.year(date);
    return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
  };
  [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
    i = 7 - i;
    var interval = d3_time[day] = d3_time_interval(function(date) {
      (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
      return date;
    }, function(date, offset) {
      date.setDate(date.getDate() + Math.floor(offset) * 7);
    }, function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
    });
    d3_time[day + "s"] = interval.range;
    d3_time[day + "s"].utc = interval.utc.range;
    d3_time[day + "OfYear"] = function(date) {
      var day = d3_time.year(date).getDay();
      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
    };
  });
  d3_time.week = d3_time.sunday;
  d3_time.weeks = d3_time.sunday.range;
  d3_time.weeks.utc = d3_time.sunday.utc.range;
  d3_time.weekOfYear = d3_time.sundayOfYear;
  function d3_locale_timeFormat(locale) {
    var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
    function d3_time_format(template) {
      var n = template.length;
      function format(date) {
        var string = [], i = -1, j = 0, c, p, f;
        while (++i < n) {
          if (template.charCodeAt(i) === 37) {
            string.push(template.slice(j, i));
            if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
            if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
            string.push(c);
            j = i + 1;
          }
        }
        string.push(template.slice(j, i));
        return string.join("");
      }
      format.parse = function(string) {
        var d = {
          y: 1900,
          m: 0,
          d: 1,
          H: 0,
          M: 0,
          S: 0,
          L: 0,
          Z: null
        }, i = d3_time_parse(d, template, string, 0);
        if (i != string.length) return null;
        if ("p" in d) d.H = d.H % 12 + d.p * 12;
        var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
        if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
          if (!("w" in d)) d.w = "W" in d ? 1 : 0;
          date.setFullYear(d.y, 0, 1);
          date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
        } else date.setFullYear(d.y, d.m, d.d);
        date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
        return localZ ? date._ : date;
      };
      format.toString = function() {
        return template;
      };
      return format;
    }
    function d3_time_parse(date, template, string, j) {
      var c, p, t, i = 0, n = template.length, m = string.length;
      while (i < n) {
        if (j >= m) return -1;
        c = template.charCodeAt(i++);
        if (c === 37) {
          t = template.charAt(i++);
          p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
          if (!p || (j = p(date, string, j)) < 0) return -1;
        } else if (c != string.charCodeAt(j++)) {
          return -1;
        }
      }
      return j;
    }
    d3_time_format.utc = function(template) {
      var local = d3_time_format(template);
      function format(date) {
        try {
          d3_date = d3_date_utc;
          var utc = new d3_date();
          utc._ = date;
          return local(utc);
        } finally {
          d3_date = Date;
        }
      }
      format.parse = function(string) {
        try {
          d3_date = d3_date_utc;
          var date = local.parse(string);
          return date && date._;
        } finally {
          d3_date = Date;
        }
      };
      format.toString = local.toString;
      return format;
    };
    d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
    var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
    locale_periods.forEach(function(p, i) {
      d3_time_periodLookup.set(p.toLowerCase(), i);
    });
    var d3_time_formats = {
      a: function(d) {
        return locale_shortDays[d.getDay()];
      },
      A: function(d) {
        return locale_days[d.getDay()];
      },
      b: function(d) {
        return locale_shortMonths[d.getMonth()];
      },
      B: function(d) {
        return locale_months[d.getMonth()];
      },
      c: d3_time_format(locale_dateTime),
      d: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      e: function(d, p) {
        return d3_time_formatPad(d.getDate(), p, 2);
      },
      H: function(d, p) {
        return d3_time_formatPad(d.getHours(), p, 2);
      },
      I: function(d, p) {
        return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
      },
      j: function(d, p) {
        return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
      },
      L: function(d, p) {
        return d3_time_formatPad(d.getMilliseconds(), p, 3);
      },
      m: function(d, p) {
        return d3_time_formatPad(d.getMonth() + 1, p, 2);
      },
      M: function(d, p) {
        return d3_time_formatPad(d.getMinutes(), p, 2);
      },
      p: function(d) {
        return locale_periods[+(d.getHours() >= 12)];
      },
      S: function(d, p) {
        return d3_time_formatPad(d.getSeconds(), p, 2);
      },
      U: function(d, p) {
        return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
      },
      w: function(d) {
        return d.getDay();
      },
      W: function(d, p) {
        return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
      },
      x: d3_time_format(locale_date),
      X: d3_time_format(locale_time),
      y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 100, p, 2);
      },
      Y: function(d, p) {
        return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
      },
      Z: d3_time_zone,
      "%": function() {
        return "%";
      }
    };
    var d3_time_parsers = {
      a: d3_time_parseWeekdayAbbrev,
      A: d3_time_parseWeekday,
      b: d3_time_parseMonthAbbrev,
      B: d3_time_parseMonth,
      c: d3_time_parseLocaleFull,
      d: d3_time_parseDay,
      e: d3_time_parseDay,
      H: d3_time_parseHour24,
      I: d3_time_parseHour24,
      j: d3_time_parseDayOfYear,
      L: d3_time_parseMilliseconds,
      m: d3_time_parseMonthNumber,
      M: d3_time_parseMinutes,
      p: d3_time_parseAmPm,
      S: d3_time_parseSeconds,
      U: d3_time_parseWeekNumberSunday,
      w: d3_time_parseWeekdayNumber,
      W: d3_time_parseWeekNumberMonday,
      x: d3_time_parseLocaleDate,
      X: d3_time_parseLocaleTime,
      y: d3_time_parseYear,
      Y: d3_time_parseFullYear,
      Z: d3_time_parseZone,
      "%": d3_time_parseLiteralPercent
    };
    function d3_time_parseWeekdayAbbrev(date, string, i) {
      d3_time_dayAbbrevRe.lastIndex = 0;
      var n = d3_time_dayAbbrevRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseWeekday(date, string, i) {
      d3_time_dayRe.lastIndex = 0;
      var n = d3_time_dayRe.exec(string.slice(i));
      return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonthAbbrev(date, string, i) {
      d3_time_monthAbbrevRe.lastIndex = 0;
      var n = d3_time_monthAbbrevRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseMonth(date, string, i) {
      d3_time_monthRe.lastIndex = 0;
      var n = d3_time_monthRe.exec(string.slice(i));
      return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
    }
    function d3_time_parseLocaleFull(date, string, i) {
      return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
    }
    function d3_time_parseLocaleDate(date, string, i) {
      return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
    }
    function d3_time_parseLocaleTime(date, string, i) {
      return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
    }
    function d3_time_parseAmPm(date, string, i) {
      var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
      return n == null ? -1 : (date.p = n, i);
    }
    return d3_time_format;
  }
  var d3_time_formatPads = {
    "-": "",
    _: " ",
    "0": "0"
  }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
  function d3_time_formatPad(value, fill, width) {
    var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
    return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
  }
  function d3_time_formatRe(names) {
    return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
  }
  function d3_time_formatLookup(names) {
    var map = new d3_Map(), i = -1, n = names.length;
    while (++i < n) map.set(names[i].toLowerCase(), i);
    return map;
  }
  function d3_time_parseWeekdayNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 1));
    return n ? (date.w = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberSunday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.U = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseWeekNumberMonday(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i));
    return n ? (date.W = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseFullYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 4));
    return n ? (date.y = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
  }
  function d3_time_parseZone(date, string, i) {
    return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, 
    i + 5) : -1;
  }
  function d3_time_expandYear(d) {
    return d + (d > 68 ? 1900 : 2e3);
  }
  function d3_time_parseMonthNumber(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
  }
  function d3_time_parseDay(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.d = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseDayOfYear(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.j = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseHour24(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.H = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMinutes(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.M = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseSeconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
    return n ? (date.S = +n[0], i + n[0].length) : -1;
  }
  function d3_time_parseMilliseconds(date, string, i) {
    d3_time_numberRe.lastIndex = 0;
    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
    return n ? (date.L = +n[0], i + n[0].length) : -1;
  }
  function d3_time_zone(d) {
    var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
    return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
  }
  function d3_time_parseLiteralPercent(date, string, i) {
    d3_time_percentRe.lastIndex = 0;
    var n = d3_time_percentRe.exec(string.slice(i, i + 1));
    return n ? i + n[0].length : -1;
  }
  function d3_time_formatMulti(formats) {
    var n = formats.length, i = -1;
    while (++i < n) formats[i][0] = this(formats[i][0]);
    return function(date) {
      var i = 0, f = formats[i];
      while (!f[1](date)) f = formats[++i];
      return f[0](date);
    };
  }
  d3.locale = function(locale) {
    return {
      numberFormat: d3_locale_numberFormat(locale),
      timeFormat: d3_locale_timeFormat(locale)
    };
  };
  var d3_locale_enUS = d3.locale({
    decimal: ".",
    thousands: ",",
    grouping: [ 3 ],
    currency: [ "$", "" ],
    dateTime: "%a %b %e %X %Y",
    date: "%m/%d/%Y",
    time: "%H:%M:%S",
    periods: [ "AM", "PM" ],
    days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
    shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
    months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
    shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
  });
  d3.format = d3_locale_enUS.numberFormat;
  d3.geo = {};
  function d3_adder() {}
  d3_adder.prototype = {
    s: 0,
    t: 0,
    add: function(y) {
      d3_adderSum(y, this.t, d3_adderTemp);
      d3_adderSum(d3_adderTemp.s, this.s, this);
      if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
    },
    reset: function() {
      this.s = this.t = 0;
    },
    valueOf: function() {
      return this.s;
    }
  };
  var d3_adderTemp = new d3_adder();
  function d3_adderSum(a, b, o) {
    var x = o.s = a + b, bv = x - a, av = x - bv;
    o.t = a - av + (b - bv);
  }
  d3.geo.stream = function(object, listener) {
    if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
      d3_geo_streamObjectType[object.type](object, listener);
    } else {
      d3_geo_streamGeometry(object, listener);
    }
  };
  function d3_geo_streamGeometry(geometry, listener) {
    if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
      d3_geo_streamGeometryType[geometry.type](geometry, listener);
    }
  }
  var d3_geo_streamObjectType = {
    Feature: function(feature, listener) {
      d3_geo_streamGeometry(feature.geometry, listener);
    },
    FeatureCollection: function(object, listener) {
      var features = object.features, i = -1, n = features.length;
      while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
    }
  };
  var d3_geo_streamGeometryType = {
    Sphere: function(object, listener) {
      listener.sphere();
    },
    Point: function(object, listener) {
      object = object.coordinates;
      listener.point(object[0], object[1], object[2]);
    },
    MultiPoint: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
    },
    LineString: function(object, listener) {
      d3_geo_streamLine(object.coordinates, listener, 0);
    },
    MultiLineString: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
    },
    Polygon: function(object, listener) {
      d3_geo_streamPolygon(object.coordinates, listener);
    },
    MultiPolygon: function(object, listener) {
      var coordinates = object.coordinates, i = -1, n = coordinates.length;
      while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
    },
    GeometryCollection: function(object, listener) {
      var geometries = object.geometries, i = -1, n = geometries.length;
      while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
    }
  };
  function d3_geo_streamLine(coordinates, listener, closed) {
    var i = -1, n = coordinates.length - closed, coordinate;
    listener.lineStart();
    while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
    listener.lineEnd();
  }
  function d3_geo_streamPolygon(coordinates, listener) {
    var i = -1, n = coordinates.length;
    listener.polygonStart();
    while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
    listener.polygonEnd();
  }
  d3.geo.area = function(object) {
    d3_geo_areaSum = 0;
    d3.geo.stream(object, d3_geo_area);
    return d3_geo_areaSum;
  };
  var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
  var d3_geo_area = {
    sphere: function() {
      d3_geo_areaSum += 4 * π;
    },
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_areaRingSum.reset();
      d3_geo_area.lineStart = d3_geo_areaRingStart;
    },
    polygonEnd: function() {
      var area = 2 * d3_geo_areaRingSum;
      d3_geo_areaSum += area < 0 ? 4 * π + area : area;
      d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
    }
  };
  function d3_geo_areaRingStart() {
    var λ00, φ00, λ0, cosφ0, sinφ0;
    d3_geo_area.point = function(λ, φ) {
      d3_geo_area.point = nextPoint;
      λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4), 
      sinφ0 = Math.sin(φ);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      φ = φ * d3_radians / 2 + π / 4;
      var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ);
      d3_geo_areaRingSum.add(Math.atan2(v, u));
      λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
    }
    d3_geo_area.lineEnd = function() {
      nextPoint(λ00, φ00);
    };
  }
  function d3_geo_cartesian(spherical) {
    var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
    return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
  }
  function d3_geo_cartesianDot(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  }
  function d3_geo_cartesianCross(a, b) {
    return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
  }
  function d3_geo_cartesianAdd(a, b) {
    a[0] += b[0];
    a[1] += b[1];
    a[2] += b[2];
  }
  function d3_geo_cartesianScale(vector, k) {
    return [ vector[0] * k, vector[1] * k, vector[2] * k ];
  }
  function d3_geo_cartesianNormalize(d) {
    var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
    d[0] /= l;
    d[1] /= l;
    d[2] /= l;
  }
  function d3_geo_spherical(cartesian) {
    return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
  }
  function d3_geo_sphericalEqual(a, b) {
    return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
  }
  d3.geo.bounds = function() {
    var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
    var bound = {
      point: point,
      lineStart: lineStart,
      lineEnd: lineEnd,
      polygonStart: function() {
        bound.point = ringPoint;
        bound.lineStart = ringStart;
        bound.lineEnd = ringEnd;
        dλSum = 0;
        d3_geo_area.polygonStart();
      },
      polygonEnd: function() {
        d3_geo_area.polygonEnd();
        bound.point = point;
        bound.lineStart = lineStart;
        bound.lineEnd = lineEnd;
        if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
        range[0] = λ0, range[1] = λ1;
      }
    };
    function point(λ, φ) {
      ranges.push(range = [ λ0 = λ, λ1 = λ ]);
      if (φ < φ0) φ0 = φ;
      if (φ > φ1) φ1 = φ;
    }
    function linePoint(λ, φ) {
      var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
      if (p0) {
        var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
        d3_geo_cartesianNormalize(inflection);
        inflection = d3_geo_spherical(inflection);
        var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
        if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = inflection[1] * d3_degrees;
          if (φi > φ1) φ1 = φi;
        } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
          var φi = -inflection[1] * d3_degrees;
          if (φi < φ0) φ0 = φi;
        } else {
          if (φ < φ0) φ0 = φ;
          if (φ > φ1) φ1 = φ;
        }
        if (antimeridian) {
          if (λ < λ_) {
            if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
          } else {
            if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
          }
        } else {
          if (λ1 >= λ0) {
            if (λ < λ0) λ0 = λ;
            if (λ > λ1) λ1 = λ;
          } else {
            if (λ > λ_) {
              if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
            } else {
              if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
            }
          }
        }
      } else {
        point(λ, φ);
      }
      p0 = p, λ_ = λ;
    }
    function lineStart() {
      bound.point = linePoint;
    }
    function lineEnd() {
      range[0] = λ0, range[1] = λ1;
      bound.point = point;
      p0 = null;
    }
    function ringPoint(λ, φ) {
      if (p0) {
        var dλ = λ - λ_;
        dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
      } else λ__ = λ, φ__ = φ;
      d3_geo_area.point(λ, φ);
      linePoint(λ, φ);
    }
    function ringStart() {
      d3_geo_area.lineStart();
    }
    function ringEnd() {
      ringPoint(λ__, φ__);
      d3_geo_area.lineEnd();
      if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
      range[0] = λ0, range[1] = λ1;
      p0 = null;
    }
    function angle(λ0, λ1) {
      return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
    }
    function compareRanges(a, b) {
      return a[0] - b[0];
    }
    function withinRange(x, range) {
      return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
    }
    return function(feature) {
      φ1 = λ1 = -(λ0 = φ0 = Infinity);
      ranges = [];
      d3.geo.stream(feature, bound);
      var n = ranges.length;
      if (n) {
        ranges.sort(compareRanges);
        for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
          b = ranges[i];
          if (withinRange(b[0], a) || withinRange(b[1], a)) {
            if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
            if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
          } else {
            merged.push(a = b);
          }
        }
        var best = -Infinity, dλ;
        for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
          b = merged[i];
          if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
        }
      }
      ranges = range = null;
      return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
    };
  }();
  d3.geo.centroid = function(object) {
    d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
    d3.geo.stream(object, d3_geo_centroid);
    var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
    if (m < ε2) {
      x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
      if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
      m = x * x + y * y + z * z;
      if (m < ε2) return [ NaN, NaN ];
    }
    return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
  };
  var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
  var d3_geo_centroid = {
    sphere: d3_noop,
    point: d3_geo_centroidPoint,
    lineStart: d3_geo_centroidLineStart,
    lineEnd: d3_geo_centroidLineEnd,
    polygonStart: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
    }
  };
  function d3_geo_centroidPoint(λ, φ) {
    λ *= d3_radians;
    var cosφ = Math.cos(φ *= d3_radians);
    d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
  }
  function d3_geo_centroidPointXYZ(x, y, z) {
    ++d3_geo_centroidW0;
    d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
    d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
    d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
  }
  function d3_geo_centroidLineStart() {
    var x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroid.point = nextPoint;
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_centroidLineEnd() {
    d3_geo_centroid.point = d3_geo_centroidPoint;
  }
  function d3_geo_centroidRingStart() {
    var λ00, φ00, x0, y0, z0;
    d3_geo_centroid.point = function(λ, φ) {
      λ00 = λ, φ00 = φ;
      d3_geo_centroid.point = nextPoint;
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians);
      x0 = cosφ * Math.cos(λ);
      y0 = cosφ * Math.sin(λ);
      z0 = Math.sin(φ);
      d3_geo_centroidPointXYZ(x0, y0, z0);
    };
    d3_geo_centroid.lineEnd = function() {
      nextPoint(λ00, φ00);
      d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
      d3_geo_centroid.point = d3_geo_centroidPoint;
    };
    function nextPoint(λ, φ) {
      λ *= d3_radians;
      var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
      d3_geo_centroidX2 += v * cx;
      d3_geo_centroidY2 += v * cy;
      d3_geo_centroidZ2 += v * cz;
      d3_geo_centroidW1 += w;
      d3_geo_centroidX1 += w * (x0 + (x0 = x));
      d3_geo_centroidY1 += w * (y0 + (y0 = y));
      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
      d3_geo_centroidPointXYZ(x0, y0, z0);
    }
  }
  function d3_geo_compose(a, b) {
    function compose(x, y) {
      return x = a(x, y), b(x[0], x[1]);
    }
    if (a.invert && b.invert) compose.invert = function(x, y) {
      return x = b.invert(x, y), x && a.invert(x[0], x[1]);
    };
    return compose;
  }
  function d3_true() {
    return true;
  }
  function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
    var subject = [], clip = [];
    segments.forEach(function(segment) {
      if ((n = segment.length - 1) <= 0) return;
      var n, p0 = segment[0], p1 = segment[n];
      if (d3_geo_sphericalEqual(p0, p1)) {
        listener.lineStart();
        for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
        listener.lineEnd();
        return;
      }
      var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
      a.o = b;
      subject.push(a);
      clip.push(b);
      a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
      b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
      a.o = b;
      subject.push(a);
      clip.push(b);
    });
    clip.sort(compare);
    d3_geo_clipPolygonLinkCircular(subject);
    d3_geo_clipPolygonLinkCircular(clip);
    if (!subject.length) return;
    for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
      clip[i].e = entry = !entry;
    }
    var start = subject[0], points, point;
    while (1) {
      var current = start, isSubject = true;
      while (current.v) if ((current = current.n) === start) return;
      points = current.z;
      listener.lineStart();
      do {
        current.v = current.o.v = true;
        if (current.e) {
          if (isSubject) {
            for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.n.x, 1, listener);
          }
          current = current.n;
        } else {
          if (isSubject) {
            points = current.p.z;
            for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
          } else {
            interpolate(current.x, current.p.x, -1, listener);
          }
          current = current.p;
        }
        current = current.o;
        points = current.z;
        isSubject = !isSubject;
      } while (!current.v);
      listener.lineEnd();
    }
  }
  function d3_geo_clipPolygonLinkCircular(array) {
    if (!(n = array.length)) return;
    var n, i = 0, a = array[0], b;
    while (++i < n) {
      a.n = b = array[i];
      b.p = a;
      a = b;
    }
    a.n = b = array[0];
    b.p = a;
  }
  function d3_geo_clipPolygonIntersection(point, points, other, entry) {
    this.x = point;
    this.z = points;
    this.o = other;
    this.e = entry;
    this.v = false;
    this.n = this.p = null;
  }
  function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
    return function(rotate, listener) {
      var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          clip.point = pointRing;
          clip.lineStart = ringStart;
          clip.lineEnd = ringEnd;
          segments = [];
          polygon = [];
        },
        polygonEnd: function() {
          clip.point = point;
          clip.lineStart = lineStart;
          clip.lineEnd = lineEnd;
          segments = d3.merge(segments);
          var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
          if (segments.length) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
          } else if (clipStartInside) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            interpolate(null, null, 1, listener);
            listener.lineEnd();
          }
          if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
          segments = polygon = null;
        },
        sphere: function() {
          listener.polygonStart();
          listener.lineStart();
          interpolate(null, null, 1, listener);
          listener.lineEnd();
          listener.polygonEnd();
        }
      };
      function point(λ, φ) {
        var point = rotate(λ, φ);
        if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
      }
      function pointLine(λ, φ) {
        var point = rotate(λ, φ);
        line.point(point[0], point[1]);
      }
      function lineStart() {
        clip.point = pointLine;
        line.lineStart();
      }
      function lineEnd() {
        clip.point = point;
        line.lineEnd();
      }
      var segments;
      var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
      function pointRing(λ, φ) {
        ring.push([ λ, φ ]);
        var point = rotate(λ, φ);
        ringListener.point(point[0], point[1]);
      }
      function ringStart() {
        ringListener.lineStart();
        ring = [];
      }
      function ringEnd() {
        pointRing(ring[0][0], ring[0][1]);
        ringListener.lineEnd();
        var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
        ring.pop();
        polygon.push(ring);
        ring = null;
        if (!n) return;
        if (clean & 1) {
          segment = ringSegments[0];
          var n = segment.length - 1, i = -1, point;
          if (n > 0) {
            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
            listener.lineStart();
            while (++i < n) listener.point((point = segment[i])[0], point[1]);
            listener.lineEnd();
          }
          return;
        }
        if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
        segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
      }
      return clip;
    };
  }
  function d3_geo_clipSegmentLength1(segment) {
    return segment.length > 1;
  }
  function d3_geo_clipBufferListener() {
    var lines = [], line;
    return {
      lineStart: function() {
        lines.push(line = []);
      },
      point: function(λ, φ) {
        line.push([ λ, φ ]);
      },
      lineEnd: d3_noop,
      buffer: function() {
        var buffer = lines;
        lines = [];
        line = null;
        return buffer;
      },
      rejoin: function() {
        if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
      }
    };
  }
  function d3_geo_clipSort(a, b) {
    return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
  }
  var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
  function d3_geo_clipAntimeridianLine(listener) {
    var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
    return {
      lineStart: function() {
        listener.lineStart();
        clean = 1;
      },
      point: function(λ1, φ1) {
        var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
        if (abs(dλ - π) < ε) {
          listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          listener.point(λ1, φ0);
          clean = 0;
        } else if (sλ0 !== sλ1 && dλ >= π) {
          if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
          if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
          φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
          listener.point(sλ0, φ0);
          listener.lineEnd();
          listener.lineStart();
          listener.point(sλ1, φ0);
          clean = 0;
        }
        listener.point(λ0 = λ1, φ0 = φ1);
        sλ0 = sλ1;
      },
      lineEnd: function() {
        listener.lineEnd();
        λ0 = φ0 = NaN;
      },
      clean: function() {
        return 2 - clean;
      }
    };
  }
  function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
    var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
    return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
  }
  function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
    var φ;
    if (from == null) {
      φ = direction * halfπ;
      listener.point(-π, φ);
      listener.point(0, φ);
      listener.point(π, φ);
      listener.point(π, 0);
      listener.point(π, -φ);
      listener.point(0, -φ);
      listener.point(-π, -φ);
      listener.point(-π, 0);
      listener.point(-π, φ);
    } else if (abs(from[0] - to[0]) > ε) {
      var s = from[0] < to[0] ? π : -π;
      φ = direction * s / 2;
      listener.point(-s, φ);
      listener.point(0, φ);
      listener.point(s, φ);
    } else {
      listener.point(to[0], to[1]);
    }
  }
  function d3_geo_pointInPolygon(point, polygon) {
    var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
    d3_geo_areaRingSum.reset();
    for (var i = 0, n = polygon.length; i < n; ++i) {
      var ring = polygon[i], m = ring.length;
      if (!m) continue;
      var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
      while (true) {
        if (j === m) j = 0;
        point = ring[j];
        var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ;
        d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ)));
        polarAngle += antimeridian ? dλ + sdλ * τ : dλ;
        if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
          var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
          d3_geo_cartesianNormalize(arc);
          var intersection = d3_geo_cartesianCross(meridianNormal, arc);
          d3_geo_cartesianNormalize(intersection);
          var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
          if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
            winding += antimeridian ^ dλ >= 0 ? 1 : -1;
          }
        }
        if (!j++) break;
        λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
      }
    }
    return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1;
  }
  function d3_geo_clipCircle(radius) {
    var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
    return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
    function visible(λ, φ) {
      return Math.cos(λ) * Math.cos(φ) > cr;
    }
    function clipLine(listener) {
      var point0, c0, v0, v00, clean;
      return {
        lineStart: function() {
          v00 = v0 = false;
          clean = 1;
        },
        point: function(λ, φ) {
          var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
          if (!point0 && (v00 = v0 = v)) listener.lineStart();
          if (v !== v0) {
            point2 = intersect(point0, point1);
            if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
              point1[0] += ε;
              point1[1] += ε;
              v = visible(point1[0], point1[1]);
            }
          }
          if (v !== v0) {
            clean = 0;
            if (v) {
              listener.lineStart();
              point2 = intersect(point1, point0);
              listener.point(point2[0], point2[1]);
            } else {
              point2 = intersect(point0, point1);
              listener.point(point2[0], point2[1]);
              listener.lineEnd();
            }
            point0 = point2;
          } else if (notHemisphere && point0 && smallRadius ^ v) {
            var t;
            if (!(c & c0) && (t = intersect(point1, point0, true))) {
              clean = 0;
              if (smallRadius) {
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
              } else {
                listener.point(t[1][0], t[1][1]);
                listener.lineEnd();
                listener.lineStart();
                listener.point(t[0][0], t[0][1]);
              }
            }
          }
          if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
            listener.point(point1[0], point1[1]);
          }
          point0 = point1, v0 = v, c0 = c;
        },
        lineEnd: function() {
          if (v0) listener.lineEnd();
          point0 = null;
        },
        clean: function() {
          return clean | (v00 && v0) << 1;
        }
      };
    }
    function intersect(a, b, two) {
      var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
      var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
      if (!determinant) return !two && a;
      var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
      d3_geo_cartesianAdd(A, B);
      var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
      if (t2 < 0) return;
      var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
      d3_geo_cartesianAdd(q, A);
      q = d3_geo_spherical(q);
      if (!two) return q;
      var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
      if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
      var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
      if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
      if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
        var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
        d3_geo_cartesianAdd(q1, A);
        return [ q, d3_geo_spherical(q1) ];
      }
    }
    function code(λ, φ) {
      var r = smallRadius ? radius : π - radius, code = 0;
      if (λ < -r) code |= 1; else if (λ > r) code |= 2;
      if (φ < -r) code |= 4; else if (φ > r) code |= 8;
      return code;
    }
  }
  function d3_geom_clipLine(x0, y0, x1, y1) {
    return function(line) {
      var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
      r = x0 - ax;
      if (!dx && r > 0) return;
      r /= dx;
      if (dx < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dx > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = x1 - ax;
      if (!dx && r < 0) return;
      r /= dx;
      if (dx < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dx > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      r = y0 - ay;
      if (!dy && r > 0) return;
      r /= dy;
      if (dy < 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      } else if (dy > 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      }
      r = y1 - ay;
      if (!dy && r < 0) return;
      r /= dy;
      if (dy < 0) {
        if (r > t1) return;
        if (r > t0) t0 = r;
      } else if (dy > 0) {
        if (r < t0) return;
        if (r < t1) t1 = r;
      }
      if (t0 > 0) line.a = {
        x: ax + t0 * dx,
        y: ay + t0 * dy
      };
      if (t1 < 1) line.b = {
        x: ax + t1 * dx,
        y: ay + t1 * dy
      };
      return line;
    };
  }
  var d3_geo_clipExtentMAX = 1e9;
  d3.geo.clipExtent = function() {
    var x0, y0, x1, y1, stream, clip, clipExtent = {
      stream: function(output) {
        if (stream) stream.valid = false;
        stream = clip(output);
        stream.valid = true;
        return stream;
      },
      extent: function(_) {
        if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
        clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
        if (stream) stream.valid = false, stream = null;
        return clipExtent;
      }
    };
    return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
  };
  function d3_geo_clipExtent(x0, y0, x1, y1) {
    return function(listener) {
      var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
      var clip = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          listener = bufferListener;
          segments = [];
          polygon = [];
          clean = true;
        },
        polygonEnd: function() {
          listener = listener_;
          segments = d3.merge(segments);
          var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
          if (inside || visible) {
            listener.polygonStart();
            if (inside) {
              listener.lineStart();
              interpolate(null, null, 1, listener);
              listener.lineEnd();
            }
            if (visible) {
              d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
            }
            listener.polygonEnd();
          }
          segments = polygon = ring = null;
        }
      };
      function insidePolygon(p) {
        var wn = 0, n = polygon.length, y = p[1];
        for (var i = 0; i < n; ++i) {
          for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
            b = v[j];
            if (a[1] <= y) {
              if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
            } else {
              if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
            }
            a = b;
          }
        }
        return wn !== 0;
      }
      function interpolate(from, to, direction, listener) {
        var a = 0, a1 = 0;
        if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
          do {
            listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
          } while ((a = (a + direction + 4) % 4) !== a1);
        } else {
          listener.point(to[0], to[1]);
        }
      }
      function pointVisible(x, y) {
        return x0 <= x && x <= x1 && y0 <= y && y <= y1;
      }
      function point(x, y) {
        if (pointVisible(x, y)) listener.point(x, y);
      }
      var x__, y__, v__, x_, y_, v_, first, clean;
      function lineStart() {
        clip.point = linePoint;
        if (polygon) polygon.push(ring = []);
        first = true;
        v_ = false;
        x_ = y_ = NaN;
      }
      function lineEnd() {
        if (segments) {
          linePoint(x__, y__);
          if (v__ && v_) bufferListener.rejoin();
          segments.push(bufferListener.buffer());
        }
        clip.point = point;
        if (v_) listener.lineEnd();
      }
      function linePoint(x, y) {
        x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
        y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
        var v = pointVisible(x, y);
        if (polygon) ring.push([ x, y ]);
        if (first) {
          x__ = x, y__ = y, v__ = v;
          first = false;
          if (v) {
            listener.lineStart();
            listener.point(x, y);
          }
        } else {
          if (v && v_) listener.point(x, y); else {
            var l = {
              a: {
                x: x_,
                y: y_
              },
              b: {
                x: x,
                y: y
              }
            };
            if (clipLine(l)) {
              if (!v_) {
                listener.lineStart();
                listener.point(l.a.x, l.a.y);
              }
              listener.point(l.b.x, l.b.y);
              if (!v) listener.lineEnd();
              clean = false;
            } else if (v) {
              listener.lineStart();
              listener.point(x, y);
              clean = false;
            }
          }
        }
        x_ = x, y_ = y, v_ = v;
      }
      return clip;
    };
    function corner(p, direction) {
      return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
    }
    function compare(a, b) {
      return comparePoints(a.x, b.x);
    }
    function comparePoints(a, b) {
      var ca = corner(a, 1), cb = corner(b, 1);
      return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
    }
  }
  function d3_geo_conic(projectAt) {
    var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
    p.parallels = function(_) {
      if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
      return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
    };
    return p;
  }
  function d3_geo_conicEqualArea(φ0, φ1) {
    var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
    function forward(λ, φ) {
      var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
      return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = ρ0 - y;
      return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
    };
    return forward;
  }
  (d3.geo.conicEqualArea = function() {
    return d3_geo_conic(d3_geo_conicEqualArea);
  }).raw = d3_geo_conicEqualArea;
  d3.geo.albers = function() {
    return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
  };
  d3.geo.albersUsa = function() {
    var lower48 = d3.geo.albers();
    var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
    var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
    var point, pointStream = {
      point: function(x, y) {
        point = [ x, y ];
      }
    }, lower48Point, alaskaPoint, hawaiiPoint;
    function albersUsa(coordinates) {
      var x = coordinates[0], y = coordinates[1];
      point = null;
      (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
      return point;
    }
    albersUsa.invert = function(coordinates) {
      var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
      return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
    };
    albersUsa.stream = function(stream) {
      var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
      return {
        point: function(x, y) {
          lower48Stream.point(x, y);
          alaskaStream.point(x, y);
          hawaiiStream.point(x, y);
        },
        sphere: function() {
          lower48Stream.sphere();
          alaskaStream.sphere();
          hawaiiStream.sphere();
        },
        lineStart: function() {
          lower48Stream.lineStart();
          alaskaStream.lineStart();
          hawaiiStream.lineStart();
        },
        lineEnd: function() {
          lower48Stream.lineEnd();
          alaskaStream.lineEnd();
          hawaiiStream.lineEnd();
        },
        polygonStart: function() {
          lower48Stream.polygonStart();
          alaskaStream.polygonStart();
          hawaiiStream.polygonStart();
        },
        polygonEnd: function() {
          lower48Stream.polygonEnd();
          alaskaStream.polygonEnd();
          hawaiiStream.polygonEnd();
        }
      };
    };
    albersUsa.precision = function(_) {
      if (!arguments.length) return lower48.precision();
      lower48.precision(_);
      alaska.precision(_);
      hawaii.precision(_);
      return albersUsa;
    };
    albersUsa.scale = function(_) {
      if (!arguments.length) return lower48.scale();
      lower48.scale(_);
      alaska.scale(_ * .35);
      hawaii.scale(_);
      return albersUsa.translate(lower48.translate());
    };
    albersUsa.translate = function(_) {
      if (!arguments.length) return lower48.translate();
      var k = lower48.scale(), x = +_[0], y = +_[1];
      lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
      alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
      return albersUsa;
    };
    return albersUsa.scale(1070);
  };
  var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
    point: d3_noop,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: function() {
      d3_geo_pathAreaPolygon = 0;
      d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
      d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
    }
  };
  function d3_geo_pathAreaRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathArea.point = function(x, y) {
      d3_geo_pathArea.point = nextPoint;
      x00 = x0 = x, y00 = y0 = y;
    };
    function nextPoint(x, y) {
      d3_geo_pathAreaPolygon += y0 * x - x0 * y;
      x0 = x, y0 = y;
    }
    d3_geo_pathArea.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
  var d3_geo_pathBounds = {
    point: d3_geo_pathBoundsPoint,
    lineStart: d3_noop,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_pathBoundsPoint(x, y) {
    if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
    if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
    if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
    if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
  }
  function d3_geo_pathBuffer() {
    var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointCircle = d3_geo_pathBufferCircle(_);
        return stream;
      },
      result: function() {
        if (buffer.length) {
          var result = buffer.join("");
          buffer = [];
          return result;
        }
      }
    };
    function point(x, y) {
      buffer.push("M", x, ",", y, pointCircle);
    }
    function pointLineStart(x, y) {
      buffer.push("M", x, ",", y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      buffer.push("L", x, ",", y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      buffer.push("Z");
    }
    return stream;
  }
  function d3_geo_pathBufferCircle(radius) {
    return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
  }
  var d3_geo_pathCentroid = {
    point: d3_geo_pathCentroidPoint,
    lineStart: d3_geo_pathCentroidLineStart,
    lineEnd: d3_geo_pathCentroidLineEnd,
    polygonStart: function() {
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
    },
    polygonEnd: function() {
      d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
      d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
    }
  };
  function d3_geo_pathCentroidPoint(x, y) {
    d3_geo_centroidX0 += x;
    d3_geo_centroidY0 += y;
    ++d3_geo_centroidZ0;
  }
  function d3_geo_pathCentroidLineStart() {
    var x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
  }
  function d3_geo_pathCentroidLineEnd() {
    d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
  }
  function d3_geo_pathCentroidRingStart() {
    var x00, y00, x0, y0;
    d3_geo_pathCentroid.point = function(x, y) {
      d3_geo_pathCentroid.point = nextPoint;
      d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
    };
    function nextPoint(x, y) {
      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
      d3_geo_centroidX1 += z * (x0 + x) / 2;
      d3_geo_centroidY1 += z * (y0 + y) / 2;
      d3_geo_centroidZ1 += z;
      z = y0 * x - x0 * y;
      d3_geo_centroidX2 += z * (x0 + x);
      d3_geo_centroidY2 += z * (y0 + y);
      d3_geo_centroidZ2 += z * 3;
      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
    }
    d3_geo_pathCentroid.lineEnd = function() {
      nextPoint(x00, y00);
    };
  }
  function d3_geo_pathContext(context) {
    var pointRadius = 4.5;
    var stream = {
      point: point,
      lineStart: function() {
        stream.point = pointLineStart;
      },
      lineEnd: lineEnd,
      polygonStart: function() {
        stream.lineEnd = lineEndPolygon;
      },
      polygonEnd: function() {
        stream.lineEnd = lineEnd;
        stream.point = point;
      },
      pointRadius: function(_) {
        pointRadius = _;
        return stream;
      },
      result: d3_noop
    };
    function point(x, y) {
      context.moveTo(x + pointRadius, y);
      context.arc(x, y, pointRadius, 0, τ);
    }
    function pointLineStart(x, y) {
      context.moveTo(x, y);
      stream.point = pointLine;
    }
    function pointLine(x, y) {
      context.lineTo(x, y);
    }
    function lineEnd() {
      stream.point = point;
    }
    function lineEndPolygon() {
      context.closePath();
    }
    return stream;
  }
  function d3_geo_resample(project) {
    var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
    function resample(stream) {
      return (maxDepth ? resampleRecursive : resampleNone)(stream);
    }
    function resampleNone(stream) {
      return d3_geo_transformPoint(stream, function(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      });
    }
    function resampleRecursive(stream) {
      var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
      var resample = {
        point: point,
        lineStart: lineStart,
        lineEnd: lineEnd,
        polygonStart: function() {
          stream.polygonStart();
          resample.lineStart = ringStart;
        },
        polygonEnd: function() {
          stream.polygonEnd();
          resample.lineStart = lineStart;
        }
      };
      function point(x, y) {
        x = project(x, y);
        stream.point(x[0], x[1]);
      }
      function lineStart() {
        x0 = NaN;
        resample.point = linePoint;
        stream.lineStart();
      }
      function linePoint(λ, φ) {
        var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
        stream.point(x0, y0);
      }
      function lineEnd() {
        resample.point = point;
        stream.lineEnd();
      }
      function ringStart() {
        lineStart();
        resample.point = ringPoint;
        resample.lineEnd = ringEnd;
      }
      function ringPoint(λ, φ) {
        linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
        resample.point = linePoint;
      }
      function ringEnd() {
        resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
        resample.lineEnd = lineEnd;
        lineEnd();
      }
      return resample;
    }
    function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
      var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
      if (d2 > 4 * δ2 && depth--) {
        var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
        if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
          resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
          stream.point(x2, y2);
          resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
        }
      }
    }
    resample.precision = function(_) {
      if (!arguments.length) return Math.sqrt(δ2);
      maxDepth = (δ2 = _ * _) > 0 && 16;
      return resample;
    };
    return resample;
  }
  d3.geo.path = function() {
    var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
    function path(object) {
      if (object) {
        if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
        if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
        d3.geo.stream(object, cacheStream);
      }
      return contextStream.result();
    }
    path.area = function(object) {
      d3_geo_pathAreaSum = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathArea));
      return d3_geo_pathAreaSum;
    };
    path.centroid = function(object) {
      d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
      d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
      return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
    };
    path.bounds = function(object) {
      d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
      d3.geo.stream(object, projectStream(d3_geo_pathBounds));
      return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
    };
    path.projection = function(_) {
      if (!arguments.length) return projection;
      projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
      return reset();
    };
    path.context = function(_) {
      if (!arguments.length) return context;
      contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
      if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
      return reset();
    };
    path.pointRadius = function(_) {
      if (!arguments.length) return pointRadius;
      pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
      return path;
    };
    function reset() {
      cacheStream = null;
      return path;
    }
    return path.projection(d3.geo.albersUsa()).context(null);
  };
  function d3_geo_pathProjectStream(project) {
    var resample = d3_geo_resample(function(x, y) {
      return project([ x * d3_degrees, y * d3_degrees ]);
    });
    return function(stream) {
      return d3_geo_projectionRadians(resample(stream));
    };
  }
  d3.geo.transform = function(methods) {
    return {
      stream: function(stream) {
        var transform = new d3_geo_transform(stream);
        for (var k in methods) transform[k] = methods[k];
        return transform;
      }
    };
  };
  function d3_geo_transform(stream) {
    this.stream = stream;
  }
  d3_geo_transform.prototype = {
    point: function(x, y) {
      this.stream.point(x, y);
    },
    sphere: function() {
      this.stream.sphere();
    },
    lineStart: function() {
      this.stream.lineStart();
    },
    lineEnd: function() {
      this.stream.lineEnd();
    },
    polygonStart: function() {
      this.stream.polygonStart();
    },
    polygonEnd: function() {
      this.stream.polygonEnd();
    }
  };
  function d3_geo_transformPoint(stream, point) {
    return {
      point: point,
      sphere: function() {
        stream.sphere();
      },
      lineStart: function() {
        stream.lineStart();
      },
      lineEnd: function() {
        stream.lineEnd();
      },
      polygonStart: function() {
        stream.polygonStart();
      },
      polygonEnd: function() {
        stream.polygonEnd();
      }
    };
  }
  d3.geo.projection = d3_geo_projection;
  d3.geo.projectionMutator = d3_geo_projectionMutator;
  function d3_geo_projection(project) {
    return d3_geo_projectionMutator(function() {
      return project;
    })();
  }
  function d3_geo_projectionMutator(projectAt) {
    var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
      x = project(x, y);
      return [ x[0] * k + δx, δy - x[1] * k ];
    }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
    function projection(point) {
      point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
      return [ point[0] * k + δx, δy - point[1] * k ];
    }
    function invert(point) {
      point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
      return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
    }
    projection.stream = function(output) {
      if (stream) stream.valid = false;
      stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
      stream.valid = true;
      return stream;
    };
    projection.clipAngle = function(_) {
      if (!arguments.length) return clipAngle;
      preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
      return invalidate();
    };
    projection.clipExtent = function(_) {
      if (!arguments.length) return clipExtent;
      clipExtent = _;
      postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
      return invalidate();
    };
    projection.scale = function(_) {
      if (!arguments.length) return k;
      k = +_;
      return reset();
    };
    projection.translate = function(_) {
      if (!arguments.length) return [ x, y ];
      x = +_[0];
      y = +_[1];
      return reset();
    };
    projection.center = function(_) {
      if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
      λ = _[0] % 360 * d3_radians;
      φ = _[1] % 360 * d3_radians;
      return reset();
    };
    projection.rotate = function(_) {
      if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
      δλ = _[0] % 360 * d3_radians;
      δφ = _[1] % 360 * d3_radians;
      δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
      return reset();
    };
    d3.rebind(projection, projectResample, "precision");
    function reset() {
      projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
      var center = project(λ, φ);
      δx = x - center[0] * k;
      δy = y + center[1] * k;
      return invalidate();
    }
    function invalidate() {
      if (stream) stream.valid = false, stream = null;
      return projection;
    }
    return function() {
      project = projectAt.apply(this, arguments);
      projection.invert = project.invert && invert;
      return reset();
    };
  }
  function d3_geo_projectionRadians(stream) {
    return d3_geo_transformPoint(stream, function(x, y) {
      stream.point(x * d3_radians, y * d3_radians);
    });
  }
  function d3_geo_equirectangular(λ, φ) {
    return [ λ, φ ];
  }
  (d3.geo.equirectangular = function() {
    return d3_geo_projection(d3_geo_equirectangular);
  }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
  d3.geo.rotation = function(rotate) {
    rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
    function forward(coordinates) {
      coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    }
    forward.invert = function(coordinates) {
      coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
    };
    return forward;
  };
  function d3_geo_identityRotation(λ, φ) {
    return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
  }
  d3_geo_identityRotation.invert = d3_geo_equirectangular;
  function d3_geo_rotation(δλ, δφ, δγ) {
    return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
  }
  function d3_geo_forwardRotationλ(δλ) {
    return function(λ, φ) {
      return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
    };
  }
  function d3_geo_rotationλ(δλ) {
    var rotation = d3_geo_forwardRotationλ(δλ);
    rotation.invert = d3_geo_forwardRotationλ(-δλ);
    return rotation;
  }
  function d3_geo_rotationφγ(δφ, δγ) {
    var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
    function rotation(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
      return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
    }
    rotation.invert = function(λ, φ) {
      var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
      return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
    };
    return rotation;
  }
  d3.geo.circle = function() {
    var origin = [ 0, 0 ], angle, precision = 6, interpolate;
    function circle() {
      var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
      interpolate(null, null, 1, {
        point: function(x, y) {
          ring.push(x = rotate(x, y));
          x[0] *= d3_degrees, x[1] *= d3_degrees;
        }
      });
      return {
        type: "Polygon",
        coordinates: [ ring ]
      };
    }
    circle.origin = function(x) {
      if (!arguments.length) return origin;
      origin = x;
      return circle;
    };
    circle.angle = function(x) {
      if (!arguments.length) return angle;
      interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
      return circle;
    };
    circle.precision = function(_) {
      if (!arguments.length) return precision;
      interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
      return circle;
    };
    return circle.angle(90);
  };
  function d3_geo_circleInterpolate(radius, precision) {
    var cr = Math.cos(radius), sr = Math.sin(radius);
    return function(from, to, direction, listener) {
      var step = direction * precision;
      if (from != null) {
        from = d3_geo_circleAngle(cr, from);
        to = d3_geo_circleAngle(cr, to);
        if (direction > 0 ? from < to : from > to) from += direction * τ;
      } else {
        from = radius + direction * τ;
        to = radius - .5 * step;
      }
      for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
        listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
      }
    };
  }
  function d3_geo_circleAngle(cr, point) {
    var a = d3_geo_cartesian(point);
    a[0] -= cr;
    d3_geo_cartesianNormalize(a);
    var angle = d3_acos(-a[1]);
    return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
  }
  d3.geo.distance = function(a, b) {
    var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
    return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
  };
  d3.geo.graticule = function() {
    var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
    function graticule() {
      return {
        type: "MultiLineString",
        coordinates: lines()
      };
    }
    function lines() {
      return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
        return abs(x % DX) > ε;
      }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
        return abs(y % DY) > ε;
      }).map(y));
    }
    graticule.lines = function() {
      return lines().map(function(coordinates) {
        return {
          type: "LineString",
          coordinates: coordinates
        };
      });
    };
    graticule.outline = function() {
      return {
        type: "Polygon",
        coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
      };
    };
    graticule.extent = function(_) {
      if (!arguments.length) return graticule.minorExtent();
      return graticule.majorExtent(_).minorExtent(_);
    };
    graticule.majorExtent = function(_) {
      if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
      X0 = +_[0][0], X1 = +_[1][0];
      Y0 = +_[0][1], Y1 = +_[1][1];
      if (X0 > X1) _ = X0, X0 = X1, X1 = _;
      if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
      return graticule.precision(precision);
    };
    graticule.minorExtent = function(_) {
      if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
      x0 = +_[0][0], x1 = +_[1][0];
      y0 = +_[0][1], y1 = +_[1][1];
      if (x0 > x1) _ = x0, x0 = x1, x1 = _;
      if (y0 > y1) _ = y0, y0 = y1, y1 = _;
      return graticule.precision(precision);
    };
    graticule.step = function(_) {
      if (!arguments.length) return graticule.minorStep();
      return graticule.majorStep(_).minorStep(_);
    };
    graticule.majorStep = function(_) {
      if (!arguments.length) return [ DX, DY ];
      DX = +_[0], DY = +_[1];
      return graticule;
    };
    graticule.minorStep = function(_) {
      if (!arguments.length) return [ dx, dy ];
      dx = +_[0], dy = +_[1];
      return graticule;
    };
    graticule.precision = function(_) {
      if (!arguments.length) return precision;
      precision = +_;
      x = d3_geo_graticuleX(y0, y1, 90);
      y = d3_geo_graticuleY(x0, x1, precision);
      X = d3_geo_graticuleX(Y0, Y1, 90);
      Y = d3_geo_graticuleY(X0, X1, precision);
      return graticule;
    };
    return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
  };
  function d3_geo_graticuleX(y0, y1, dy) {
    var y = d3.range(y0, y1 - ε, dy).concat(y1);
    return function(x) {
      return y.map(function(y) {
        return [ x, y ];
      });
    };
  }
  function d3_geo_graticuleY(x0, x1, dx) {
    var x = d3.range(x0, x1 - ε, dx).concat(x1);
    return function(y) {
      return x.map(function(x) {
        return [ x, y ];
      });
    };
  }
  function d3_source(d) {
    return d.source;
  }
  function d3_target(d) {
    return d.target;
  }
  d3.geo.greatArc = function() {
    var source = d3_source, source_, target = d3_target, target_;
    function greatArc() {
      return {
        type: "LineString",
        coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
      };
    }
    greatArc.distance = function() {
      return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
    };
    greatArc.source = function(_) {
      if (!arguments.length) return source;
      source = _, source_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.target = function(_) {
      if (!arguments.length) return target;
      target = _, target_ = typeof _ === "function" ? null : _;
      return greatArc;
    };
    greatArc.precision = function() {
      return arguments.length ? greatArc : 0;
    };
    return greatArc;
  };
  d3.geo.interpolate = function(source, target) {
    return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
  };
  function d3_geo_interpolate(x0, y0, x1, y1) {
    var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
    var interpolate = d ? function(t) {
      var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
      return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
    } : function() {
      return [ x0 * d3_degrees, y0 * d3_degrees ];
    };
    interpolate.distance = d;
    return interpolate;
  }
  d3.geo.length = function(object) {
    d3_geo_lengthSum = 0;
    d3.geo.stream(object, d3_geo_length);
    return d3_geo_lengthSum;
  };
  var d3_geo_lengthSum;
  var d3_geo_length = {
    sphere: d3_noop,
    point: d3_noop,
    lineStart: d3_geo_lengthLineStart,
    lineEnd: d3_noop,
    polygonStart: d3_noop,
    polygonEnd: d3_noop
  };
  function d3_geo_lengthLineStart() {
    var λ0, sinφ0, cosφ0;
    d3_geo_length.point = function(λ, φ) {
      λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
      d3_geo_length.point = nextPoint;
    };
    d3_geo_length.lineEnd = function() {
      d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
    };
    function nextPoint(λ, φ) {
      var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
      d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
      λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
    }
  }
  function d3_geo_azimuthal(scale, angle) {
    function azimuthal(λ, φ) {
      var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
      return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
    }
    azimuthal.invert = function(x, y) {
      var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
      return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
    };
    return azimuthal;
  }
  var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
    return Math.sqrt(2 / (1 + cosλcosφ));
  }, function(ρ) {
    return 2 * Math.asin(ρ / 2);
  });
  (d3.geo.azimuthalEqualArea = function() {
    return d3_geo_projection(d3_geo_azimuthalEqualArea);
  }).raw = d3_geo_azimuthalEqualArea;
  var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
    var c = Math.acos(cosλcosφ);
    return c && c / Math.sin(c);
  }, d3_identity);
  (d3.geo.azimuthalEquidistant = function() {
    return d3_geo_projection(d3_geo_azimuthalEquidistant);
  }).raw = d3_geo_azimuthalEquidistant;
  function d3_geo_conicConformal(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), t = function(φ) {
      return Math.tan(π / 4 + φ / 2);
    }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
    if (!n) return d3_geo_mercator;
    function forward(λ, φ) {
      if (F > 0) {
        if (φ < -halfπ + ε) φ = -halfπ + ε;
      } else {
        if (φ > halfπ - ε) φ = halfπ - ε;
      }
      var ρ = F / Math.pow(t(φ), n);
      return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
      return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
    };
    return forward;
  }
  (d3.geo.conicConformal = function() {
    return d3_geo_conic(d3_geo_conicConformal);
  }).raw = d3_geo_conicConformal;
  function d3_geo_conicEquidistant(φ0, φ1) {
    var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
    if (abs(n) < ε) return d3_geo_equirectangular;
    function forward(λ, φ) {
      var ρ = G - φ;
      return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
    }
    forward.invert = function(x, y) {
      var ρ0_y = G - y;
      return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
    };
    return forward;
  }
  (d3.geo.conicEquidistant = function() {
    return d3_geo_conic(d3_geo_conicEquidistant);
  }).raw = d3_geo_conicEquidistant;
  var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / cosλcosφ;
  }, Math.atan);
  (d3.geo.gnomonic = function() {
    return d3_geo_projection(d3_geo_gnomonic);
  }).raw = d3_geo_gnomonic;
  function d3_geo_mercator(λ, φ) {
    return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
  }
  d3_geo_mercator.invert = function(x, y) {
    return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
  };
  function d3_geo_mercatorProjection(project) {
    var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
    m.scale = function() {
      var v = scale.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.translate = function() {
      var v = translate.apply(m, arguments);
      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
    };
    m.clipExtent = function(_) {
      var v = clipExtent.apply(m, arguments);
      if (v === m) {
        if (clipAuto = _ == null) {
          var k = π * scale(), t = translate();
          clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
        }
      } else if (clipAuto) {
        v = null;
      }
      return v;
    };
    return m.clipExtent(null);
  }
  (d3.geo.mercator = function() {
    return d3_geo_mercatorProjection(d3_geo_mercator);
  }).raw = d3_geo_mercator;
  var d3_geo_orthographic = d3_geo_azimuthal(function() {
    return 1;
  }, Math.asin);
  (d3.geo.orthographic = function() {
    return d3_geo_projection(d3_geo_orthographic);
  }).raw = d3_geo_orthographic;
  var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
    return 1 / (1 + cosλcosφ);
  }, function(ρ) {
    return 2 * Math.atan(ρ);
  });
  (d3.geo.stereographic = function() {
    return d3_geo_projection(d3_geo_stereographic);
  }).raw = d3_geo_stereographic;
  function d3_geo_transverseMercator(λ, φ) {
    return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ];
  }
  d3_geo_transverseMercator.invert = function(x, y) {
    return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ];
  };
  (d3.geo.transverseMercator = function() {
    var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
    projection.center = function(_) {
      return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
    };
    projection.rotate = function(_) {
      return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), 
      [ _[0], _[1], _[2] - 90 ]);
    };
    return rotate([ 0, 0, 90 ]);
  }).raw = d3_geo_transverseMercator;
  d3.geom = {};
  function d3_geom_pointX(d) {
    return d[0];
  }
  function d3_geom_pointY(d) {
    return d[1];
  }
  d3.geom.hull = function(vertices) {
    var x = d3_geom_pointX, y = d3_geom_pointY;
    if (arguments.length) return hull(vertices);
    function hull(data) {
      if (data.length < 3) return [];
      var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
      for (i = 0; i < n; i++) {
        points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
      }
      points.sort(d3_geom_hullOrder);
      for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
      var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
      var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
      for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
      for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
      return polygon;
    }
    hull.x = function(_) {
      return arguments.length ? (x = _, hull) : x;
    };
    hull.y = function(_) {
      return arguments.length ? (y = _, hull) : y;
    };
    return hull;
  };
  function d3_geom_hullUpper(points) {
    var n = points.length, hull = [ 0, 1 ], hs = 2;
    for (var i = 2; i < n; i++) {
      while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
      hull[hs++] = i;
    }
    return hull.slice(0, hs);
  }
  function d3_geom_hullOrder(a, b) {
    return a[0] - b[0] || a[1] - b[1];
  }
  d3.geom.polygon = function(coordinates) {
    d3_subclass(coordinates, d3_geom_polygonPrototype);
    return coordinates;
  };
  var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
  d3_geom_polygonPrototype.area = function() {
    var i = -1, n = this.length, a, b = this[n - 1], area = 0;
    while (++i < n) {
      a = b;
      b = this[i];
      area += a[1] * b[0] - a[0] * b[1];
    }
    return area * .5;
  };
  d3_geom_polygonPrototype.centroid = function(k) {
    var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
    if (!arguments.length) k = -1 / (6 * this.area());
    while (++i < n) {
      a = b;
      b = this[i];
      c = a[0] * b[1] - b[0] * a[1];
      x += (a[0] + b[0]) * c;
      y += (a[1] + b[1]) * c;
    }
    return [ x * k, y * k ];
  };
  d3_geom_polygonPrototype.clip = function(subject) {
    var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
    while (++i < n) {
      input = subject.slice();
      subject.length = 0;
      b = this[i];
      c = input[(m = input.length - closed) - 1];
      j = -1;
      while (++j < m) {
        d = input[j];
        if (d3_geom_polygonInside(d, a, b)) {
          if (!d3_geom_polygonInside(c, a, b)) {
            subject.push(d3_geom_polygonIntersect(c, d, a, b));
          }
          subject.push(d);
        } else if (d3_geom_polygonInside(c, a, b)) {
          subject.push(d3_geom_polygonIntersect(c, d, a, b));
        }
        c = d;
      }
      if (closed) subject.push(subject[0]);
      a = b;
    }
    return subject;
  };
  function d3_geom_polygonInside(p, a, b) {
    return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
  }
  function d3_geom_polygonIntersect(c, d, a, b) {
    var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
    return [ x1 + ua * x21, y1 + ua * y21 ];
  }
  function d3_geom_polygonClosed(coordinates) {
    var a = coordinates[0], b = coordinates[coordinates.length - 1];
    return !(a[0] - b[0] || a[1] - b[1]);
  }
  var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
  function d3_geom_voronoiBeach() {
    d3_geom_voronoiRedBlackNode(this);
    this.edge = this.site = this.circle = null;
  }
  function d3_geom_voronoiCreateBeach(site) {
    var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
    beach.site = site;
    return beach;
  }
  function d3_geom_voronoiDetachBeach(beach) {
    d3_geom_voronoiDetachCircle(beach);
    d3_geom_voronoiBeaches.remove(beach);
    d3_geom_voronoiBeachPool.push(beach);
    d3_geom_voronoiRedBlackNode(beach);
  }
  function d3_geom_voronoiRemoveBeach(beach) {
    var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
      x: x,
      y: y
    }, previous = beach.P, next = beach.N, disappearing = [ beach ];
    d3_geom_voronoiDetachBeach(beach);
    var lArc = previous;
    while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
      previous = lArc.P;
      disappearing.unshift(lArc);
      d3_geom_voronoiDetachBeach(lArc);
      lArc = previous;
    }
    disappearing.unshift(lArc);
    d3_geom_voronoiDetachCircle(lArc);
    var rArc = next;
    while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
      next = rArc.N;
      disappearing.push(rArc);
      d3_geom_voronoiDetachBeach(rArc);
      rArc = next;
    }
    disappearing.push(rArc);
    d3_geom_voronoiDetachCircle(rArc);
    var nArcs = disappearing.length, iArc;
    for (iArc = 1; iArc < nArcs; ++iArc) {
      rArc = disappearing[iArc];
      lArc = disappearing[iArc - 1];
      d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
    }
    lArc = disappearing[0];
    rArc = disappearing[nArcs - 1];
    rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiAddBeach(site) {
    var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
    while (node) {
      dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
      if (dxl > ε) node = node.L; else {
        dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
        if (dxr > ε) {
          if (!node.R) {
            lArc = node;
            break;
          }
          node = node.R;
        } else {
          if (dxl > -ε) {
            lArc = node.P;
            rArc = node;
          } else if (dxr > -ε) {
            lArc = node;
            rArc = node.N;
          } else {
            lArc = rArc = node;
          }
          break;
        }
      }
    }
    var newArc = d3_geom_voronoiCreateBeach(site);
    d3_geom_voronoiBeaches.insert(lArc, newArc);
    if (!lArc && !rArc) return;
    if (lArc === rArc) {
      d3_geom_voronoiDetachCircle(lArc);
      rArc = d3_geom_voronoiCreateBeach(lArc.site);
      d3_geom_voronoiBeaches.insert(newArc, rArc);
      newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      d3_geom_voronoiAttachCircle(lArc);
      d3_geom_voronoiAttachCircle(rArc);
      return;
    }
    if (!rArc) {
      newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
      return;
    }
    d3_geom_voronoiDetachCircle(lArc);
    d3_geom_voronoiDetachCircle(rArc);
    var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
      x: (cy * hb - by * hc) / d + ax,
      y: (bx * hc - cx * hb) / d + ay
    };
    d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
    newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
    rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
    d3_geom_voronoiAttachCircle(lArc);
    d3_geom_voronoiAttachCircle(rArc);
  }
  function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
    var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
    if (!pby2) return rfocx;
    var lArc = arc.P;
    if (!lArc) return -Infinity;
    site = lArc.site;
    var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
    if (!plby2) return lfocx;
    var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
    if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
    return (rfocx + lfocx) / 2;
  }
  function d3_geom_voronoiRightBreakPoint(arc, directrix) {
    var rArc = arc.N;
    if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
    var site = arc.site;
    return site.y === directrix ? site.x : Infinity;
  }
  function d3_geom_voronoiCell(site) {
    this.site = site;
    this.edges = [];
  }
  d3_geom_voronoiCell.prototype.prepare = function() {
    var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
    while (iHalfEdge--) {
      edge = halfEdges[iHalfEdge].edge;
      if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
    }
    halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
    return halfEdges.length;
  };
  function d3_geom_voronoiCloseCells(extent) {
    var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
    while (iCell--) {
      cell = cells[iCell];
      if (!cell || !cell.prepare()) continue;
      halfEdges = cell.edges;
      nHalfEdges = halfEdges.length;
      iHalfEdge = 0;
      while (iHalfEdge < nHalfEdges) {
        end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
        start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
        if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
          halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
            x: x0,
            y: abs(x2 - x0) < ε ? y2 : y1
          } : abs(y3 - y1) < ε && x1 - x3 > ε ? {
            x: abs(y2 - y1) < ε ? x2 : x1,
            y: y1
          } : abs(x3 - x1) < ε && y3 - y0 > ε ? {
            x: x1,
            y: abs(x2 - x1) < ε ? y2 : y0
          } : abs(y3 - y0) < ε && x3 - x0 > ε ? {
            x: abs(y2 - y0) < ε ? x2 : x0,
            y: y0
          } : null), cell.site, null));
          ++nHalfEdges;
        }
      }
    }
  }
  function d3_geom_voronoiHalfEdgeOrder(a, b) {
    return b.angle - a.angle;
  }
  function d3_geom_voronoiCircle() {
    d3_geom_voronoiRedBlackNode(this);
    this.x = this.y = this.arc = this.site = this.cy = null;
  }
  function d3_geom_voronoiAttachCircle(arc) {
    var lArc = arc.P, rArc = arc.N;
    if (!lArc || !rArc) return;
    var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
    if (lSite === rSite) return;
    var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
    var d = 2 * (ax * cy - ay * cx);
    if (d >= -ε2) return;
    var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
    var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
    circle.arc = arc;
    circle.site = cSite;
    circle.x = x + bx;
    circle.y = cy + Math.sqrt(x * x + y * y);
    circle.cy = cy;
    arc.circle = circle;
    var before = null, node = d3_geom_voronoiCircles._;
    while (node) {
      if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
        if (node.L) node = node.L; else {
          before = node.P;
          break;
        }
      } else {
        if (node.R) node = node.R; else {
          before = node;
          break;
        }
      }
    }
    d3_geom_voronoiCircles.insert(before, circle);
    if (!before) d3_geom_voronoiFirstCircle = circle;
  }
  function d3_geom_voronoiDetachCircle(arc) {
    var circle = arc.circle;
    if (circle) {
      if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
      d3_geom_voronoiCircles.remove(circle);
      d3_geom_voronoiCirclePool.push(circle);
      d3_geom_voronoiRedBlackNode(circle);
      arc.circle = null;
    }
  }
  function d3_geom_voronoiClipEdges(extent) {
    var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
    while (i--) {
      e = edges[i];
      if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
        e.a = e.b = null;
        edges.splice(i, 1);
      }
    }
  }
  function d3_geom_voronoiConnectEdge(edge, extent) {
    var vb = edge.b;
    if (vb) return true;
    var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
    if (ry === ly) {
      if (fx < x0 || fx >= x1) return;
      if (lx > rx) {
        if (!va) va = {
          x: fx,
          y: y0
        }; else if (va.y >= y1) return;
        vb = {
          x: fx,
          y: y1
        };
      } else {
        if (!va) va = {
          x: fx,
          y: y1
        }; else if (va.y < y0) return;
        vb = {
          x: fx,
          y: y0
        };
      }
    } else {
      fm = (lx - rx) / (ry - ly);
      fb = fy - fm * fx;
      if (fm < -1 || fm > 1) {
        if (lx > rx) {
          if (!va) va = {
            x: (y0 - fb) / fm,
            y: y0
          }; else if (va.y >= y1) return;
          vb = {
            x: (y1 - fb) / fm,
            y: y1
          };
        } else {
          if (!va) va = {
            x: (y1 - fb) / fm,
            y: y1
          }; else if (va.y < y0) return;
          vb = {
            x: (y0 - fb) / fm,
            y: y0
          };
        }
      } else {
        if (ly < ry) {
          if (!va) va = {
            x: x0,
            y: fm * x0 + fb
          }; else if (va.x >= x1) return;
          vb = {
            x: x1,
            y: fm * x1 + fb
          };
        } else {
          if (!va) va = {
            x: x1,
            y: fm * x1 + fb
          }; else if (va.x < x0) return;
          vb = {
            x: x0,
            y: fm * x0 + fb
          };
        }
      }
    }
    edge.a = va;
    edge.b = vb;
    return true;
  }
  function d3_geom_voronoiEdge(lSite, rSite) {
    this.l = lSite;
    this.r = rSite;
    this.a = this.b = null;
  }
  function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, rSite);
    d3_geom_voronoiEdges.push(edge);
    if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
    if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
    d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
    d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
    return edge;
  }
  function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
    var edge = new d3_geom_voronoiEdge(lSite, null);
    edge.a = va;
    edge.b = vb;
    d3_geom_voronoiEdges.push(edge);
    return edge;
  }
  function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
    if (!edge.a && !edge.b) {
      edge.a = vertex;
      edge.l = lSite;
      edge.r = rSite;
    } else if (edge.l === rSite) {
      edge.b = vertex;
    } else {
      edge.a = vertex;
    }
  }
  function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
    var va = edge.a, vb = edge.b;
    this.edge = edge;
    this.site = lSite;
    this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
  }
  d3_geom_voronoiHalfEdge.prototype = {
    start: function() {
      return this.edge.l === this.site ? this.edge.a : this.edge.b;
    },
    end: function() {
      return this.edge.l === this.site ? this.edge.b : this.edge.a;
    }
  };
  function d3_geom_voronoiRedBlackTree() {
    this._ = null;
  }
  function d3_geom_voronoiRedBlackNode(node) {
    node.U = node.C = node.L = node.R = node.P = node.N = null;
  }
  d3_geom_voronoiRedBlackTree.prototype = {
    insert: function(after, node) {
      var parent, grandpa, uncle;
      if (after) {
        node.P = after;
        node.N = after.N;
        if (after.N) after.N.P = node;
        after.N = node;
        if (after.R) {
          after = after.R;
          while (after.L) after = after.L;
          after.L = node;
        } else {
          after.R = node;
        }
        parent = after;
      } else if (this._) {
        after = d3_geom_voronoiRedBlackFirst(this._);
        node.P = null;
        node.N = after;
        after.P = after.L = node;
        parent = after;
      } else {
        node.P = node.N = null;
        this._ = node;
        parent = null;
      }
      node.L = node.R = null;
      node.U = parent;
      node.C = true;
      after = node;
      while (parent && parent.C) {
        grandpa = parent.U;
        if (parent === grandpa.L) {
          uncle = grandpa.R;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.R) {
              d3_geom_voronoiRedBlackRotateLeft(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, grandpa);
          }
        } else {
          uncle = grandpa.L;
          if (uncle && uncle.C) {
            parent.C = uncle.C = false;
            grandpa.C = true;
            after = grandpa;
          } else {
            if (after === parent.L) {
              d3_geom_voronoiRedBlackRotateRight(this, parent);
              after = parent;
              parent = after.U;
            }
            parent.C = false;
            grandpa.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
          }
        }
        parent = after.U;
      }
      this._.C = false;
    },
    remove: function(node) {
      if (node.N) node.N.P = node.P;
      if (node.P) node.P.N = node.N;
      node.N = node.P = null;
      var parent = node.U, sibling, left = node.L, right = node.R, next, red;
      if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
      if (parent) {
        if (parent.L === node) parent.L = next; else parent.R = next;
      } else {
        this._ = next;
      }
      if (left && right) {
        red = next.C;
        next.C = node.C;
        next.L = left;
        left.U = next;
        if (next !== right) {
          parent = next.U;
          next.U = node.U;
          node = next.R;
          parent.L = node;
          next.R = right;
          right.U = next;
        } else {
          next.U = parent;
          parent = next;
          node = next.R;
        }
      } else {
        red = node.C;
        node = next;
      }
      if (node) node.U = parent;
      if (red) return;
      if (node && node.C) {
        node.C = false;
        return;
      }
      do {
        if (node === this._) break;
        if (node === parent.L) {
          sibling = parent.R;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            sibling = parent.R;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.R || !sibling.R.C) {
              sibling.L.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateRight(this, sibling);
              sibling = parent.R;
            }
            sibling.C = parent.C;
            parent.C = sibling.R.C = false;
            d3_geom_voronoiRedBlackRotateLeft(this, parent);
            node = this._;
            break;
          }
        } else {
          sibling = parent.L;
          if (sibling.C) {
            sibling.C = false;
            parent.C = true;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            sibling = parent.L;
          }
          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
            if (!sibling.L || !sibling.L.C) {
              sibling.R.C = false;
              sibling.C = true;
              d3_geom_voronoiRedBlackRotateLeft(this, sibling);
              sibling = parent.L;
            }
            sibling.C = parent.C;
            parent.C = sibling.L.C = false;
            d3_geom_voronoiRedBlackRotateRight(this, parent);
            node = this._;
            break;
          }
        }
        sibling.C = true;
        node = parent;
        parent = parent.U;
      } while (!node.C);
      if (node) node.C = false;
    }
  };
  function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
    var p = node, q = node.R, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.R = q.L;
    if (p.R) p.R.U = p;
    q.L = p;
  }
  function d3_geom_voronoiRedBlackRotateRight(tree, node) {
    var p = node, q = node.L, parent = p.U;
    if (parent) {
      if (parent.L === p) parent.L = q; else parent.R = q;
    } else {
      tree._ = q;
    }
    q.U = parent;
    p.U = q;
    p.L = q.R;
    if (p.L) p.L.U = p;
    q.R = p;
  }
  function d3_geom_voronoiRedBlackFirst(node) {
    while (node.L) node = node.L;
    return node;
  }
  function d3_geom_voronoi(sites, bbox) {
    var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
    d3_geom_voronoiEdges = [];
    d3_geom_voronoiCells = new Array(sites.length);
    d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
    d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
    while (true) {
      circle = d3_geom_voronoiFirstCircle;
      if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
        if (site.x !== x0 || site.y !== y0) {
          d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
          d3_geom_voronoiAddBeach(site);
          x0 = site.x, y0 = site.y;
        }
        site = sites.pop();
      } else if (circle) {
        d3_geom_voronoiRemoveBeach(circle.arc);
      } else {
        break;
      }
    }
    if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
    var diagram = {
      cells: d3_geom_voronoiCells,
      edges: d3_geom_voronoiEdges
    };
    d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
    return diagram;
  }
  function d3_geom_voronoiVertexOrder(a, b) {
    return b.y - a.y || b.x - a.x;
  }
  d3.geom.voronoi = function(points) {
    var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
    if (points) return voronoi(points);
    function voronoi(data) {
      var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
      d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
        var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
          var s = e.start();
          return [ s.x, s.y ];
        }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
        polygon.point = data[i];
      });
      return polygons;
    }
    function sites(data) {
      return data.map(function(d, i) {
        return {
          x: Math.round(fx(d, i) / ε) * ε,
          y: Math.round(fy(d, i) / ε) * ε,
          i: i
        };
      });
    }
    voronoi.links = function(data) {
      return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
        return edge.l && edge.r;
      }).map(function(edge) {
        return {
          source: data[edge.l.i],
          target: data[edge.r.i]
        };
      });
    };
    voronoi.triangles = function(data) {
      var triangles = [];
      d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
        var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
        while (++j < m) {
          e0 = e1;
          s0 = s1;
          e1 = edges[j].edge;
          s1 = e1.l === site ? e1.r : e1.l;
          if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
            triangles.push([ data[i], data[s0.i], data[s1.i] ]);
          }
        }
      });
      return triangles;
    };
    voronoi.x = function(_) {
      return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
    };
    voronoi.y = function(_) {
      return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
    };
    voronoi.clipExtent = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
      clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
      return voronoi;
    };
    voronoi.size = function(_) {
      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
      return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
    };
    return voronoi;
  };
  var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
  function d3_geom_voronoiTriangleArea(a, b, c) {
    return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
  }
  d3.geom.delaunay = function(vertices) {
    return d3.geom.voronoi().triangles(vertices);
  };
  d3.geom.quadtree = function(points, x1, y1, x2, y2) {
    var x = d3_geom_pointX, y = d3_geom_pointY, compat;
    if (compat = arguments.length) {
      x = d3_geom_quadtreeCompatX;
      y = d3_geom_quadtreeCompatY;
      if (compat === 3) {
        y2 = y1;
        x2 = x1;
        y1 = x1 = 0;
      }
      return quadtree(points);
    }
    function quadtree(data) {
      var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
      if (x1 != null) {
        x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
      } else {
        x2_ = y2_ = -(x1_ = y1_ = Infinity);
        xs = [], ys = [];
        n = data.length;
        if (compat) for (i = 0; i < n; ++i) {
          d = data[i];
          if (d.x < x1_) x1_ = d.x;
          if (d.y < y1_) y1_ = d.y;
          if (d.x > x2_) x2_ = d.x;
          if (d.y > y2_) y2_ = d.y;
          xs.push(d.x);
          ys.push(d.y);
        } else for (i = 0; i < n; ++i) {
          var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
          if (x_ < x1_) x1_ = x_;
          if (y_ < y1_) y1_ = y_;
          if (x_ > x2_) x2_ = x_;
          if (y_ > y2_) y2_ = y_;
          xs.push(x_);
          ys.push(y_);
        }
      }
      var dx = x2_ - x1_, dy = y2_ - y1_;
      if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
      function insert(n, d, x, y, x1, y1, x2, y2) {
        if (isNaN(x) || isNaN(y)) return;
        if (n.leaf) {
          var nx = n.x, ny = n.y;
          if (nx != null) {
            if (abs(nx - x) + abs(ny - y) < .01) {
              insertChild(n, d, x, y, x1, y1, x2, y2);
            } else {
              var nPoint = n.point;
              n.x = n.y = n.point = null;
              insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
              insertChild(n, d, x, y, x1, y1, x2, y2);
            }
          } else {
            n.x = x, n.y = y, n.point = d;
          }
        } else {
          insertChild(n, d, x, y, x1, y1, x2, y2);
        }
      }
      function insertChild(n, d, x, y, x1, y1, x2, y2) {
        var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
        n.leaf = false;
        n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
        if (right) x1 = xm; else x2 = xm;
        if (below) y1 = ym; else y2 = ym;
        insert(n, d, x, y, x1, y1, x2, y2);
      }
      var root = d3_geom_quadtreeNode();
      root.add = function(d) {
        insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
      };
      root.visit = function(f) {
        d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
      };
      root.find = function(point) {
        return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
      };
      i = -1;
      if (x1 == null) {
        while (++i < n) {
          insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
        }
        --i;
      } else data.forEach(root.add);
      xs = ys = data = d = null;
      return root;
    }
    quadtree.x = function(_) {
      return arguments.length ? (x = _, quadtree) : x;
    };
    quadtree.y = function(_) {
      return arguments.length ? (y = _, quadtree) : y;
    };
    quadtree.extent = function(_) {
      if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], 
      y2 = +_[1][1];
      return quadtree;
    };
    quadtree.size = function(_) {
      if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
      return quadtree;
    };
    return quadtree;
  };
  function d3_geom_quadtreeCompatX(d) {
    return d.x;
  }
  function d3_geom_quadtreeCompatY(d) {
    return d.y;
  }
  function d3_geom_quadtreeNode() {
    return {
      leaf: true,
      nodes: [],
      point: null,
      x: null,
      y: null
    };
  }
  function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
    if (!f(node, x1, y1, x2, y2)) {
      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
      if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
      if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
      if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
      if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
    }
  }
  function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
    var minDistance2 = Infinity, closestPoint;
    (function find(node, x1, y1, x2, y2) {
      if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
      if (point = node.point) {
        var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
        if (distance2 < minDistance2) {
          var distance = Math.sqrt(minDistance2 = distance2);
          x0 = x - distance, y0 = y - distance;
          x3 = x + distance, y3 = y + distance;
          closestPoint = point;
        }
      }
      var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
      for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
        if (node = children[i & 3]) switch (i & 3) {
         case 0:
          find(node, x1, y1, xm, ym);
          break;

         case 1:
          find(node, xm, y1, x2, ym);
          break;

         case 2:
          find(node, x1, ym, xm, y2);
          break;

         case 3:
          find(node, xm, ym, x2, y2);
          break;
        }
      }
    })(root, x0, y0, x3, y3);
    return closestPoint;
  }
  d3.interpolateRgb = d3_interpolateRgb;
  function d3_interpolateRgb(a, b) {
    a = d3.rgb(a);
    b = d3.rgb(b);
    var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
    return function(t) {
      return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
    };
  }
  d3.interpolateObject = d3_interpolateObject;
  function d3_interpolateObject(a, b) {
    var i = {}, c = {}, k;
    for (k in a) {
      if (k in b) {
        i[k] = d3_interpolate(a[k], b[k]);
      } else {
        c[k] = a[k];
      }
    }
    for (k in b) {
      if (!(k in a)) {
        c[k] = b[k];
      }
    }
    return function(t) {
      for (k in i) c[k] = i[k](t);
      return c;
    };
  }
  d3.interpolateNumber = d3_interpolateNumber;
  function d3_interpolateNumber(a, b) {
    a = +a, b = +b;
    return function(t) {
      return a * (1 - t) + b * t;
    };
  }
  d3.interpolateString = d3_interpolateString;
  function d3_interpolateString(a, b) {
    var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
    a = a + "", b = b + "";
    while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
      if ((bs = bm.index) > bi) {
        bs = b.slice(bi, bs);
        if (s[i]) s[i] += bs; else s[++i] = bs;
      }
      if ((am = am[0]) === (bm = bm[0])) {
        if (s[i]) s[i] += bm; else s[++i] = bm;
      } else {
        s[++i] = null;
        q.push({
          i: i,
          x: d3_interpolateNumber(am, bm)
        });
      }
      bi = d3_interpolate_numberB.lastIndex;
    }
    if (bi < b.length) {
      bs = b.slice(bi);
      if (s[i]) s[i] += bs; else s[++i] = bs;
    }
    return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
      return b(t) + "";
    }) : function() {
      return b;
    } : (b = q.length, function(t) {
      for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    });
  }
  var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
  d3.interpolate = d3_interpolate;
  function d3_interpolate(a, b) {
    var i = d3.interpolators.length, f;
    while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
    return f;
  }
  d3.interpolators = [ function(a, b) {
    var t = typeof b;
    return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
  } ];
  d3.interpolateArray = d3_interpolateArray;
  function d3_interpolateArray(a, b) {
    var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
    for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
    for (;i < na; ++i) c[i] = a[i];
    for (;i < nb; ++i) c[i] = b[i];
    return function(t) {
      for (i = 0; i < n0; ++i) c[i] = x[i](t);
      return c;
    };
  }
  var d3_ease_default = function() {
    return d3_identity;
  };
  var d3_ease = d3.map({
    linear: d3_ease_default,
    poly: d3_ease_poly,
    quad: function() {
      return d3_ease_quad;
    },
    cubic: function() {
      return d3_ease_cubic;
    },
    sin: function() {
      return d3_ease_sin;
    },
    exp: function() {
      return d3_ease_exp;
    },
    circle: function() {
      return d3_ease_circle;
    },
    elastic: d3_ease_elastic,
    back: d3_ease_back,
    bounce: function() {
      return d3_ease_bounce;
    }
  });
  var d3_ease_mode = d3.map({
    "in": d3_identity,
    out: d3_ease_reverse,
    "in-out": d3_ease_reflect,
    "out-in": function(f) {
      return d3_ease_reflect(d3_ease_reverse(f));
    }
  });
  d3.ease = function(name) {
    var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
    t = d3_ease.get(t) || d3_ease_default;
    m = d3_ease_mode.get(m) || d3_identity;
    return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
  };
  function d3_ease_clamp(f) {
    return function(t) {
      return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
    };
  }
  function d3_ease_reverse(f) {
    return function(t) {
      return 1 - f(1 - t);
    };
  }
  function d3_ease_reflect(f) {
    return function(t) {
      return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
    };
  }
  function d3_ease_quad(t) {
    return t * t;
  }
  function d3_ease_cubic(t) {
    return t * t * t;
  }
  function d3_ease_cubicInOut(t) {
    if (t <= 0) return 0;
    if (t >= 1) return 1;
    var t2 = t * t, t3 = t2 * t;
    return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
  }
  function d3_ease_poly(e) {
    return function(t) {
      return Math.pow(t, e);
    };
  }
  function d3_ease_sin(t) {
    return 1 - Math.cos(t * halfπ);
  }
  function d3_ease_exp(t) {
    return Math.pow(2, 10 * (t - 1));
  }
  function d3_ease_circle(t) {
    return 1 - Math.sqrt(1 - t * t);
  }
  function d3_ease_elastic(a, p) {
    var s;
    if (arguments.length < 2) p = .45;
    if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
    return function(t) {
      return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
    };
  }
  function d3_ease_back(s) {
    if (!s) s = 1.70158;
    return function(t) {
      return t * t * ((s + 1) * t - s);
    };
  }
  function d3_ease_bounce(t) {
    return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
  }
  d3.interpolateHcl = d3_interpolateHcl;
  function d3_interpolateHcl(a, b) {
    a = d3.hcl(a);
    b = d3.hcl(b);
    var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
    if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
    };
  }
  d3.interpolateHsl = d3_interpolateHsl;
  function d3_interpolateHsl(a, b) {
    a = d3.hsl(a);
    b = d3.hsl(b);
    var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
    if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
    return function(t) {
      return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
    };
  }
  d3.interpolateLab = d3_interpolateLab;
  function d3_interpolateLab(a, b) {
    a = d3.lab(a);
    b = d3.lab(b);
    var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
    return function(t) {
      return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
    };
  }
  d3.interpolateRound = d3_interpolateRound;
  function d3_interpolateRound(a, b) {
    b -= a;
    return function(t) {
      return Math.round(a + b * t);
    };
  }
  d3.transform = function(string) {
    var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
    return (d3.transform = function(string) {
      if (string != null) {
        g.setAttribute("transform", string);
        var t = g.transform.baseVal.consolidate();
      }
      return new d3_transform(t ? t.matrix : d3_transformIdentity);
    })(string);
  };
  function d3_transform(m) {
    var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
    if (r0[0] * r1[1] < r1[0] * r0[1]) {
      r0[0] *= -1;
      r0[1] *= -1;
      kx *= -1;
      kz *= -1;
    }
    this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
    this.translate = [ m.e, m.f ];
    this.scale = [ kx, ky ];
    this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
  }
  d3_transform.prototype.toString = function() {
    return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
  };
  function d3_transformDot(a, b) {
    return a[0] * b[0] + a[1] * b[1];
  }
  function d3_transformNormalize(a) {
    var k = Math.sqrt(d3_transformDot(a, a));
    if (k) {
      a[0] /= k;
      a[1] /= k;
    }
    return k;
  }
  function d3_transformCombine(a, b, k) {
    a[0] += k * b[0];
    a[1] += k * b[1];
    return a;
  }
  var d3_transformIdentity = {
    a: 1,
    b: 0,
    c: 0,
    d: 1,
    e: 0,
    f: 0
  };
  d3.interpolateTransform = d3_interpolateTransform;
  function d3_interpolateTransformPop(s) {
    return s.length ? s.pop() + "," : "";
  }
  function d3_interpolateTranslate(ta, tb, s, q) {
    if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
      var i = s.push("translate(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ta[0], tb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ta[1], tb[1])
      });
    } else if (tb[0] || tb[1]) {
      s.push("translate(" + tb + ")");
    }
  }
  function d3_interpolateRotate(ra, rb, s, q) {
    if (ra !== rb) {
      if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
        x: d3_interpolateNumber(ra, rb)
      });
    } else if (rb) {
      s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
    }
  }
  function d3_interpolateSkew(wa, wb, s, q) {
    if (wa !== wb) {
      q.push({
        i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
        x: d3_interpolateNumber(wa, wb)
      });
    } else if (wb) {
      s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
    }
  }
  function d3_interpolateScale(ka, kb, s, q) {
    if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
      var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
      q.push({
        i: i - 4,
        x: d3_interpolateNumber(ka[0], kb[0])
      }, {
        i: i - 2,
        x: d3_interpolateNumber(ka[1], kb[1])
      });
    } else if (kb[0] !== 1 || kb[1] !== 1) {
      s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
    }
  }
  function d3_interpolateTransform(a, b) {
    var s = [], q = [];
    a = d3.transform(a), b = d3.transform(b);
    d3_interpolateTranslate(a.translate, b.translate, s, q);
    d3_interpolateRotate(a.rotate, b.rotate, s, q);
    d3_interpolateSkew(a.skew, b.skew, s, q);
    d3_interpolateScale(a.scale, b.scale, s, q);
    a = b = null;
    return function(t) {
      var i = -1, n = q.length, o;
      while (++i < n) s[(o = q[i]).i] = o.x(t);
      return s.join("");
    };
  }
  function d3_uninterpolateNumber(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return (x - a) / b;
    };
  }
  function d3_uninterpolateClamp(a, b) {
    b = (b -= a = +a) || 1 / b;
    return function(x) {
      return Math.max(0, Math.min(1, (x - a) / b));
    };
  }
  d3.layout = {};
  d3.layout.bundle = function() {
    return function(links) {
      var paths = [], i = -1, n = links.length;
      while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
      return paths;
    };
  };
  function d3_layout_bundlePath(link) {
    var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
    while (start !== lca) {
      start = start.parent;
      points.push(start);
    }
    var k = points.length;
    while (end !== lca) {
      points.splice(k, 0, end);
      end = end.parent;
    }
    return points;
  }
  function d3_layout_bundleAncestors(node) {
    var ancestors = [], parent = node.parent;
    while (parent != null) {
      ancestors.push(node);
      node = parent;
      parent = parent.parent;
    }
    ancestors.push(node);
    return ancestors;
  }
  function d3_layout_bundleLeastCommonAncestor(a, b) {
    if (a === b) return a;
    var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
    while (aNode === bNode) {
      sharedNode = aNode;
      aNode = aNodes.pop();
      bNode = bNodes.pop();
    }
    return sharedNode;
  }
  d3.layout.chord = function() {
    var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
    function relayout() {
      var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
      chords = [];
      groups = [];
      k = 0, i = -1;
      while (++i < n) {
        x = 0, j = -1;
        while (++j < n) {
          x += matrix[i][j];
        }
        groupSums.push(x);
        subgroupIndex.push(d3.range(n));
        k += x;
      }
      if (sortGroups) {
        groupIndex.sort(function(a, b) {
          return sortGroups(groupSums[a], groupSums[b]);
        });
      }
      if (sortSubgroups) {
        subgroupIndex.forEach(function(d, i) {
          d.sort(function(a, b) {
            return sortSubgroups(matrix[i][a], matrix[i][b]);
          });
        });
      }
      k = (τ - padding * n) / k;
      x = 0, i = -1;
      while (++i < n) {
        x0 = x, j = -1;
        while (++j < n) {
          var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
          subgroups[di + "-" + dj] = {
            index: di,
            subindex: dj,
            startAngle: a0,
            endAngle: a1,
            value: v
          };
        }
        groups[di] = {
          index: di,
          startAngle: x0,
          endAngle: x,
          value: groupSums[di]
        };
        x += padding;
      }
      i = -1;
      while (++i < n) {
        j = i - 1;
        while (++j < n) {
          var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
          if (source.value || target.value) {
            chords.push(source.value < target.value ? {
              source: target,
              target: source
            } : {
              source: source,
              target: target
            });
          }
        }
      }
      if (sortChords) resort();
    }
    function resort() {
      chords.sort(function(a, b) {
        return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
      });
    }
    chord.matrix = function(x) {
      if (!arguments.length) return matrix;
      n = (matrix = x) && matrix.length;
      chords = groups = null;
      return chord;
    };
    chord.padding = function(x) {
      if (!arguments.length) return padding;
      padding = x;
      chords = groups = null;
      return chord;
    };
    chord.sortGroups = function(x) {
      if (!arguments.length) return sortGroups;
      sortGroups = x;
      chords = groups = null;
      return chord;
    };
    chord.sortSubgroups = function(x) {
      if (!arguments.length) return sortSubgroups;
      sortSubgroups = x;
      chords = null;
      return chord;
    };
    chord.sortChords = function(x) {
      if (!arguments.length) return sortChords;
      sortChords = x;
      if (chords) resort();
      return chord;
    };
    chord.chords = function() {
      if (!chords) relayout();
      return chords;
    };
    chord.groups = function() {
      if (!groups) relayout();
      return groups;
    };
    return chord;
  };
  d3.layout.force = function() {
    var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
    function repulse(node) {
      return function(quad, x1, _, x2) {
        if (quad.point !== node) {
          var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
          if (dw * dw / theta2 < dn) {
            if (dn < chargeDistance2) {
              var k = quad.charge / dn;
              node.px -= dx * k;
              node.py -= dy * k;
            }
            return true;
          }
          if (quad.point && dn && dn < chargeDistance2) {
            var k = quad.pointCharge / dn;
            node.px -= dx * k;
            node.py -= dy * k;
          }
        }
        return !quad.charge;
      };
    }
    force.tick = function() {
      if ((alpha *= .99) < .005) {
        timer = null;
        event.end({
          type: "end",
          alpha: alpha = 0
        });
        return true;
      }
      var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
      for (i = 0; i < m; ++i) {
        o = links[i];
        s = o.source;
        t = o.target;
        x = t.x - s.x;
        y = t.y - s.y;
        if (l = x * x + y * y) {
          l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
          x *= l;
          y *= l;
          t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
          t.y -= y * k;
          s.x += x * (k = 1 - k);
          s.y += y * k;
        }
      }
      if (k = alpha * gravity) {
        x = size[0] / 2;
        y = size[1] / 2;
        i = -1;
        if (k) while (++i < n) {
          o = nodes[i];
          o.x += (x - o.x) * k;
          o.y += (y - o.y) * k;
        }
      }
      if (charge) {
        d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
        i = -1;
        while (++i < n) {
          if (!(o = nodes[i]).fixed) {
            q.visit(repulse(o));
          }
        }
      }
      i = -1;
      while (++i < n) {
        o = nodes[i];
        if (o.fixed) {
          o.x = o.px;
          o.y = o.py;
        } else {
          o.x -= (o.px - (o.px = o.x)) * friction;
          o.y -= (o.py - (o.py = o.y)) * friction;
        }
      }
      event.tick({
        type: "tick",
        alpha: alpha
      });
    };
    force.nodes = function(x) {
      if (!arguments.length) return nodes;
      nodes = x;
      return force;
    };
    force.links = function(x) {
      if (!arguments.length) return links;
      links = x;
      return force;
    };
    force.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return force;
    };
    force.linkDistance = function(x) {
      if (!arguments.length) return linkDistance;
      linkDistance = typeof x === "function" ? x : +x;
      return force;
    };
    force.distance = force.linkDistance;
    force.linkStrength = function(x) {
      if (!arguments.length) return linkStrength;
      linkStrength = typeof x === "function" ? x : +x;
      return force;
    };
    force.friction = function(x) {
      if (!arguments.length) return friction;
      friction = +x;
      return force;
    };
    force.charge = function(x) {
      if (!arguments.length) return charge;
      charge = typeof x === "function" ? x : +x;
      return force;
    };
    force.chargeDistance = function(x) {
      if (!arguments.length) return Math.sqrt(chargeDistance2);
      chargeDistance2 = x * x;
      return force;
    };
    force.gravity = function(x) {
      if (!arguments.length) return gravity;
      gravity = +x;
      return force;
    };
    force.theta = function(x) {
      if (!arguments.length) return Math.sqrt(theta2);
      theta2 = x * x;
      return force;
    };
    force.alpha = function(x) {
      if (!arguments.length) return alpha;
      x = +x;
      if (alpha) {
        if (x > 0) {
          alpha = x;
        } else {
          timer.c = null, timer.t = NaN, timer = null;
          event.end({
            type: "end",
            alpha: alpha = 0
          });
        }
      } else if (x > 0) {
        event.start({
          type: "start",
          alpha: alpha = x
        });
        timer = d3_timer(force.tick);
      }
      return force;
    };
    force.start = function() {
      var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
      for (i = 0; i < n; ++i) {
        (o = nodes[i]).index = i;
        o.weight = 0;
      }
      for (i = 0; i < m; ++i) {
        o = links[i];
        if (typeof o.source == "number") o.source = nodes[o.source];
        if (typeof o.target == "number") o.target = nodes[o.target];
        ++o.source.weight;
        ++o.target.weight;
      }
      for (i = 0; i < n; ++i) {
        o = nodes[i];
        if (isNaN(o.x)) o.x = position("x", w);
        if (isNaN(o.y)) o.y = position("y", h);
        if (isNaN(o.px)) o.px = o.x;
        if (isNaN(o.py)) o.py = o.y;
      }
      distances = [];
      if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
      strengths = [];
      if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
      charges = [];
      if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
      function position(dimension, size) {
        if (!neighbors) {
          neighbors = new Array(n);
          for (j = 0; j < n; ++j) {
            neighbors[j] = [];
          }
          for (j = 0; j < m; ++j) {
            var o = links[j];
            neighbors[o.source.index].push(o.target);
            neighbors[o.target.index].push(o.source);
          }
        }
        var candidates = neighbors[i], j = -1, l = candidates.length, x;
        while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
        return Math.random() * size;
      }
      return force.resume();
    };
    force.resume = function() {
      return force.alpha(.1);
    };
    force.stop = function() {
      return force.alpha(0);
    };
    force.drag = function() {
      if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
      if (!arguments.length) return drag;
      this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
    };
    function dragmove(d) {
      d.px = d3.event.x, d.py = d3.event.y;
      force.resume();
    }
    return d3.rebind(force, event, "on");
  };
  function d3_layout_forceDragstart(d) {
    d.fixed |= 2;
  }
  function d3_layout_forceDragend(d) {
    d.fixed &= ~6;
  }
  function d3_layout_forceMouseover(d) {
    d.fixed |= 4;
    d.px = d.x, d.py = d.y;
  }
  function d3_layout_forceMouseout(d) {
    d.fixed &= ~4;
  }
  function d3_layout_forceAccumulate(quad, alpha, charges) {
    var cx = 0, cy = 0;
    quad.charge = 0;
    if (!quad.leaf) {
      var nodes = quad.nodes, n = nodes.length, i = -1, c;
      while (++i < n) {
        c = nodes[i];
        if (c == null) continue;
        d3_layout_forceAccumulate(c, alpha, charges);
        quad.charge += c.charge;
        cx += c.charge * c.cx;
        cy += c.charge * c.cy;
      }
    }
    if (quad.point) {
      if (!quad.leaf) {
        quad.point.x += Math.random() - .5;
        quad.point.y += Math.random() - .5;
      }
      var k = alpha * charges[quad.point.index];
      quad.charge += quad.pointCharge = k;
      cx += k * quad.point.x;
      cy += k * quad.point.y;
    }
    quad.cx = cx / quad.charge;
    quad.cy = cy / quad.charge;
  }
  var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
  d3.layout.hierarchy = function() {
    var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
    function hierarchy(root) {
      var stack = [ root ], nodes = [], node;
      root.depth = 0;
      while ((node = stack.pop()) != null) {
        nodes.push(node);
        if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
          var n, childs, child;
          while (--n >= 0) {
            stack.push(child = childs[n]);
            child.parent = node;
            child.depth = node.depth + 1;
          }
          if (value) node.value = 0;
          node.children = childs;
        } else {
          if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
          delete node.children;
        }
      }
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var childs, parent;
        if (sort && (childs = node.children)) childs.sort(sort);
        if (value && (parent = node.parent)) parent.value += node.value;
      });
      return nodes;
    }
    hierarchy.sort = function(x) {
      if (!arguments.length) return sort;
      sort = x;
      return hierarchy;
    };
    hierarchy.children = function(x) {
      if (!arguments.length) return children;
      children = x;
      return hierarchy;
    };
    hierarchy.value = function(x) {
      if (!arguments.length) return value;
      value = x;
      return hierarchy;
    };
    hierarchy.revalue = function(root) {
      if (value) {
        d3_layout_hierarchyVisitBefore(root, function(node) {
          if (node.children) node.value = 0;
        });
        d3_layout_hierarchyVisitAfter(root, function(node) {
          var parent;
          if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
          if (parent = node.parent) parent.value += node.value;
        });
      }
      return root;
    };
    return hierarchy;
  };
  function d3_layout_hierarchyRebind(object, hierarchy) {
    d3.rebind(object, hierarchy, "sort", "children", "value");
    object.nodes = object;
    object.links = d3_layout_hierarchyLinks;
    return object;
  }
  function d3_layout_hierarchyVisitBefore(node, callback) {
    var nodes = [ node ];
    while ((node = nodes.pop()) != null) {
      callback(node);
      if ((children = node.children) && (n = children.length)) {
        var n, children;
        while (--n >= 0) nodes.push(children[n]);
      }
    }
  }
  function d3_layout_hierarchyVisitAfter(node, callback) {
    var nodes = [ node ], nodes2 = [];
    while ((node = nodes.pop()) != null) {
      nodes2.push(node);
      if ((children = node.children) && (n = children.length)) {
        var i = -1, n, children;
        while (++i < n) nodes.push(children[i]);
      }
    }
    while ((node = nodes2.pop()) != null) {
      callback(node);
    }
  }
  function d3_layout_hierarchyChildren(d) {
    return d.children;
  }
  function d3_layout_hierarchyValue(d) {
    return d.value;
  }
  function d3_layout_hierarchySort(a, b) {
    return b.value - a.value;
  }
  function d3_layout_hierarchyLinks(nodes) {
    return d3.merge(nodes.map(function(parent) {
      return (parent.children || []).map(function(child) {
        return {
          source: parent,
          target: child
        };
      });
    }));
  }
  d3.layout.partition = function() {
    var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
    function position(node, x, dx, dy) {
      var children = node.children;
      node.x = x;
      node.y = node.depth * dy;
      node.dx = dx;
      node.dy = dy;
      if (children && (n = children.length)) {
        var i = -1, n, c, d;
        dx = node.value ? dx / node.value : 0;
        while (++i < n) {
          position(c = children[i], x, d = c.value * dx, dy);
          x += d;
        }
      }
    }
    function depth(node) {
      var children = node.children, d = 0;
      if (children && (n = children.length)) {
        var i = -1, n;
        while (++i < n) d = Math.max(d, depth(children[i]));
      }
      return 1 + d;
    }
    function partition(d, i) {
      var nodes = hierarchy.call(this, d, i);
      position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
      return nodes;
    }
    partition.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return partition;
    };
    return d3_layout_hierarchyRebind(partition, hierarchy);
  };
  d3.layout.pie = function() {
    var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
    function pie(data) {
      var n = data.length, values = data.map(function(d, i) {
        return +value.call(pie, d, i);
      }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
      if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
        return values[j] - values[i];
      } : function(i, j) {
        return sort(data[i], data[j]);
      });
      index.forEach(function(i) {
        arcs[i] = {
          data: data[i],
          value: v = values[i],
          startAngle: a,
          endAngle: a += v * k + pa,
          padAngle: p
        };
      });
      return arcs;
    }
    pie.value = function(_) {
      if (!arguments.length) return value;
      value = _;
      return pie;
    };
    pie.sort = function(_) {
      if (!arguments.length) return sort;
      sort = _;
      return pie;
    };
    pie.startAngle = function(_) {
      if (!arguments.length) return startAngle;
      startAngle = _;
      return pie;
    };
    pie.endAngle = function(_) {
      if (!arguments.length) return endAngle;
      endAngle = _;
      return pie;
    };
    pie.padAngle = function(_) {
      if (!arguments.length) return padAngle;
      padAngle = _;
      return pie;
    };
    return pie;
  };
  var d3_layout_pieSortByValue = {};
  d3.layout.stack = function() {
    var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
    function stack(data, index) {
      if (!(n = data.length)) return data;
      var series = data.map(function(d, i) {
        return values.call(stack, d, i);
      });
      var points = series.map(function(d) {
        return d.map(function(v, i) {
          return [ x.call(stack, v, i), y.call(stack, v, i) ];
        });
      });
      var orders = order.call(stack, points, index);
      series = d3.permute(series, orders);
      points = d3.permute(points, orders);
      var offsets = offset.call(stack, points, index);
      var m = series[0].length, n, i, j, o;
      for (j = 0; j < m; ++j) {
        out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
        for (i = 1; i < n; ++i) {
          out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
        }
      }
      return data;
    }
    stack.values = function(x) {
      if (!arguments.length) return values;
      values = x;
      return stack;
    };
    stack.order = function(x) {
      if (!arguments.length) return order;
      order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
      return stack;
    };
    stack.offset = function(x) {
      if (!arguments.length) return offset;
      offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
      return stack;
    };
    stack.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      return stack;
    };
    stack.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      return stack;
    };
    stack.out = function(z) {
      if (!arguments.length) return out;
      out = z;
      return stack;
    };
    return stack;
  };
  function d3_layout_stackX(d) {
    return d.x;
  }
  function d3_layout_stackY(d) {
    return d.y;
  }
  function d3_layout_stackOut(d, y0, y) {
    d.y0 = y0;
    d.y = y;
  }
  var d3_layout_stackOrders = d3.map({
    "inside-out": function(data) {
      var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
        return max[a] - max[b];
      }), top = 0, bottom = 0, tops = [], bottoms = [];
      for (i = 0; i < n; ++i) {
        j = index[i];
        if (top < bottom) {
          top += sums[j];
          tops.push(j);
        } else {
          bottom += sums[j];
          bottoms.push(j);
        }
      }
      return bottoms.reverse().concat(tops);
    },
    reverse: function(data) {
      return d3.range(data.length).reverse();
    },
    "default": d3_layout_stackOrderDefault
  });
  var d3_layout_stackOffsets = d3.map({
    silhouette: function(data) {
      var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o > max) max = o;
        sums.push(o);
      }
      for (j = 0; j < m; ++j) {
        y0[j] = (max - sums[j]) / 2;
      }
      return y0;
    },
    wiggle: function(data) {
      var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
      y0[0] = o = o0 = 0;
      for (j = 1; j < m; ++j) {
        for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
        for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
          for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
            s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
          }
          s2 += s3 * data[i][j][1];
        }
        y0[j] = o -= s1 ? s2 / s1 * dx : 0;
        if (o < o0) o0 = o;
      }
      for (j = 0; j < m; ++j) y0[j] -= o0;
      return y0;
    },
    expand: function(data) {
      var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
      for (j = 0; j < m; ++j) {
        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
        if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
      }
      for (j = 0; j < m; ++j) y0[j] = 0;
      return y0;
    },
    zero: d3_layout_stackOffsetZero
  });
  function d3_layout_stackOrderDefault(data) {
    return d3.range(data.length);
  }
  function d3_layout_stackOffsetZero(data) {
    var j = -1, m = data[0].length, y0 = [];
    while (++j < m) y0[j] = 0;
    return y0;
  }
  function d3_layout_stackMaxIndex(array) {
    var i = 1, j = 0, v = array[0][1], k, n = array.length;
    for (;i < n; ++i) {
      if ((k = array[i][1]) > v) {
        j = i;
        v = k;
      }
    }
    return j;
  }
  function d3_layout_stackReduceSum(d) {
    return d.reduce(d3_layout_stackSum, 0);
  }
  function d3_layout_stackSum(p, d) {
    return p + d[1];
  }
  d3.layout.histogram = function() {
    var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
    function histogram(data, i) {
      var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
      while (++i < m) {
        bin = bins[i] = [];
        bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
        bin.y = 0;
      }
      if (m > 0) {
        i = -1;
        while (++i < n) {
          x = values[i];
          if (x >= range[0] && x <= range[1]) {
            bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
            bin.y += k;
            bin.push(data[i]);
          }
        }
      }
      return bins;
    }
    histogram.value = function(x) {
      if (!arguments.length) return valuer;
      valuer = x;
      return histogram;
    };
    histogram.range = function(x) {
      if (!arguments.length) return ranger;
      ranger = d3_functor(x);
      return histogram;
    };
    histogram.bins = function(x) {
      if (!arguments.length) return binner;
      binner = typeof x === "number" ? function(range) {
        return d3_layout_histogramBinFixed(range, x);
      } : d3_functor(x);
      return histogram;
    };
    histogram.frequency = function(x) {
      if (!arguments.length) return frequency;
      frequency = !!x;
      return histogram;
    };
    return histogram;
  };
  function d3_layout_histogramBinSturges(range, values) {
    return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
  }
  function d3_layout_histogramBinFixed(range, n) {
    var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
    while (++x <= n) f[x] = m * x + b;
    return f;
  }
  function d3_layout_histogramRange(values) {
    return [ d3.min(values), d3.max(values) ];
  }
  d3.layout.pack = function() {
    var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
    function pack(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
        return radius;
      };
      root.x = root.y = 0;
      d3_layout_hierarchyVisitAfter(root, function(d) {
        d.r = +r(d.value);
      });
      d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
      if (padding) {
        var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r += dr;
        });
        d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
        d3_layout_hierarchyVisitAfter(root, function(d) {
          d.r -= dr;
        });
      }
      d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
      return nodes;
    }
    pack.size = function(_) {
      if (!arguments.length) return size;
      size = _;
      return pack;
    };
    pack.radius = function(_) {
      if (!arguments.length) return radius;
      radius = _ == null || typeof _ === "function" ? _ : +_;
      return pack;
    };
    pack.padding = function(_) {
      if (!arguments.length) return padding;
      padding = +_;
      return pack;
    };
    return d3_layout_hierarchyRebind(pack, hierarchy);
  };
  function d3_layout_packSort(a, b) {
    return a.value - b.value;
  }
  function d3_layout_packInsert(a, b) {
    var c = a._pack_next;
    a._pack_next = b;
    b._pack_prev = a;
    b._pack_next = c;
    c._pack_prev = b;
  }
  function d3_layout_packSplice(a, b) {
    a._pack_next = b;
    b._pack_prev = a;
  }
  function d3_layout_packIntersects(a, b) {
    var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
    return .999 * dr * dr > dx * dx + dy * dy;
  }
  function d3_layout_packSiblings(node) {
    if (!(nodes = node.children) || !(n = nodes.length)) return;
    var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
    function bound(node) {
      xMin = Math.min(node.x - node.r, xMin);
      xMax = Math.max(node.x + node.r, xMax);
      yMin = Math.min(node.y - node.r, yMin);
      yMax = Math.max(node.y + node.r, yMax);
    }
    nodes.forEach(d3_layout_packLink);
    a = nodes[0];
    a.x = -a.r;
    a.y = 0;
    bound(a);
    if (n > 1) {
      b = nodes[1];
      b.x = b.r;
      b.y = 0;
      bound(b);
      if (n > 2) {
        c = nodes[2];
        d3_layout_packPlace(a, b, c);
        bound(c);
        d3_layout_packInsert(a, c);
        a._pack_prev = c;
        d3_layout_packInsert(c, b);
        b = a._pack_next;
        for (i = 3; i < n; i++) {
          d3_layout_packPlace(a, b, c = nodes[i]);
          var isect = 0, s1 = 1, s2 = 1;
          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
            if (d3_layout_packIntersects(j, c)) {
              isect = 1;
              break;
            }
          }
          if (isect == 1) {
            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
              if (d3_layout_packIntersects(k, c)) {
                break;
              }
            }
          }
          if (isect) {
            if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
            i--;
          } else {
            d3_layout_packInsert(a, c);
            b = c;
            bound(c);
          }
        }
      }
    }
    var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
    for (i = 0; i < n; i++) {
      c = nodes[i];
      c.x -= cx;
      c.y -= cy;
      cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
    }
    node.r = cr;
    nodes.forEach(d3_layout_packUnlink);
  }
  function d3_layout_packLink(node) {
    node._pack_next = node._pack_prev = node;
  }
  function d3_layout_packUnlink(node) {
    delete node._pack_next;
    delete node._pack_prev;
  }
  function d3_layout_packTransform(node, x, y, k) {
    var children = node.children;
    node.x = x += k * node.x;
    node.y = y += k * node.y;
    node.r *= k;
    if (children) {
      var i = -1, n = children.length;
      while (++i < n) d3_layout_packTransform(children[i], x, y, k);
    }
  }
  function d3_layout_packPlace(a, b, c) {
    var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
    if (db && (dx || dy)) {
      var da = b.r + c.r, dc = dx * dx + dy * dy;
      da *= da;
      db *= db;
      var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
      c.x = a.x + x * dx + y * dy;
      c.y = a.y + x * dy - y * dx;
    } else {
      c.x = a.x + db;
      c.y = a.y;
    }
  }
  d3.layout.tree = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
    function tree(d, i) {
      var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
      d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
      d3_layout_hierarchyVisitBefore(root1, secondWalk);
      if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
        var left = root0, right = root0, bottom = root0;
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          if (node.x < left.x) left = node;
          if (node.x > right.x) right = node;
          if (node.depth > bottom.depth) bottom = node;
        });
        var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
        d3_layout_hierarchyVisitBefore(root0, function(node) {
          node.x = (node.x + tx) * kx;
          node.y = node.depth * ky;
        });
      }
      return nodes;
    }
    function wrapTree(root0) {
      var root1 = {
        A: null,
        children: [ root0 ]
      }, queue = [ root1 ], node1;
      while ((node1 = queue.pop()) != null) {
        for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
          queue.push((children[i] = child = {
            _: children[i],
            parent: node1,
            children: (child = children[i].children) && child.slice() || [],
            A: null,
            a: null,
            z: 0,
            m: 0,
            c: 0,
            s: 0,
            t: null,
            i: i
          }).a = child);
        }
      }
      return root1.children[0];
    }
    function firstWalk(v) {
      var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
      if (children.length) {
        d3_layout_treeShift(v);
        var midpoint = (children[0].z + children[children.length - 1].z) / 2;
        if (w) {
          v.z = w.z + separation(v._, w._);
          v.m = v.z - midpoint;
        } else {
          v.z = midpoint;
        }
      } else if (w) {
        v.z = w.z + separation(v._, w._);
      }
      v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
    }
    function secondWalk(v) {
      v._.x = v.z + v.parent.m;
      v.m += v.parent.m;
    }
    function apportion(v, w, ancestor) {
      if (w) {
        var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
        while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
          vom = d3_layout_treeLeft(vom);
          vop = d3_layout_treeRight(vop);
          vop.a = v;
          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
          if (shift > 0) {
            d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
            sip += shift;
            sop += shift;
          }
          sim += vim.m;
          sip += vip.m;
          som += vom.m;
          sop += vop.m;
        }
        if (vim && !d3_layout_treeRight(vop)) {
          vop.t = vim;
          vop.m += sim - sop;
        }
        if (vip && !d3_layout_treeLeft(vom)) {
          vom.t = vip;
          vom.m += sip - som;
          ancestor = v;
        }
      }
      return ancestor;
    }
    function sizeNode(node) {
      node.x *= size[0];
      node.y = node.depth * size[1];
    }
    tree.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return tree;
    };
    tree.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null ? sizeNode : null;
      return tree;
    };
    tree.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) == null ? null : sizeNode;
      return tree;
    };
    return d3_layout_hierarchyRebind(tree, hierarchy);
  };
  function d3_layout_treeSeparation(a, b) {
    return a.parent == b.parent ? 1 : 2;
  }
  function d3_layout_treeLeft(v) {
    var children = v.children;
    return children.length ? children[0] : v.t;
  }
  function d3_layout_treeRight(v) {
    var children = v.children, n;
    return (n = children.length) ? children[n - 1] : v.t;
  }
  function d3_layout_treeMove(wm, wp, shift) {
    var change = shift / (wp.i - wm.i);
    wp.c -= change;
    wp.s += shift;
    wm.c += change;
    wp.z += shift;
    wp.m += shift;
  }
  function d3_layout_treeShift(v) {
    var shift = 0, change = 0, children = v.children, i = children.length, w;
    while (--i >= 0) {
      w = children[i];
      w.z += shift;
      w.m += shift;
      shift += w.s + (change += w.c);
    }
  }
  function d3_layout_treeAncestor(vim, v, ancestor) {
    return vim.a.parent === v.parent ? vim.a : ancestor;
  }
  d3.layout.cluster = function() {
    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
    function cluster(d, i) {
      var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
      d3_layout_hierarchyVisitAfter(root, function(node) {
        var children = node.children;
        if (children && children.length) {
          node.x = d3_layout_clusterX(children);
          node.y = d3_layout_clusterY(children);
        } else {
          node.x = previousNode ? x += separation(node, previousNode) : 0;
          node.y = 0;
          previousNode = node;
        }
      });
      var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
      d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
        node.x = (node.x - root.x) * size[0];
        node.y = (root.y - node.y) * size[1];
      } : function(node) {
        node.x = (node.x - x0) / (x1 - x0) * size[0];
        node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
      });
      return nodes;
    }
    cluster.separation = function(x) {
      if (!arguments.length) return separation;
      separation = x;
      return cluster;
    };
    cluster.size = function(x) {
      if (!arguments.length) return nodeSize ? null : size;
      nodeSize = (size = x) == null;
      return cluster;
    };
    cluster.nodeSize = function(x) {
      if (!arguments.length) return nodeSize ? size : null;
      nodeSize = (size = x) != null;
      return cluster;
    };
    return d3_layout_hierarchyRebind(cluster, hierarchy);
  };
  function d3_layout_clusterY(children) {
    return 1 + d3.max(children, function(child) {
      return child.y;
    });
  }
  function d3_layout_clusterX(children) {
    return children.reduce(function(x, child) {
      return x + child.x;
    }, 0) / children.length;
  }
  function d3_layout_clusterLeft(node) {
    var children = node.children;
    return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
  }
  function d3_layout_clusterRight(node) {
    var children = node.children, n;
    return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
  }
  d3.layout.treemap = function() {
    var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
    function scale(children, k) {
      var i = -1, n = children.length, child, area;
      while (++i < n) {
        area = (child = children[i]).value * (k < 0 ? 0 : k);
        child.area = isNaN(area) || area <= 0 ? 0 : area;
      }
    }
    function squarify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while ((n = remaining.length) > 0) {
          row.push(child = remaining[n - 1]);
          row.area += child.area;
          if (mode !== "squarify" || (score = worst(row, u)) <= best) {
            remaining.pop();
            best = score;
          } else {
            row.area -= row.pop().area;
            position(row, u, rect, false);
            u = Math.min(rect.dx, rect.dy);
            row.length = row.area = 0;
            best = Infinity;
          }
        }
        if (row.length) {
          position(row, u, rect, true);
          row.length = row.area = 0;
        }
        children.forEach(squarify);
      }
    }
    function stickify(node) {
      var children = node.children;
      if (children && children.length) {
        var rect = pad(node), remaining = children.slice(), child, row = [];
        scale(remaining, rect.dx * rect.dy / node.value);
        row.area = 0;
        while (child = remaining.pop()) {
          row.push(child);
          row.area += child.area;
          if (child.z != null) {
            position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
            row.length = row.area = 0;
          }
        }
        children.forEach(stickify);
      }
    }
    function worst(row, u) {
      var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
      while (++i < n) {
        if (!(r = row[i].area)) continue;
        if (r < rmin) rmin = r;
        if (r > rmax) rmax = r;
      }
      s *= s;
      u *= u;
      return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
    }
    function position(row, u, rect, flush) {
      var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
      if (u == rect.dx) {
        if (flush || v > rect.dy) v = rect.dy;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dy = v;
          x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
        }
        o.z = true;
        o.dx += rect.x + rect.dx - x;
        rect.y += v;
        rect.dy -= v;
      } else {
        if (flush || v > rect.dx) v = rect.dx;
        while (++i < n) {
          o = row[i];
          o.x = x;
          o.y = y;
          o.dx = v;
          y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
        }
        o.z = false;
        o.dy += rect.y + rect.dy - y;
        rect.x += v;
        rect.dx -= v;
      }
    }
    function treemap(d) {
      var nodes = stickies || hierarchy(d), root = nodes[0];
      root.x = root.y = 0;
      if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
      if (stickies) hierarchy.revalue(root);
      scale([ root ], root.dx * root.dy / root.value);
      (stickies ? stickify : squarify)(root);
      if (sticky) stickies = nodes;
      return nodes;
    }
    treemap.size = function(x) {
      if (!arguments.length) return size;
      size = x;
      return treemap;
    };
    treemap.padding = function(x) {
      if (!arguments.length) return padding;
      function padFunction(node) {
        var p = x.call(treemap, node, node.depth);
        return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
      }
      function padConstant(node) {
        return d3_layout_treemapPad(node, x);
      }
      var type;
      pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], 
      padConstant) : padConstant;
      return treemap;
    };
    treemap.round = function(x) {
      if (!arguments.length) return round != Number;
      round = x ? Math.round : Number;
      return treemap;
    };
    treemap.sticky = function(x) {
      if (!arguments.length) return sticky;
      sticky = x;
      stickies = null;
      return treemap;
    };
    treemap.ratio = function(x) {
      if (!arguments.length) return ratio;
      ratio = x;
      return treemap;
    };
    treemap.mode = function(x) {
      if (!arguments.length) return mode;
      mode = x + "";
      return treemap;
    };
    return d3_layout_hierarchyRebind(treemap, hierarchy);
  };
  function d3_layout_treemapPadNull(node) {
    return {
      x: node.x,
      y: node.y,
      dx: node.dx,
      dy: node.dy
    };
  }
  function d3_layout_treemapPad(node, padding) {
    var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
    if (dx < 0) {
      x += dx / 2;
      dx = 0;
    }
    if (dy < 0) {
      y += dy / 2;
      dy = 0;
    }
    return {
      x: x,
      y: y,
      dx: dx,
      dy: dy
    };
  }
  d3.random = {
    normal: function(µ, σ) {
      var n = arguments.length;
      if (n < 2) σ = 1;
      if (n < 1) µ = 0;
      return function() {
        var x, y, r;
        do {
          x = Math.random() * 2 - 1;
          y = Math.random() * 2 - 1;
          r = x * x + y * y;
        } while (!r || r > 1);
        return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
      };
    },
    logNormal: function() {
      var random = d3.random.normal.apply(d3, arguments);
      return function() {
        return Math.exp(random());
      };
    },
    bates: function(m) {
      var random = d3.random.irwinHall(m);
      return function() {
        return random() / m;
      };
    },
    irwinHall: function(m) {
      return function() {
        for (var s = 0, j = 0; j < m; j++) s += Math.random();
        return s;
      };
    }
  };
  d3.scale = {};
  function d3_scaleExtent(domain) {
    var start = domain[0], stop = domain[domain.length - 1];
    return start < stop ? [ start, stop ] : [ stop, start ];
  }
  function d3_scaleRange(scale) {
    return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
  }
  function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
    var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
    return function(x) {
      return i(u(x));
    };
  }
  function d3_scale_nice(domain, nice) {
    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
    if (x1 < x0) {
      dx = i0, i0 = i1, i1 = dx;
      dx = x0, x0 = x1, x1 = dx;
    }
    domain[i0] = nice.floor(x0);
    domain[i1] = nice.ceil(x1);
    return domain;
  }
  function d3_scale_niceStep(step) {
    return step ? {
      floor: function(x) {
        return Math.floor(x / step) * step;
      },
      ceil: function(x) {
        return Math.ceil(x / step) * step;
      }
    } : d3_scale_niceIdentity;
  }
  var d3_scale_niceIdentity = {
    floor: d3_identity,
    ceil: d3_identity
  };
  function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
    var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
    if (domain[k] < domain[0]) {
      domain = domain.slice().reverse();
      range = range.slice().reverse();
    }
    while (++j <= k) {
      u.push(uninterpolate(domain[j - 1], domain[j]));
      i.push(interpolate(range[j - 1], range[j]));
    }
    return function(x) {
      var j = d3.bisect(domain, x, 1, k) - 1;
      return i[j](u[j](x));
    };
  }
  d3.scale.linear = function() {
    return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
  };
  function d3_scale_linear(domain, range, interpolate, clamp) {
    var output, input;
    function rescale() {
      var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
      output = linear(domain, range, uninterpolate, interpolate);
      input = linear(range, domain, uninterpolate, d3_interpolate);
      return scale;
    }
    function scale(x) {
      return output(x);
    }
    scale.invert = function(y) {
      return input(y);
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(Number);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.rangeRound = function(x) {
      return scale.range(x).interpolate(d3_interpolateRound);
    };
    scale.clamp = function(x) {
      if (!arguments.length) return clamp;
      clamp = x;
      return rescale();
    };
    scale.interpolate = function(x) {
      if (!arguments.length) return interpolate;
      interpolate = x;
      return rescale();
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      d3_scale_linearNice(domain, m);
      return rescale();
    };
    scale.copy = function() {
      return d3_scale_linear(domain, range, interpolate, clamp);
    };
    return rescale();
  }
  function d3_scale_linearRebind(scale, linear) {
    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
  }
  function d3_scale_linearNice(domain, m) {
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
    return domain;
  }
  function d3_scale_linearTickRange(domain, m) {
    if (m == null) m = 10;
    var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
    if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
    extent[0] = Math.ceil(extent[0] / step) * step;
    extent[1] = Math.floor(extent[1] / step) * step + step * .5;
    extent[2] = step;
    return extent;
  }
  function d3_scale_linearTicks(domain, m) {
    return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
  }
  function d3_scale_linearTickFormat(domain, m, format) {
    var range = d3_scale_linearTickRange(domain, m);
    if (format) {
      var match = d3_format_re.exec(format);
      match.shift();
      if (match[8] === "s") {
        var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
        if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
        match[8] = "f";
        format = d3.format(match.join(""));
        return function(d) {
          return format(prefix.scale(d)) + prefix.symbol;
        };
      }
      if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
      format = match.join("");
    } else {
      format = ",." + d3_scale_linearPrecision(range[2]) + "f";
    }
    return d3.format(format);
  }
  var d3_scale_linearFormatSignificant = {
    s: 1,
    g: 1,
    p: 1,
    r: 1,
    e: 1
  };
  function d3_scale_linearPrecision(value) {
    return -Math.floor(Math.log(value) / Math.LN10 + .01);
  }
  function d3_scale_linearFormatPrecision(type, range) {
    var p = d3_scale_linearPrecision(range[2]);
    return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
  }
  d3.scale.log = function() {
    return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
  };
  function d3_scale_log(linear, base, positive, domain) {
    function log(x) {
      return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
    }
    function pow(x) {
      return positive ? Math.pow(base, x) : -Math.pow(base, -x);
    }
    function scale(x) {
      return linear(log(x));
    }
    scale.invert = function(x) {
      return pow(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      positive = x[0] >= 0;
      linear.domain((domain = x.map(Number)).map(log));
      return scale;
    };
    scale.base = function(_) {
      if (!arguments.length) return base;
      base = +_;
      linear.domain(domain.map(log));
      return scale;
    };
    scale.nice = function() {
      var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
      linear.domain(niced);
      domain = niced.map(pow);
      return scale;
    };
    scale.ticks = function() {
      var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
      if (isFinite(j - i)) {
        if (positive) {
          for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
          ticks.push(pow(i));
        } else {
          ticks.push(pow(i));
          for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
        }
        for (i = 0; ticks[i] < u; i++) {}
        for (j = ticks.length; ticks[j - 1] > v; j--) {}
        ticks = ticks.slice(i, j);
      }
      return ticks;
    };
    scale.tickFormat = function(n, format) {
      if (!arguments.length) return d3_scale_logFormat;
      if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
      var k = Math.max(1, base * n / scale.ticks().length);
      return function(d) {
        var i = d / pow(Math.round(log(d)));
        if (i * base < base - .5) i *= base;
        return i <= k ? format(d) : "";
      };
    };
    scale.copy = function() {
      return d3_scale_log(linear.copy(), base, positive, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
    floor: function(x) {
      return -Math.ceil(-x);
    },
    ceil: function(x) {
      return -Math.floor(-x);
    }
  };
  d3.scale.pow = function() {
    return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
  };
  function d3_scale_pow(linear, exponent, domain) {
    var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
    function scale(x) {
      return linear(powp(x));
    }
    scale.invert = function(x) {
      return powb(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      linear.domain((domain = x.map(Number)).map(powp));
      return scale;
    };
    scale.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    scale.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    scale.nice = function(m) {
      return scale.domain(d3_scale_linearNice(domain, m));
    };
    scale.exponent = function(x) {
      if (!arguments.length) return exponent;
      powp = d3_scale_powPow(exponent = x);
      powb = d3_scale_powPow(1 / exponent);
      linear.domain(domain.map(powp));
      return scale;
    };
    scale.copy = function() {
      return d3_scale_pow(linear.copy(), exponent, domain);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_scale_powPow(e) {
    return function(x) {
      return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
    };
  }
  d3.scale.sqrt = function() {
    return d3.scale.pow().exponent(.5);
  };
  d3.scale.ordinal = function() {
    return d3_scale_ordinal([], {
      t: "range",
      a: [ [] ]
    });
  };
  function d3_scale_ordinal(domain, ranger) {
    var index, range, rangeBand;
    function scale(x) {
      return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
    }
    function steps(start, step) {
      return d3.range(domain.length).map(function(i) {
        return start + step * i;
      });
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = [];
      index = new d3_Map();
      var i = -1, n = x.length, xi;
      while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
      return scale[ranger.t].apply(scale, ranger.a);
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      rangeBand = 0;
      ranger = {
        t: "range",
        a: arguments
      };
      return scale;
    };
    scale.rangePoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 
      0) : (stop - start) / (domain.length - 1 + padding);
      range = steps(start + step * padding / 2, step);
      rangeBand = 0;
      ranger = {
        t: "rangePoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundPoints = function(x, padding) {
      if (arguments.length < 2) padding = 0;
      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 
      0) : (stop - start) / (domain.length - 1 + padding) | 0;
      range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
      rangeBand = 0;
      ranger = {
        t: "rangeRoundPoints",
        a: arguments
      };
      return scale;
    };
    scale.rangeBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
      range = steps(start + step * outerPadding, step);
      if (reverse) range.reverse();
      rangeBand = step * (1 - padding);
      ranger = {
        t: "rangeBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeRoundBands = function(x, padding, outerPadding) {
      if (arguments.length < 2) padding = 0;
      if (arguments.length < 3) outerPadding = padding;
      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
      range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
      if (reverse) range.reverse();
      rangeBand = Math.round(step * (1 - padding));
      ranger = {
        t: "rangeRoundBands",
        a: arguments
      };
      return scale;
    };
    scale.rangeBand = function() {
      return rangeBand;
    };
    scale.rangeExtent = function() {
      return d3_scaleExtent(ranger.a[0]);
    };
    scale.copy = function() {
      return d3_scale_ordinal(domain, ranger);
    };
    return scale.domain(domain);
  }
  d3.scale.category10 = function() {
    return d3.scale.ordinal().range(d3_category10);
  };
  d3.scale.category20 = function() {
    return d3.scale.ordinal().range(d3_category20);
  };
  d3.scale.category20b = function() {
    return d3.scale.ordinal().range(d3_category20b);
  };
  d3.scale.category20c = function() {
    return d3.scale.ordinal().range(d3_category20c);
  };
  var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
  var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
  var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
  var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
  d3.scale.quantile = function() {
    return d3_scale_quantile([], []);
  };
  function d3_scale_quantile(domain, range) {
    var thresholds;
    function rescale() {
      var k = 0, q = range.length;
      thresholds = [];
      while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
      return scale;
    }
    function scale(x) {
      if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
    }
    scale.domain = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.quantiles = function() {
      return thresholds;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
    };
    scale.copy = function() {
      return d3_scale_quantile(domain, range);
    };
    return rescale();
  }
  d3.scale.quantize = function() {
    return d3_scale_quantize(0, 1, [ 0, 1 ]);
  };
  function d3_scale_quantize(x0, x1, range) {
    var kx, i;
    function scale(x) {
      return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
    }
    function rescale() {
      kx = range.length / (x1 - x0);
      i = range.length - 1;
      return scale;
    }
    scale.domain = function(x) {
      if (!arguments.length) return [ x0, x1 ];
      x0 = +x[0];
      x1 = +x[x.length - 1];
      return rescale();
    };
    scale.range = function(x) {
      if (!arguments.length) return range;
      range = x;
      return rescale();
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      y = y < 0 ? NaN : y / kx + x0;
      return [ y, y + 1 / kx ];
    };
    scale.copy = function() {
      return d3_scale_quantize(x0, x1, range);
    };
    return rescale();
  }
  d3.scale.threshold = function() {
    return d3_scale_threshold([ .5 ], [ 0, 1 ]);
  };
  function d3_scale_threshold(domain, range) {
    function scale(x) {
      if (x <= x) return range[d3.bisect(domain, x)];
    }
    scale.domain = function(_) {
      if (!arguments.length) return domain;
      domain = _;
      return scale;
    };
    scale.range = function(_) {
      if (!arguments.length) return range;
      range = _;
      return scale;
    };
    scale.invertExtent = function(y) {
      y = range.indexOf(y);
      return [ domain[y - 1], domain[y] ];
    };
    scale.copy = function() {
      return d3_scale_threshold(domain, range);
    };
    return scale;
  }
  d3.scale.identity = function() {
    return d3_scale_identity([ 0, 1 ]);
  };
  function d3_scale_identity(domain) {
    function identity(x) {
      return +x;
    }
    identity.invert = identity;
    identity.domain = identity.range = function(x) {
      if (!arguments.length) return domain;
      domain = x.map(identity);
      return identity;
    };
    identity.ticks = function(m) {
      return d3_scale_linearTicks(domain, m);
    };
    identity.tickFormat = function(m, format) {
      return d3_scale_linearTickFormat(domain, m, format);
    };
    identity.copy = function() {
      return d3_scale_identity(domain);
    };
    return identity;
  }
  d3.svg = {};
  function d3_zero() {
    return 0;
  }
  d3.svg.arc = function() {
    var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
    function arc() {
      var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
      if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
      if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
      var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
      if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
        rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
        if (!cw) p1 *= -1;
        if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
        if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
      }
      if (r1) {
        x0 = r1 * Math.cos(a0 + p1);
        y0 = r1 * Math.sin(a0 + p1);
        x1 = r1 * Math.cos(a1 - p1);
        y1 = r1 * Math.sin(a1 - p1);
        var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
        if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
          var h1 = (a0 + a1) / 2;
          x0 = r1 * Math.cos(h1);
          y0 = r1 * Math.sin(h1);
          x1 = y1 = null;
        }
      } else {
        x0 = y0 = 0;
      }
      if (r0) {
        x2 = r0 * Math.cos(a1 - p0);
        y2 = r0 * Math.sin(a1 - p0);
        x3 = r0 * Math.cos(a0 + p0);
        y3 = r0 * Math.sin(a0 + p0);
        var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
        if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
          var h0 = (a0 + a1) / 2;
          x2 = r0 * Math.cos(h0);
          y2 = r0 * Math.sin(h0);
          x3 = y3 = null;
        }
      } else {
        x2 = y2 = 0;
      }
      if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
        cr = r0 < r1 ^ cw ? 0 : 1;
        var rc1 = rc, rc0 = rc;
        if (da < π) {
          var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
          rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
          rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
        }
        if (x1 != null) {
          var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
          if (rc === rc1) {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
          } else {
            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
          }
        } else {
          path.push("M", x0, ",", y0);
        }
        if (x3 != null) {
          var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
          if (rc === rc0) {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          } else {
            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
          }
        } else {
          path.push("L", x2, ",", y2);
        }
      } else {
        path.push("M", x0, ",", y0);
        if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
        path.push("L", x2, ",", y2);
        if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
      }
      path.push("Z");
      return path.join("");
    }
    function circleSegment(r1, cw) {
      return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
    }
    arc.innerRadius = function(v) {
      if (!arguments.length) return innerRadius;
      innerRadius = d3_functor(v);
      return arc;
    };
    arc.outerRadius = function(v) {
      if (!arguments.length) return outerRadius;
      outerRadius = d3_functor(v);
      return arc;
    };
    arc.cornerRadius = function(v) {
      if (!arguments.length) return cornerRadius;
      cornerRadius = d3_functor(v);
      return arc;
    };
    arc.padRadius = function(v) {
      if (!arguments.length) return padRadius;
      padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
      return arc;
    };
    arc.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return arc;
    };
    arc.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return arc;
    };
    arc.padAngle = function(v) {
      if (!arguments.length) return padAngle;
      padAngle = d3_functor(v);
      return arc;
    };
    arc.centroid = function() {
      var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
      return [ Math.cos(a) * r, Math.sin(a) * r ];
    };
    return arc;
  };
  var d3_svg_arcAuto = "auto";
  function d3_svg_arcInnerRadius(d) {
    return d.innerRadius;
  }
  function d3_svg_arcOuterRadius(d) {
    return d.outerRadius;
  }
  function d3_svg_arcStartAngle(d) {
    return d.startAngle;
  }
  function d3_svg_arcEndAngle(d) {
    return d.endAngle;
  }
  function d3_svg_arcPadAngle(d) {
    return d && d.padAngle;
  }
  function d3_svg_arcSweep(x0, y0, x1, y1) {
    return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
  }
  function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
    var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
    return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
  }
  function d3_svg_line(projection) {
    var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
    function line(data) {
      var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
      function segment() {
        segments.push("M", interpolate(projection(points), tension));
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
        } else if (points.length) {
          segment();
          points = [];
        }
      }
      if (points.length) segment();
      return segments.length ? segments.join("") : null;
    }
    line.x = function(_) {
      if (!arguments.length) return x;
      x = _;
      return line;
    };
    line.y = function(_) {
      if (!arguments.length) return y;
      y = _;
      return line;
    };
    line.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return line;
    };
    line.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      return line;
    };
    line.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return line;
    };
    return line;
  }
  d3.svg.line = function() {
    return d3_svg_line(d3_identity);
  };
  var d3_svg_lineInterpolators = d3.map({
    linear: d3_svg_lineLinear,
    "linear-closed": d3_svg_lineLinearClosed,
    step: d3_svg_lineStep,
    "step-before": d3_svg_lineStepBefore,
    "step-after": d3_svg_lineStepAfter,
    basis: d3_svg_lineBasis,
    "basis-open": d3_svg_lineBasisOpen,
    "basis-closed": d3_svg_lineBasisClosed,
    bundle: d3_svg_lineBundle,
    cardinal: d3_svg_lineCardinal,
    "cardinal-open": d3_svg_lineCardinalOpen,
    "cardinal-closed": d3_svg_lineCardinalClosed,
    monotone: d3_svg_lineMonotone
  });
  d3_svg_lineInterpolators.forEach(function(key, value) {
    value.key = key;
    value.closed = /-closed$/.test(key);
  });
  function d3_svg_lineLinear(points) {
    return points.length > 1 ? points.join("L") : points + "Z";
  }
  function d3_svg_lineLinearClosed(points) {
    return points.join("L") + "Z";
  }
  function d3_svg_lineStep(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
    if (n > 1) path.push("H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepBefore(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
    return path.join("");
  }
  function d3_svg_lineStepAfter(points) {
    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
    while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
    return path.join("");
  }
  function d3_svg_lineCardinalOpen(points, tension) {
    return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineCardinalClosed(points, tension) {
    return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), 
    points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
  }
  function d3_svg_lineCardinal(points, tension) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
  }
  function d3_svg_lineHermite(points, tangents) {
    if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
      return d3_svg_lineLinear(points);
    }
    var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
    if (quad) {
      path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
      p0 = points[1];
      pi = 2;
    }
    if (tangents.length > 1) {
      t = tangents[1];
      p = points[pi];
      pi++;
      path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      for (var i = 2; i < tangents.length; i++, pi++) {
        p = points[pi];
        t = tangents[i];
        path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
      }
    }
    if (quad) {
      var lp = points[pi];
      path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
    }
    return path;
  }
  function d3_svg_lineCardinalTangents(points, tension) {
    var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
    while (++i < n) {
      p0 = p1;
      p1 = p2;
      p2 = points[i];
      tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
    }
    return tangents;
  }
  function d3_svg_lineBasis(points) {
    if (points.length < 3) return d3_svg_lineLinear(points);
    var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    points.push(points[n - 1]);
    while (++i <= n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    points.pop();
    path.push("L", pi);
    return path.join("");
  }
  function d3_svg_lineBasisOpen(points) {
    if (points.length < 4) return d3_svg_lineLinear(points);
    var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
    while (++i < 3) {
      pi = points[i];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
    --i;
    while (++i < n) {
      pi = points[i];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBasisClosed(points) {
    var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
    while (++i < 4) {
      pi = points[i % n];
      px.push(pi[0]);
      py.push(pi[1]);
    }
    path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
    --i;
    while (++i < m) {
      pi = points[i % n];
      px.shift();
      px.push(pi[0]);
      py.shift();
      py.push(pi[1]);
      d3_svg_lineBasisBezier(path, px, py);
    }
    return path.join("");
  }
  function d3_svg_lineBundle(points, tension) {
    var n = points.length - 1;
    if (n) {
      var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
      while (++i <= n) {
        p = points[i];
        t = i / n;
        p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
        p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
      }
    }
    return d3_svg_lineBasis(points);
  }
  function d3_svg_lineDot4(a, b) {
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  }
  var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
  function d3_svg_lineBasisBezier(path, x, y) {
    path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
  }
  function d3_svg_lineSlope(p0, p1) {
    return (p1[1] - p0[1]) / (p1[0] - p0[0]);
  }
  function d3_svg_lineFiniteDifferences(points) {
    var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
    while (++i < j) {
      m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
    }
    m[i] = d;
    return m;
  }
  function d3_svg_lineMonotoneTangents(points) {
    var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
    while (++i < j) {
      d = d3_svg_lineSlope(points[i], points[i + 1]);
      if (abs(d) < ε) {
        m[i] = m[i + 1] = 0;
      } else {
        a = m[i] / d;
        b = m[i + 1] / d;
        s = a * a + b * b;
        if (s > 9) {
          s = d * 3 / Math.sqrt(s);
          m[i] = s * a;
          m[i + 1] = s * b;
        }
      }
    }
    i = -1;
    while (++i <= j) {
      s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
      tangents.push([ s || 0, m[i] * s || 0 ]);
    }
    return tangents;
  }
  function d3_svg_lineMonotone(points) {
    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
  }
  d3.svg.line.radial = function() {
    var line = d3_svg_line(d3_svg_lineRadial);
    line.radius = line.x, delete line.x;
    line.angle = line.y, delete line.y;
    return line;
  };
  function d3_svg_lineRadial(points) {
    var point, i = -1, n = points.length, r, a;
    while (++i < n) {
      point = points[i];
      r = point[0];
      a = point[1] - halfπ;
      point[0] = r * Math.cos(a);
      point[1] = r * Math.sin(a);
    }
    return points;
  }
  function d3_svg_area(projection) {
    var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
    function area(data) {
      var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
        return x;
      } : d3_functor(x1), fy1 = y0 === y1 ? function() {
        return y;
      } : d3_functor(y1), x, y;
      function segment() {
        segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
      }
      while (++i < n) {
        if (defined.call(this, d = data[i], i)) {
          points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
          points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
        } else if (points0.length) {
          segment();
          points0 = [];
          points1 = [];
        }
      }
      if (points0.length) segment();
      return segments.length ? segments.join("") : null;
    }
    area.x = function(_) {
      if (!arguments.length) return x1;
      x0 = x1 = _;
      return area;
    };
    area.x0 = function(_) {
      if (!arguments.length) return x0;
      x0 = _;
      return area;
    };
    area.x1 = function(_) {
      if (!arguments.length) return x1;
      x1 = _;
      return area;
    };
    area.y = function(_) {
      if (!arguments.length) return y1;
      y0 = y1 = _;
      return area;
    };
    area.y0 = function(_) {
      if (!arguments.length) return y0;
      y0 = _;
      return area;
    };
    area.y1 = function(_) {
      if (!arguments.length) return y1;
      y1 = _;
      return area;
    };
    area.defined = function(_) {
      if (!arguments.length) return defined;
      defined = _;
      return area;
    };
    area.interpolate = function(_) {
      if (!arguments.length) return interpolateKey;
      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
      interpolateReverse = interpolate.reverse || interpolate;
      L = interpolate.closed ? "M" : "L";
      return area;
    };
    area.tension = function(_) {
      if (!arguments.length) return tension;
      tension = _;
      return area;
    };
    return area;
  }
  d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
  d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
  d3.svg.area = function() {
    return d3_svg_area(d3_identity);
  };
  d3.svg.area.radial = function() {
    var area = d3_svg_area(d3_svg_lineRadial);
    area.radius = area.x, delete area.x;
    area.innerRadius = area.x0, delete area.x0;
    area.outerRadius = area.x1, delete area.x1;
    area.angle = area.y, delete area.y;
    area.startAngle = area.y0, delete area.y0;
    area.endAngle = area.y1, delete area.y1;
    return area;
  };
  d3.svg.chord = function() {
    var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
    function chord(d, i) {
      var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
      return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
    }
    function subgroup(self, f, d, i) {
      var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
      return {
        r: r,
        a0: a0,
        a1: a1,
        p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
        p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
      };
    }
    function equals(a, b) {
      return a.a0 == b.a0 && a.a1 == b.a1;
    }
    function arc(r, p, a) {
      return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
    }
    function curve(r0, p0, r1, p1) {
      return "Q 0,0 " + p1;
    }
    chord.radius = function(v) {
      if (!arguments.length) return radius;
      radius = d3_functor(v);
      return chord;
    };
    chord.source = function(v) {
      if (!arguments.length) return source;
      source = d3_functor(v);
      return chord;
    };
    chord.target = function(v) {
      if (!arguments.length) return target;
      target = d3_functor(v);
      return chord;
    };
    chord.startAngle = function(v) {
      if (!arguments.length) return startAngle;
      startAngle = d3_functor(v);
      return chord;
    };
    chord.endAngle = function(v) {
      if (!arguments.length) return endAngle;
      endAngle = d3_functor(v);
      return chord;
    };
    return chord;
  };
  function d3_svg_chordRadius(d) {
    return d.radius;
  }
  d3.svg.diagonal = function() {
    var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
    function diagonal(d, i) {
      var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
        x: p0.x,
        y: m
      }, {
        x: p3.x,
        y: m
      }, p3 ];
      p = p.map(projection);
      return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
    }
    diagonal.source = function(x) {
      if (!arguments.length) return source;
      source = d3_functor(x);
      return diagonal;
    };
    diagonal.target = function(x) {
      if (!arguments.length) return target;
      target = d3_functor(x);
      return diagonal;
    };
    diagonal.projection = function(x) {
      if (!arguments.length) return projection;
      projection = x;
      return diagonal;
    };
    return diagonal;
  };
  function d3_svg_diagonalProjection(d) {
    return [ d.x, d.y ];
  }
  d3.svg.diagonal.radial = function() {
    var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
    diagonal.projection = function(x) {
      return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
    };
    return diagonal;
  };
  function d3_svg_diagonalRadialProjection(projection) {
    return function() {
      var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
      return [ r * Math.cos(a), r * Math.sin(a) ];
    };
  }
  d3.svg.symbol = function() {
    var type = d3_svg_symbolType, size = d3_svg_symbolSize;
    function symbol(d, i) {
      return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
    }
    symbol.type = function(x) {
      if (!arguments.length) return type;
      type = d3_functor(x);
      return symbol;
    };
    symbol.size = function(x) {
      if (!arguments.length) return size;
      size = d3_functor(x);
      return symbol;
    };
    return symbol;
  };
  function d3_svg_symbolSize() {
    return 64;
  }
  function d3_svg_symbolType() {
    return "circle";
  }
  function d3_svg_symbolCircle(size) {
    var r = Math.sqrt(size / π);
    return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
  }
  var d3_svg_symbols = d3.map({
    circle: d3_svg_symbolCircle,
    cross: function(size) {
      var r = Math.sqrt(size / 5) / 2;
      return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
    },
    diamond: function(size) {
      var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
      return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
    },
    square: function(size) {
      var r = Math.sqrt(size) / 2;
      return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
    },
    "triangle-down": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
    },
    "triangle-up": function(size) {
      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
      return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
    }
  });
  d3.svg.symbolTypes = d3_svg_symbols.keys();
  var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
  d3_selectionPrototype.transition = function(name) {
    var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
      time: Date.now(),
      ease: d3_ease_cubicInOut,
      delay: 0,
      duration: 250
    };
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_selectionPrototype.interrupt = function(name) {
    return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
  };
  var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
  function d3_selection_interruptNS(ns) {
    return function() {
      var lock, activeId, active;
      if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
        active.timer.c = null;
        active.timer.t = NaN;
        if (--lock.count) delete lock[activeId]; else delete this[ns];
        lock.active += .5;
        active.event && active.event.interrupt.call(this, this.__data__, active.index);
      }
    };
  }
  function d3_transition(groups, ns, id) {
    d3_subclass(groups, d3_transitionPrototype);
    groups.namespace = ns;
    groups.id = id;
    return groups;
  }
  var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
  d3_transitionPrototype.call = d3_selectionPrototype.call;
  d3_transitionPrototype.empty = d3_selectionPrototype.empty;
  d3_transitionPrototype.node = d3_selectionPrototype.node;
  d3_transitionPrototype.size = d3_selectionPrototype.size;
  d3.transition = function(selection, name) {
    return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
  };
  d3.transition.prototype = d3_transitionPrototype;
  d3_transitionPrototype.select = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
    selector = d3_selection_selector(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
          if ("__data__" in node) subnode.__data__ = node.__data__;
          d3_transitionNode(subnode, i, ns, id, node[ns][id]);
          subgroup.push(subnode);
        } else {
          subgroup.push(null);
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.selectAll = function(selector) {
    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
    selector = d3_selection_selectorAll(selector);
    for (var j = -1, m = this.length; ++j < m; ) {
      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
        if (node = group[i]) {
          transition = node[ns][id];
          subnodes = selector.call(node, node.__data__, i, j);
          subgroups.push(subgroup = []);
          for (var k = -1, o = subnodes.length; ++k < o; ) {
            if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
            subgroup.push(subnode);
          }
        }
      }
    }
    return d3_transition(subgroups, ns, id);
  };
  d3_transitionPrototype.filter = function(filter) {
    var subgroups = [], subgroup, group, node;
    if (typeof filter !== "function") filter = d3_selection_filter(filter);
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
          subgroup.push(node);
        }
      }
    }
    return d3_transition(subgroups, this.namespace, this.id);
  };
  d3_transitionPrototype.tween = function(name, tween) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
    return d3_selection_each(this, tween == null ? function(node) {
      node[ns][id].tween.remove(name);
    } : function(node) {
      node[ns][id].tween.set(name, tween);
    });
  };
  function d3_transition_tween(groups, name, value, tween) {
    var id = groups.id, ns = groups.namespace;
    return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
      node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
    } : (value = tween(value), function(node) {
      node[ns][id].tween.set(name, value);
    }));
  }
  d3_transitionPrototype.attr = function(nameNS, value) {
    if (arguments.length < 2) {
      for (value in nameNS) this.attr(value, nameNS[value]);
      return this;
    }
    var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
    function attrNull() {
      this.removeAttribute(name);
    }
    function attrNullNS() {
      this.removeAttributeNS(name.space, name.local);
    }
    function attrTween(b) {
      return b == null ? attrNull : (b += "", function() {
        var a = this.getAttribute(name), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttribute(name, i(t));
        });
      });
    }
    function attrTweenNS(b) {
      return b == null ? attrNullNS : (b += "", function() {
        var a = this.getAttributeNS(name.space, name.local), i;
        return a !== b && (i = interpolate(a, b), function(t) {
          this.setAttributeNS(name.space, name.local, i(t));
        });
      });
    }
    return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.attrTween = function(nameNS, tween) {
    var name = d3.ns.qualify(nameNS);
    function attrTween(d, i) {
      var f = tween.call(this, d, i, this.getAttribute(name));
      return f && function(t) {
        this.setAttribute(name, f(t));
      };
    }
    function attrTweenNS(d, i) {
      var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
      return f && function(t) {
        this.setAttributeNS(name.space, name.local, f(t));
      };
    }
    return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
  };
  d3_transitionPrototype.style = function(name, value, priority) {
    var n = arguments.length;
    if (n < 3) {
      if (typeof name !== "string") {
        if (n < 2) value = "";
        for (priority in name) this.style(priority, name[priority], value);
        return this;
      }
      priority = "";
    }
    function styleNull() {
      this.style.removeProperty(name);
    }
    function styleString(b) {
      return b == null ? styleNull : (b += "", function() {
        var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
        return a !== b && (i = d3_interpolate(a, b), function(t) {
          this.style.setProperty(name, i(t), priority);
        });
      });
    }
    return d3_transition_tween(this, "style." + name, value, styleString);
  };
  d3_transitionPrototype.styleTween = function(name, tween, priority) {
    if (arguments.length < 3) priority = "";
    function styleTween(d, i) {
      var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
      return f && function(t) {
        this.style.setProperty(name, f(t), priority);
      };
    }
    return this.tween("style." + name, styleTween);
  };
  d3_transitionPrototype.text = function(value) {
    return d3_transition_tween(this, "text", value, d3_transition_text);
  };
  function d3_transition_text(b) {
    if (b == null) b = "";
    return function() {
      this.textContent = b;
    };
  }
  d3_transitionPrototype.remove = function() {
    var ns = this.namespace;
    return this.each("end.transition", function() {
      var p;
      if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
    });
  };
  d3_transitionPrototype.ease = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].ease;
    if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
    return d3_selection_each(this, function(node) {
      node[ns][id].ease = value;
    });
  };
  d3_transitionPrototype.delay = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].delay;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].delay = +value.call(node, node.__data__, i, j);
    } : (value = +value, function(node) {
      node[ns][id].delay = value;
    }));
  };
  d3_transitionPrototype.duration = function(value) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 1) return this.node()[ns][id].duration;
    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
      node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
    } : (value = Math.max(1, value), function(node) {
      node[ns][id].duration = value;
    }));
  };
  d3_transitionPrototype.each = function(type, listener) {
    var id = this.id, ns = this.namespace;
    if (arguments.length < 2) {
      var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
      try {
        d3_transitionInheritId = id;
        d3_selection_each(this, function(node, i, j) {
          d3_transitionInherit = node[ns][id];
          type.call(node, node.__data__, i, j);
        });
      } finally {
        d3_transitionInherit = inherit;
        d3_transitionInheritId = inheritId;
      }
    } else {
      d3_selection_each(this, function(node) {
        var transition = node[ns][id];
        (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
      });
    }
    return this;
  };
  d3_transitionPrototype.transition = function() {
    var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
    for (var j = 0, m = this.length; j < m; j++) {
      subgroups.push(subgroup = []);
      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
        if (node = group[i]) {
          transition = node[ns][id0];
          d3_transitionNode(node, i, ns, id1, {
            time: transition.time,
            ease: transition.ease,
            delay: transition.delay + transition.duration,
            duration: transition.duration
          });
        }
        subgroup.push(node);
      }
    }
    return d3_transition(subgroups, ns, id1);
  };
  function d3_transitionNamespace(name) {
    return name == null ? "__transition__" : "__transition_" + name + "__";
  }
  function d3_transitionNode(node, i, ns, id, inherit) {
    var lock = node[ns] || (node[ns] = {
      active: 0,
      count: 0
    }), transition = lock[id], time, timer, duration, ease, tweens;
    function schedule(elapsed) {
      var delay = transition.delay;
      timer.t = delay + time;
      if (delay <= elapsed) return start(elapsed - delay);
      timer.c = start;
    }
    function start(elapsed) {
      var activeId = lock.active, active = lock[activeId];
      if (active) {
        active.timer.c = null;
        active.timer.t = NaN;
        --lock.count;
        delete lock[activeId];
        active.event && active.event.interrupt.call(node, node.__data__, active.index);
      }
      for (var cancelId in lock) {
        if (+cancelId < id) {
          var cancel = lock[cancelId];
          cancel.timer.c = null;
          cancel.timer.t = NaN;
          --lock.count;
          delete lock[cancelId];
        }
      }
      timer.c = tick;
      d3_timer(function() {
        if (timer.c && tick(elapsed || 1)) {
          timer.c = null;
          timer.t = NaN;
        }
        return 1;
      }, 0, time);
      lock.active = id;
      transition.event && transition.event.start.call(node, node.__data__, i);
      tweens = [];
      transition.tween.forEach(function(key, value) {
        if (value = value.call(node, node.__data__, i)) {
          tweens.push(value);
        }
      });
      ease = transition.ease;
      duration = transition.duration;
    }
    function tick(elapsed) {
      var t = elapsed / duration, e = ease(t), n = tweens.length;
      while (n > 0) {
        tweens[--n].call(node, e);
      }
      if (t >= 1) {
        transition.event && transition.event.end.call(node, node.__data__, i);
        if (--lock.count) delete lock[id]; else delete node[ns];
        return 1;
      }
    }
    if (!transition) {
      time = inherit.time;
      timer = d3_timer(schedule, 0, time);
      transition = lock[id] = {
        tween: new d3_Map(),
        time: time,
        timer: timer,
        delay: inherit.delay,
        duration: inherit.duration,
        ease: inherit.ease,
        index: i
      };
      inherit = null;
      ++lock.count;
    }
  }
  d3.svg.axis = function() {
    var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
    function axis(g) {
      g.each(function() {
        var g = d3.select(this);
        var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
        var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
        var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), 
        d3.transition(path));
        tickEnter.append("line");
        tickEnter.append("text");
        var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
        if (orient === "bottom" || orient === "top") {
          tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
          text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
          pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
        } else {
          tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
          text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
          pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
        }
        lineEnter.attr(y2, sign * innerTickSize);
        textEnter.attr(y1, sign * tickSpacing);
        lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
        textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
        if (scale1.rangeBand) {
          var x = scale1, dx = x.rangeBand() / 2;
          scale0 = scale1 = function(d) {
            return x(d) + dx;
          };
        } else if (scale0.rangeBand) {
          scale0 = scale1;
        } else {
          tickExit.call(tickTransform, scale1, scale0);
        }
        tickEnter.call(tickTransform, scale0, scale1);
        tickUpdate.call(tickTransform, scale1, scale1);
      });
    }
    axis.scale = function(x) {
      if (!arguments.length) return scale;
      scale = x;
      return axis;
    };
    axis.orient = function(x) {
      if (!arguments.length) return orient;
      orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
      return axis;
    };
    axis.ticks = function() {
      if (!arguments.length) return tickArguments_;
      tickArguments_ = d3_array(arguments);
      return axis;
    };
    axis.tickValues = function(x) {
      if (!arguments.length) return tickValues;
      tickValues = x;
      return axis;
    };
    axis.tickFormat = function(x) {
      if (!arguments.length) return tickFormat_;
      tickFormat_ = x;
      return axis;
    };
    axis.tickSize = function(x) {
      var n = arguments.length;
      if (!n) return innerTickSize;
      innerTickSize = +x;
      outerTickSize = +arguments[n - 1];
      return axis;
    };
    axis.innerTickSize = function(x) {
      if (!arguments.length) return innerTickSize;
      innerTickSize = +x;
      return axis;
    };
    axis.outerTickSize = function(x) {
      if (!arguments.length) return outerTickSize;
      outerTickSize = +x;
      return axis;
    };
    axis.tickPadding = function(x) {
      if (!arguments.length) return tickPadding;
      tickPadding = +x;
      return axis;
    };
    axis.tickSubdivide = function() {
      return arguments.length && axis;
    };
    return axis;
  };
  var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
    top: 1,
    right: 1,
    bottom: 1,
    left: 1
  };
  function d3_svg_axisX(selection, x0, x1) {
    selection.attr("transform", function(d) {
      var v0 = x0(d);
      return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
    });
  }
  function d3_svg_axisY(selection, y0, y1) {
    selection.attr("transform", function(d) {
      var v0 = y0(d);
      return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
    });
  }
  d3.svg.brush = function() {
    var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
    function brush(g) {
      g.each(function() {
        var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
        var background = g.selectAll(".background").data([ 0 ]);
        background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
        g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
        var resize = g.selectAll(".resize").data(resizes, d3_identity);
        resize.exit().remove();
        resize.enter().append("g").attr("class", function(d) {
          return "resize " + d;
        }).style("cursor", function(d) {
          return d3_svg_brushCursor[d];
        }).append("rect").attr("x", function(d) {
          return /[ew]$/.test(d) ? -3 : null;
        }).attr("y", function(d) {
          return /^[ns]/.test(d) ? -3 : null;
        }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
        resize.style("display", brush.empty() ? "none" : null);
        var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
        if (x) {
          range = d3_scaleRange(x);
          backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
          redrawX(gUpdate);
        }
        if (y) {
          range = d3_scaleRange(y);
          backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
          redrawY(gUpdate);
        }
        redraw(gUpdate);
      });
    }
    brush.event = function(g) {
      g.each(function() {
        var event_ = event.of(this, arguments), extent1 = {
          x: xExtent,
          y: yExtent,
          i: xExtentDomain,
          j: yExtentDomain
        }, extent0 = this.__chart__ || extent1;
        this.__chart__ = extent1;
        if (d3_transitionInheritId) {
          d3.select(this).transition().each("start.brush", function() {
            xExtentDomain = extent0.i;
            yExtentDomain = extent0.j;
            xExtent = extent0.x;
            yExtent = extent0.y;
            event_({
              type: "brushstart"
            });
          }).tween("brush:brush", function() {
            var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
            xExtentDomain = yExtentDomain = null;
            return function(t) {
              xExtent = extent1.x = xi(t);
              yExtent = extent1.y = yi(t);
              event_({
                type: "brush",
                mode: "resize"
              });
            };
          }).each("end.brush", function() {
            xExtentDomain = extent1.i;
            yExtentDomain = extent1.j;
            event_({
              type: "brush",
              mode: "resize"
            });
            event_({
              type: "brushend"
            });
          });
        } else {
          event_({
            type: "brushstart"
          });
          event_({
            type: "brush",
            mode: "resize"
          });
          event_({
            type: "brushend"
          });
        }
      });
    };
    function redraw(g) {
      g.selectAll(".resize").attr("transform", function(d) {
        return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
      });
    }
    function redrawX(g) {
      g.select(".extent").attr("x", xExtent[0]);
      g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
    }
    function redrawY(g) {
      g.select(".extent").attr("y", yExtent[0]);
      g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
    }
    function brushstart() {
      var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
      var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
      if (d3.event.changedTouches) {
        w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
      } else {
        w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
      }
      g.interrupt().selectAll("*").interrupt();
      if (dragging) {
        origin[0] = xExtent[0] - origin[0];
        origin[1] = yExtent[0] - origin[1];
      } else if (resizing) {
        var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
        offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
        origin[0] = xExtent[ex];
        origin[1] = yExtent[ey];
      } else if (d3.event.altKey) center = origin.slice();
      g.style("pointer-events", "none").selectAll(".resize").style("display", null);
      d3.select("body").style("cursor", eventTarget.style("cursor"));
      event_({
        type: "brushstart"
      });
      brushmove();
      function keydown() {
        if (d3.event.keyCode == 32) {
          if (!dragging) {
            center = null;
            origin[0] -= xExtent[1];
            origin[1] -= yExtent[1];
            dragging = 2;
          }
          d3_eventPreventDefault();
        }
      }
      function keyup() {
        if (d3.event.keyCode == 32 && dragging == 2) {
          origin[0] += xExtent[1];
          origin[1] += yExtent[1];
          dragging = 0;
          d3_eventPreventDefault();
        }
      }
      function brushmove() {
        var point = d3.mouse(target), moved = false;
        if (offset) {
          point[0] += offset[0];
          point[1] += offset[1];
        }
        if (!dragging) {
          if (d3.event.altKey) {
            if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
            origin[0] = xExtent[+(point[0] < center[0])];
            origin[1] = yExtent[+(point[1] < center[1])];
          } else center = null;
        }
        if (resizingX && move1(point, x, 0)) {
          redrawX(g);
          moved = true;
        }
        if (resizingY && move1(point, y, 1)) {
          redrawY(g);
          moved = true;
        }
        if (moved) {
          redraw(g);
          event_({
            type: "brush",
            mode: dragging ? "move" : "resize"
          });
        }
      }
      function move1(point, scale, i) {
        var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
        if (dragging) {
          r0 -= position;
          r1 -= size + position;
        }
        min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
        if (dragging) {
          max = (min += position) + size;
        } else {
          if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
          if (position < min) {
            max = min;
            min = position;
          } else {
            max = position;
          }
        }
        if (extent[0] != min || extent[1] != max) {
          if (i) yExtentDomain = null; else xExtentDomain = null;
          extent[0] = min;
          extent[1] = max;
          return true;
        }
      }
      function brushend() {
        brushmove();
        g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
        d3.select("body").style("cursor", null);
        w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
        dragRestore();
        event_({
          type: "brushend"
        });
      }
    }
    brush.x = function(z) {
      if (!arguments.length) return x;
      x = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.y = function(z) {
      if (!arguments.length) return y;
      y = z;
      resizes = d3_svg_brushResizes[!x << 1 | !y];
      return brush;
    };
    brush.clamp = function(z) {
      if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
      if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
      return brush;
    };
    brush.extent = function(z) {
      var x0, x1, y0, y1, t;
      if (!arguments.length) {
        if (x) {
          if (xExtentDomain) {
            x0 = xExtentDomain[0], x1 = xExtentDomain[1];
          } else {
            x0 = xExtent[0], x1 = xExtent[1];
            if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
            if (x1 < x0) t = x0, x0 = x1, x1 = t;
          }
        }
        if (y) {
          if (yExtentDomain) {
            y0 = yExtentDomain[0], y1 = yExtentDomain[1];
          } else {
            y0 = yExtent[0], y1 = yExtent[1];
            if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
            if (y1 < y0) t = y0, y0 = y1, y1 = t;
          }
        }
        return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
      }
      if (x) {
        x0 = z[0], x1 = z[1];
        if (y) x0 = x0[0], x1 = x1[0];
        xExtentDomain = [ x0, x1 ];
        if (x.invert) x0 = x(x0), x1 = x(x1);
        if (x1 < x0) t = x0, x0 = x1, x1 = t;
        if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
      }
      if (y) {
        y0 = z[0], y1 = z[1];
        if (x) y0 = y0[1], y1 = y1[1];
        yExtentDomain = [ y0, y1 ];
        if (y.invert) y0 = y(y0), y1 = y(y1);
        if (y1 < y0) t = y0, y0 = y1, y1 = t;
        if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
      }
      return brush;
    };
    brush.clear = function() {
      if (!brush.empty()) {
        xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
        xExtentDomain = yExtentDomain = null;
      }
      return brush;
    };
    brush.empty = function() {
      return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
    };
    return d3.rebind(brush, event, "on");
  };
  var d3_svg_brushCursor = {
    n: "ns-resize",
    e: "ew-resize",
    s: "ns-resize",
    w: "ew-resize",
    nw: "nwse-resize",
    ne: "nesw-resize",
    se: "nwse-resize",
    sw: "nesw-resize"
  };
  var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
  var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
  var d3_time_formatUtc = d3_time_format.utc;
  var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
  d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
  function d3_time_formatIsoNative(date) {
    return date.toISOString();
  }
  d3_time_formatIsoNative.parse = function(string) {
    var date = new Date(string);
    return isNaN(date) ? null : date;
  };
  d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
  d3_time.second = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 1e3) * 1e3);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 1e3);
  }, function(date) {
    return date.getSeconds();
  });
  d3_time.seconds = d3_time.second.range;
  d3_time.seconds.utc = d3_time.second.utc.range;
  d3_time.minute = d3_time_interval(function(date) {
    return new d3_date(Math.floor(date / 6e4) * 6e4);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 6e4);
  }, function(date) {
    return date.getMinutes();
  });
  d3_time.minutes = d3_time.minute.range;
  d3_time.minutes.utc = d3_time.minute.utc.range;
  d3_time.hour = d3_time_interval(function(date) {
    var timezone = date.getTimezoneOffset() / 60;
    return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
  }, function(date, offset) {
    date.setTime(date.getTime() + Math.floor(offset) * 36e5);
  }, function(date) {
    return date.getHours();
  });
  d3_time.hours = d3_time.hour.range;
  d3_time.hours.utc = d3_time.hour.utc.range;
  d3_time.month = d3_time_interval(function(date) {
    date = d3_time.day(date);
    date.setDate(1);
    return date;
  }, function(date, offset) {
    date.setMonth(date.getMonth() + offset);
  }, function(date) {
    return date.getMonth();
  });
  d3_time.months = d3_time.month.range;
  d3_time.months.utc = d3_time.month.utc.range;
  function d3_time_scale(linear, methods, format) {
    function scale(x) {
      return linear(x);
    }
    scale.invert = function(x) {
      return d3_time_scaleDate(linear.invert(x));
    };
    scale.domain = function(x) {
      if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
      linear.domain(x);
      return scale;
    };
    function tickMethod(extent, count) {
      var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
      return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
        return d / 31536e6;
      }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
    }
    scale.nice = function(interval, skip) {
      var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
      if (method) interval = method[0], skip = method[1];
      function skipped(date) {
        return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
      }
      return scale.domain(d3_scale_nice(domain, skip > 1 ? {
        floor: function(date) {
          while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
          return date;
        },
        ceil: function(date) {
          while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
          return date;
        }
      } : interval));
    };
    scale.ticks = function(interval, skip) {
      var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
        range: interval
      }, skip ];
      if (method) interval = method[0], skip = method[1];
      return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
    };
    scale.tickFormat = function() {
      return format;
    };
    scale.copy = function() {
      return d3_time_scale(linear.copy(), methods, format);
    };
    return d3_scale_linearRebind(scale, linear);
  }
  function d3_time_scaleDate(t) {
    return new Date(t);
  }
  var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
  var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
  var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
    return d.getMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getMinutes();
  } ], [ "%I %p", function(d) {
    return d.getHours();
  } ], [ "%a %d", function(d) {
    return d.getDay() && d.getDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getDate() != 1;
  } ], [ "%B", function(d) {
    return d.getMonth();
  } ], [ "%Y", d3_true ] ]);
  var d3_time_scaleMilliseconds = {
    range: function(start, stop, step) {
      return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
    },
    floor: d3_identity,
    ceil: d3_identity
  };
  d3_time_scaleLocalMethods.year = d3_time.year;
  d3_time.scale = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
  };
  var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
    return [ m[0].utc, m[1] ];
  });
  var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
    return d.getUTCMilliseconds();
  } ], [ ":%S", function(d) {
    return d.getUTCSeconds();
  } ], [ "%I:%M", function(d) {
    return d.getUTCMinutes();
  } ], [ "%I %p", function(d) {
    return d.getUTCHours();
  } ], [ "%a %d", function(d) {
    return d.getUTCDay() && d.getUTCDate() != 1;
  } ], [ "%b %d", function(d) {
    return d.getUTCDate() != 1;
  } ], [ "%B", function(d) {
    return d.getUTCMonth();
  } ], [ "%Y", d3_true ] ]);
  d3_time_scaleUtcMethods.year = d3_time.year.utc;
  d3_time.scale.utc = function() {
    return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
  };
  d3.text = d3_xhrType(function(request) {
    return request.responseText;
  });
  d3.json = function(url, callback) {
    return d3_xhr(url, "application/json", d3_json, callback);
  };
  function d3_json(request) {
    return JSON.parse(request.responseText);
  }
  d3.html = function(url, callback) {
    return d3_xhr(url, "text/html", d3_html, callback);
  };
  function d3_html(request) {
    var range = d3_document.createRange();
    range.selectNode(d3_document.body);
    return range.createContextualFragment(request.responseText);
  }
  d3.xml = d3_xhrType(function(request) {
    return request.responseXML;
  });
  if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
}();
},{}],7:[function(require,module,exports){
(function (process,global){
/*!
 * @overview es6-promise - a tiny implementation of Promises/A+.
 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
 * @license   Licensed under MIT license
 *            See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
 * @version   3.3.1
 */

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.ES6Promise = factory());
}(this, (function () { 'use strict';

function objectOrFunction(x) {
  return typeof x === 'function' || typeof x === 'object' && x !== null;
}

function isFunction(x) {
  return typeof x === 'function';
}

var _isArray = undefined;
if (!Array.isArray) {
  _isArray = function (x) {
    return Object.prototype.toString.call(x) === '[object Array]';
  };
} else {
  _isArray = Array.isArray;
}

var isArray = _isArray;

var len = 0;
var vertxNext = undefined;
var customSchedulerFn = undefined;

var asap = function asap(callback, arg) {
  queue[len] = callback;
  queue[len + 1] = arg;
  len += 2;
  if (len === 2) {
    // If len is 2, that means that we need to schedule an async flush.
    // If additional callbacks are queued before the queue is flushed, they
    // will be processed by this flush that we are scheduling.
    if (customSchedulerFn) {
      customSchedulerFn(flush);
    } else {
      scheduleFlush();
    }
  }
};

function setScheduler(scheduleFn) {
  customSchedulerFn = scheduleFn;
}

function setAsap(asapFn) {
  asap = asapFn;
}

var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';

// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';

// node
function useNextTick() {
  // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  // see https://github.com/cujojs/when/issues/410 for details
  return function () {
    return process.nextTick(flush);
  };
}

// vertx
function useVertxTimer() {
  return function () {
    vertxNext(flush);
  };
}

function useMutationObserver() {
  var iterations = 0;
  var observer = new BrowserMutationObserver(flush);
  var node = document.createTextNode('');
  observer.observe(node, { characterData: true });

  return function () {
    node.data = iterations = ++iterations % 2;
  };
}

// web worker
function useMessageChannel() {
  var channel = new MessageChannel();
  channel.port1.onmessage = flush;
  return function () {
    return channel.port2.postMessage(0);
  };
}

function useSetTimeout() {
  // Store setTimeout reference so es6-promise will be unaffected by
  // other code modifying setTimeout (like sinon.useFakeTimers())
  var globalSetTimeout = setTimeout;
  return function () {
    return globalSetTimeout(flush, 1);
  };
}

var queue = new Array(1000);
function flush() {
  for (var i = 0; i < len; i += 2) {
    var callback = queue[i];
    var arg = queue[i + 1];

    callback(arg);

    queue[i] = undefined;
    queue[i + 1] = undefined;
  }

  len = 0;
}

function attemptVertx() {
  try {
    var r = require;
    var vertx = r('vertx');
    vertxNext = vertx.runOnLoop || vertx.runOnContext;
    return useVertxTimer();
  } catch (e) {
    return useSetTimeout();
  }
}

var scheduleFlush = undefined;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
  scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
  scheduleFlush = useMutationObserver();
} else if (isWorker) {
  scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
  scheduleFlush = attemptVertx();
} else {
  scheduleFlush = useSetTimeout();
}

function then(onFulfillment, onRejection) {
  var _arguments = arguments;

  var parent = this;

  var child = new this.constructor(noop);

  if (child[PROMISE_ID] === undefined) {
    makePromise(child);
  }

  var _state = parent._state;

  if (_state) {
    (function () {
      var callback = _arguments[_state - 1];
      asap(function () {
        return invokeCallback(_state, child, callback, parent._result);
      });
    })();
  } else {
    subscribe(parent, child, onFulfillment, onRejection);
  }

  return child;
}

/**
  `Promise.resolve` returns a promise that will become resolved with the
  passed `value`. It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    resolve(1);
  });

  promise.then(function(value){
    // value === 1
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.resolve(1);

  promise.then(function(value){
    // value === 1
  });
  ```

  @method resolve
  @static
  @param {Any} value value that the returned promise will be resolved with
  Useful for tooling.
  @return {Promise} a promise that will become fulfilled with the given
  `value`
*/
function resolve(object) {
  /*jshint validthis:true */
  var Constructor = this;

  if (object && typeof object === 'object' && object.constructor === Constructor) {
    return object;
  }

  var promise = new Constructor(noop);
  _resolve(promise, object);
  return promise;
}

var PROMISE_ID = Math.random().toString(36).substring(16);

function noop() {}

var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;

var GET_THEN_ERROR = new ErrorObject();

function selfFulfillment() {
  return new TypeError("You cannot resolve a promise with itself");
}

function cannotReturnOwn() {
  return new TypeError('A promises callback cannot return that same promise.');
}

function getThen(promise) {
  try {
    return promise.then;
  } catch (error) {
    GET_THEN_ERROR.error = error;
    return GET_THEN_ERROR;
  }
}

function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  try {
    then.call(value, fulfillmentHandler, rejectionHandler);
  } catch (e) {
    return e;
  }
}

function handleForeignThenable(promise, thenable, then) {
  asap(function (promise) {
    var sealed = false;
    var error = tryThen(then, thenable, function (value) {
      if (sealed) {
        return;
      }
      sealed = true;
      if (thenable !== value) {
        _resolve(promise, value);
      } else {
        fulfill(promise, value);
      }
    }, function (reason) {
      if (sealed) {
        return;
      }
      sealed = true;

      _reject(promise, reason);
    }, 'Settle: ' + (promise._label || ' unknown promise'));

    if (!sealed && error) {
      sealed = true;
      _reject(promise, error);
    }
  }, promise);
}

function handleOwnThenable(promise, thenable) {
  if (thenable._state === FULFILLED) {
    fulfill(promise, thenable._result);
  } else if (thenable._state === REJECTED) {
    _reject(promise, thenable._result);
  } else {
    subscribe(thenable, undefined, function (value) {
      return _resolve(promise, value);
    }, function (reason) {
      return _reject(promise, reason);
    });
  }
}

function handleMaybeThenable(promise, maybeThenable, then$$) {
  if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
    handleOwnThenable(promise, maybeThenable);
  } else {
    if (then$$ === GET_THEN_ERROR) {
      _reject(promise, GET_THEN_ERROR.error);
    } else if (then$$ === undefined) {
      fulfill(promise, maybeThenable);
    } else if (isFunction(then$$)) {
      handleForeignThenable(promise, maybeThenable, then$$);
    } else {
      fulfill(promise, maybeThenable);
    }
  }
}

function _resolve(promise, value) {
  if (promise === value) {
    _reject(promise, selfFulfillment());
  } else if (objectOrFunction(value)) {
    handleMaybeThenable(promise, value, getThen(value));
  } else {
    fulfill(promise, value);
  }
}

function publishRejection(promise) {
  if (promise._onerror) {
    promise._onerror(promise._result);
  }

  publish(promise);
}

function fulfill(promise, value) {
  if (promise._state !== PENDING) {
    return;
  }

  promise._result = value;
  promise._state = FULFILLED;

  if (promise._subscribers.length !== 0) {
    asap(publish, promise);
  }
}

function _reject(promise, reason) {
  if (promise._state !== PENDING) {
    return;
  }
  promise._state = REJECTED;
  promise._result = reason;

  asap(publishRejection, promise);
}

function subscribe(parent, child, onFulfillment, onRejection) {
  var _subscribers = parent._subscribers;
  var length = _subscribers.length;

  parent._onerror = null;

  _subscribers[length] = child;
  _subscribers[length + FULFILLED] = onFulfillment;
  _subscribers[length + REJECTED] = onRejection;

  if (length === 0 && parent._state) {
    asap(publish, parent);
  }
}

function publish(promise) {
  var subscribers = promise._subscribers;
  var settled = promise._state;

  if (subscribers.length === 0) {
    return;
  }

  var child = undefined,
      callback = undefined,
      detail = promise._result;

  for (var i = 0; i < subscribers.length; i += 3) {
    child = subscribers[i];
    callback = subscribers[i + settled];

    if (child) {
      invokeCallback(settled, child, callback, detail);
    } else {
      callback(detail);
    }
  }

  promise._subscribers.length = 0;
}

function ErrorObject() {
  this.error = null;
}

var TRY_CATCH_ERROR = new ErrorObject();

function tryCatch(callback, detail) {
  try {
    return callback(detail);
  } catch (e) {
    TRY_CATCH_ERROR.error = e;
    return TRY_CATCH_ERROR;
  }
}

function invokeCallback(settled, promise, callback, detail) {
  var hasCallback = isFunction(callback),
      value = undefined,
      error = undefined,
      succeeded = undefined,
      failed = undefined;

  if (hasCallback) {
    value = tryCatch(callback, detail);

    if (value === TRY_CATCH_ERROR) {
      failed = true;
      error = value.error;
      value = null;
    } else {
      succeeded = true;
    }

    if (promise === value) {
      _reject(promise, cannotReturnOwn());
      return;
    }
  } else {
    value = detail;
    succeeded = true;
  }

  if (promise._state !== PENDING) {
    // noop
  } else if (hasCallback && succeeded) {
      _resolve(promise, value);
    } else if (failed) {
      _reject(promise, error);
    } else if (settled === FULFILLED) {
      fulfill(promise, value);
    } else if (settled === REJECTED) {
      _reject(promise, value);
    }
}

function initializePromise(promise, resolver) {
  try {
    resolver(function resolvePromise(value) {
      _resolve(promise, value);
    }, function rejectPromise(reason) {
      _reject(promise, reason);
    });
  } catch (e) {
    _reject(promise, e);
  }
}

var id = 0;
function nextId() {
  return id++;
}

function makePromise(promise) {
  promise[PROMISE_ID] = id++;
  promise._state = undefined;
  promise._result = undefined;
  promise._subscribers = [];
}

function Enumerator(Constructor, input) {
  this._instanceConstructor = Constructor;
  this.promise = new Constructor(noop);

  if (!this.promise[PROMISE_ID]) {
    makePromise(this.promise);
  }

  if (isArray(input)) {
    this._input = input;
    this.length = input.length;
    this._remaining = input.length;

    this._result = new Array(this.length);

    if (this.length === 0) {
      fulfill(this.promise, this._result);
    } else {
      this.length = this.length || 0;
      this._enumerate();
      if (this._remaining === 0) {
        fulfill(this.promise, this._result);
      }
    }
  } else {
    _reject(this.promise, validationError());
  }
}

function validationError() {
  return new Error('Array Methods must be provided an Array');
};

Enumerator.prototype._enumerate = function () {
  var length = this.length;
  var _input = this._input;

  for (var i = 0; this._state === PENDING && i < length; i++) {
    this._eachEntry(_input[i], i);
  }
};

Enumerator.prototype._eachEntry = function (entry, i) {
  var c = this._instanceConstructor;
  var resolve$$ = c.resolve;

  if (resolve$$ === resolve) {
    var _then = getThen(entry);

    if (_then === then && entry._state !== PENDING) {
      this._settledAt(entry._state, i, entry._result);
    } else if (typeof _then !== 'function') {
      this._remaining--;
      this._result[i] = entry;
    } else if (c === Promise) {
      var promise = new c(noop);
      handleMaybeThenable(promise, entry, _then);
      this._willSettleAt(promise, i);
    } else {
      this._willSettleAt(new c(function (resolve$$) {
        return resolve$$(entry);
      }), i);
    }
  } else {
    this._willSettleAt(resolve$$(entry), i);
  }
};

Enumerator.prototype._settledAt = function (state, i, value) {
  var promise = this.promise;

  if (promise._state === PENDING) {
    this._remaining--;

    if (state === REJECTED) {
      _reject(promise, value);
    } else {
      this._result[i] = value;
    }
  }

  if (this._remaining === 0) {
    fulfill(promise, this._result);
  }
};

Enumerator.prototype._willSettleAt = function (promise, i) {
  var enumerator = this;

  subscribe(promise, undefined, function (value) {
    return enumerator._settledAt(FULFILLED, i, value);
  }, function (reason) {
    return enumerator._settledAt(REJECTED, i, reason);
  });
};

/**
  `Promise.all` accepts an array of promises, and returns a new promise which
  is fulfilled with an array of fulfillment values for the passed promises, or
  rejected with the reason of the first passed promise to be rejected. It casts all
  elements of the passed iterable to promises as it runs this algorithm.

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = resolve(2);
  let promise3 = resolve(3);
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // The array here would be [ 1, 2, 3 ];
  });
  ```

  If any of the `promises` given to `all` are rejected, the first promise
  that is rejected will be given as an argument to the returned promises's
  rejection handler. For example:

  Example:

  ```javascript
  let promise1 = resolve(1);
  let promise2 = reject(new Error("2"));
  let promise3 = reject(new Error("3"));
  let promises = [ promise1, promise2, promise3 ];

  Promise.all(promises).then(function(array){
    // Code here never runs because there are rejected promises!
  }, function(error) {
    // error.message === "2"
  });
  ```

  @method all
  @static
  @param {Array} entries array of promises
  @param {String} label optional string for labeling the promise.
  Useful for tooling.
  @return {Promise} promise that is fulfilled when all `promises` have been
  fulfilled, or rejected if any of them become rejected.
  @static
*/
function all(entries) {
  return new Enumerator(this, entries).promise;
}

/**
  `Promise.race` returns a new promise which is settled in the same way as the
  first passed promise to settle.

  Example:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 2');
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // result === 'promise 2' because it was resolved before promise1
    // was resolved.
  });
  ```

  `Promise.race` is deterministic in that only the state of the first
  settled promise matters. For example, even if other promises given to the
  `promises` array argument are resolved, but the first settled promise has
  become rejected before the other promises became fulfilled, the returned
  promise will become rejected:

  ```javascript
  let promise1 = new Promise(function(resolve, reject){
    setTimeout(function(){
      resolve('promise 1');
    }, 200);
  });

  let promise2 = new Promise(function(resolve, reject){
    setTimeout(function(){
      reject(new Error('promise 2'));
    }, 100);
  });

  Promise.race([promise1, promise2]).then(function(result){
    // Code here never runs
  }, function(reason){
    // reason.message === 'promise 2' because promise 2 became rejected before
    // promise 1 became fulfilled
  });
  ```

  An example real-world use case is implementing timeouts:

  ```javascript
  Promise.race([ajax('foo.json'), timeout(5000)])
  ```

  @method race
  @static
  @param {Array} promises array of promises to observe
  Useful for tooling.
  @return {Promise} a promise which settles in the same way as the first passed
  promise to settle.
*/
function race(entries) {
  /*jshint validthis:true */
  var Constructor = this;

  if (!isArray(entries)) {
    return new Constructor(function (_, reject) {
      return reject(new TypeError('You must pass an array to race.'));
    });
  } else {
    return new Constructor(function (resolve, reject) {
      var length = entries.length;
      for (var i = 0; i < length; i++) {
        Constructor.resolve(entries[i]).then(resolve, reject);
      }
    });
  }
}

/**
  `Promise.reject` returns a promise rejected with the passed `reason`.
  It is shorthand for the following:

  ```javascript
  let promise = new Promise(function(resolve, reject){
    reject(new Error('WHOOPS'));
  });

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  Instead of writing the above, your code now simply becomes the following:

  ```javascript
  let promise = Promise.reject(new Error('WHOOPS'));

  promise.then(function(value){
    // Code here doesn't run because the promise is rejected!
  }, function(reason){
    // reason.message === 'WHOOPS'
  });
  ```

  @method reject
  @static
  @param {Any} reason value that the returned promise will be rejected with.
  Useful for tooling.
  @return {Promise} a promise rejected with the given `reason`.
*/
function reject(reason) {
  /*jshint validthis:true */
  var Constructor = this;
  var promise = new Constructor(noop);
  _reject(promise, reason);
  return promise;
}

function needsResolver() {
  throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}

function needsNew() {
  throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}

/**
  Promise objects represent the eventual result of an asynchronous operation. The
  primary way of interacting with a promise is through its `then` method, which
  registers callbacks to receive either a promise's eventual value or the reason
  why the promise cannot be fulfilled.

  Terminology
  -----------

  - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  - `thenable` is an object or function that defines a `then` method.
  - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  - `exception` is a value that is thrown using the throw statement.
  - `reason` is a value that indicates why a promise was rejected.
  - `settled` the final resting state of a promise, fulfilled or rejected.

  A promise can be in one of three states: pending, fulfilled, or rejected.

  Promises that are fulfilled have a fulfillment value and are in the fulfilled
  state.  Promises that are rejected have a rejection reason and are in the
  rejected state.  A fulfillment value is never a thenable.

  Promises can also be said to *resolve* a value.  If this value is also a
  promise, then the original promise's settled state will match the value's
  settled state.  So a promise that *resolves* a promise that rejects will
  itself reject, and a promise that *resolves* a promise that fulfills will
  itself fulfill.


  Basic Usage:
  ------------

  ```js
  let promise = new Promise(function(resolve, reject) {
    // on success
    resolve(value);

    // on failure
    reject(reason);
  });

  promise.then(function(value) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Advanced Usage:
  ---------------

  Promises shine when abstracting away asynchronous interactions such as
  `XMLHttpRequest`s.

  ```js
  function getJSON(url) {
    return new Promise(function(resolve, reject){
      let xhr = new XMLHttpRequest();

      xhr.open('GET', url);
      xhr.onreadystatechange = handler;
      xhr.responseType = 'json';
      xhr.setRequestHeader('Accept', 'application/json');
      xhr.send();

      function handler() {
        if (this.readyState === this.DONE) {
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
          }
        }
      };
    });
  }

  getJSON('/posts.json').then(function(json) {
    // on fulfillment
  }, function(reason) {
    // on rejection
  });
  ```

  Unlike callbacks, promises are great composable primitives.

  ```js
  Promise.all([
    getJSON('/posts'),
    getJSON('/comments')
  ]).then(function(values){
    values[0] // => postsJSON
    values[1] // => commentsJSON

    return values;
  });
  ```

  @class Promise
  @param {function} resolver
  Useful for tooling.
  @constructor
*/
function Promise(resolver) {
  this[PROMISE_ID] = nextId();
  this._result = this._state = undefined;
  this._subscribers = [];

  if (noop !== resolver) {
    typeof resolver !== 'function' && needsResolver();
    this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  }
}

Promise.all = all;
Promise.race = race;
Promise.resolve = resolve;
Promise.reject = reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;

Promise.prototype = {
  constructor: Promise,

  /**
    The primary way of interacting with a promise is through its `then` method,
    which registers callbacks to receive either a promise's eventual value or the
    reason why the promise cannot be fulfilled.
  
    ```js
    findUser().then(function(user){
      // user is available
    }, function(reason){
      // user is unavailable, and you are given the reason why
    });
    ```
  
    Chaining
    --------
  
    The return value of `then` is itself a promise.  This second, 'downstream'
    promise is resolved with the return value of the first promise's fulfillment
    or rejection handler, or rejected if the handler throws an exception.
  
    ```js
    findUser().then(function (user) {
      return user.name;
    }, function (reason) {
      return 'default name';
    }).then(function (userName) {
      // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
      // will be `'default name'`
    });
  
    findUser().then(function (user) {
      throw new Error('Found user, but still unhappy');
    }, function (reason) {
      throw new Error('`findUser` rejected and we're unhappy');
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
      // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
    });
    ```
    If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  
    ```js
    findUser().then(function (user) {
      throw new PedagogicalException('Upstream error');
    }).then(function (value) {
      // never reached
    }).then(function (value) {
      // never reached
    }, function (reason) {
      // The `PedgagocialException` is propagated all the way down to here
    });
    ```
  
    Assimilation
    ------------
  
    Sometimes the value you want to propagate to a downstream promise can only be
    retrieved asynchronously. This can be achieved by returning a promise in the
    fulfillment or rejection handler. The downstream promise will then be pending
    until the returned promise is settled. This is called *assimilation*.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // The user's comments are now available
    });
    ```
  
    If the assimliated promise rejects, then the downstream promise will also reject.
  
    ```js
    findUser().then(function (user) {
      return findCommentsByAuthor(user);
    }).then(function (comments) {
      // If `findCommentsByAuthor` fulfills, we'll have the value here
    }, function (reason) {
      // If `findCommentsByAuthor` rejects, we'll have the reason here
    });
    ```
  
    Simple Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let result;
  
    try {
      result = findResult();
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
    findResult(function(result, err){
      if (err) {
        // failure
      } else {
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findResult().then(function(result){
      // success
    }, function(reason){
      // failure
    });
    ```
  
    Advanced Example
    --------------
  
    Synchronous Example
  
    ```javascript
    let author, books;
  
    try {
      author = findAuthor();
      books  = findBooksByAuthor(author);
      // success
    } catch(reason) {
      // failure
    }
    ```
  
    Errback Example
  
    ```js
  
    function foundBooks(books) {
  
    }
  
    function failure(reason) {
  
    }
  
    findAuthor(function(author, err){
      if (err) {
        failure(err);
        // failure
      } else {
        try {
          findBoooksByAuthor(author, function(books, err) {
            if (err) {
              failure(err);
            } else {
              try {
                foundBooks(books);
              } catch(reason) {
                failure(reason);
              }
            }
          });
        } catch(error) {
          failure(err);
        }
        // success
      }
    });
    ```
  
    Promise Example;
  
    ```javascript
    findAuthor().
      then(findBooksByAuthor).
      then(function(books){
        // found books
    }).catch(function(reason){
      // something went wrong
    });
    ```
  
    @method then
    @param {Function} onFulfilled
    @param {Function} onRejected
    Useful for tooling.
    @return {Promise}
  */
  then: then,

  /**
    `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
    as the catch block of a try/catch statement.
  
    ```js
    function findAuthor(){
      throw new Error('couldn't find that author');
    }
  
    // synchronous
    try {
      findAuthor();
    } catch(reason) {
      // something went wrong
    }
  
    // async with promises
    findAuthor().catch(function(reason){
      // something went wrong
    });
    ```
  
    @method catch
    @param {Function} onRejection
    Useful for tooling.
    @return {Promise}
  */
  'catch': function _catch(onRejection) {
    return this.then(null, onRejection);
  }
};

function polyfill() {
    var local = undefined;

    if (typeof global !== 'undefined') {
        local = global;
    } else if (typeof self !== 'undefined') {
        local = self;
    } else {
        try {
            local = Function('return this')();
        } catch (e) {
            throw new Error('polyfill failed because global object is unavailable in this environment');
        }
    }

    var P = local.Promise;

    if (P) {
        var promiseToString = null;
        try {
            promiseToString = Object.prototype.toString.call(P.resolve());
        } catch (e) {
            // silently ignored
        }

        if (promiseToString === '[object Promise]' && !P.cast) {
            return;
        }
    }

    local.Promise = Promise;
}

polyfill();
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;

return Promise;

})));

}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":24}],8:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

function EventEmitter() {
  this._events = this._events || {};
  this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;

// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;

EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;

// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;

// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
  if (!isNumber(n) || n < 0 || isNaN(n))
    throw TypeError('n must be a positive number');
  this._maxListeners = n;
  return this;
};

EventEmitter.prototype.emit = function(type) {
  var er, handler, len, args, i, listeners;

  if (!this._events)
    this._events = {};

  // If there is no 'error' event listener then throw.
  if (type === 'error') {
    if (!this._events.error ||
        (isObject(this._events.error) && !this._events.error.length)) {
      er = arguments[1];
      if (er instanceof Error) {
        throw er; // Unhandled 'error' event
      } else {
        // At least give some kind of context to the user
        var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
        err.context = er;
        throw err;
      }
    }
  }

  handler = this._events[type];

  if (isUndefined(handler))
    return false;

  if (isFunction(handler)) {
    switch (arguments.length) {
      // fast cases
      case 1:
        handler.call(this);
        break;
      case 2:
        handler.call(this, arguments[1]);
        break;
      case 3:
        handler.call(this, arguments[1], arguments[2]);
        break;
      // slower
      default:
        args = Array.prototype.slice.call(arguments, 1);
        handler.apply(this, args);
    }
  } else if (isObject(handler)) {
    args = Array.prototype.slice.call(arguments, 1);
    listeners = handler.slice();
    len = listeners.length;
    for (i = 0; i < len; i++)
      listeners[i].apply(this, args);
  }

  return true;
};

EventEmitter.prototype.addListener = function(type, listener) {
  var m;

  if (!isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events)
    this._events = {};

  // To avoid recursion in the case that type === "newListener"! Before
  // adding it to the listeners, first emit "newListener".
  if (this._events.newListener)
    this.emit('newListener', type,
              isFunction(listener.listener) ?
              listener.listener : listener);

  if (!this._events[type])
    // Optimize the case of one listener. Don't need the extra array object.
    this._events[type] = listener;
  else if (isObject(this._events[type]))
    // If we've already got an array, just append.
    this._events[type].push(listener);
  else
    // Adding the second element, need to change to array.
    this._events[type] = [this._events[type], listener];

  // Check for listener leak
  if (isObject(this._events[type]) && !this._events[type].warned) {
    if (!isUndefined(this._maxListeners)) {
      m = this._maxListeners;
    } else {
      m = EventEmitter.defaultMaxListeners;
    }

    if (m && m > 0 && this._events[type].length > m) {
      this._events[type].warned = true;
      console.error('(node) warning: possible EventEmitter memory ' +
                    'leak detected. %d listeners added. ' +
                    'Use emitter.setMaxListeners() to increase limit.',
                    this._events[type].length);
      if (typeof console.trace === 'function') {
        // not supported in IE 10
        console.trace();
      }
    }
  }

  return this;
};

EventEmitter.prototype.on = EventEmitter.prototype.addListener;

EventEmitter.prototype.once = function(type, listener) {
  if (!isFunction(listener))
    throw TypeError('listener must be a function');

  var fired = false;

  function g() {
    this.removeListener(type, g);

    if (!fired) {
      fired = true;
      listener.apply(this, arguments);
    }
  }

  g.listener = listener;
  this.on(type, g);

  return this;
};

// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
  var list, position, length, i;

  if (!isFunction(listener))
    throw TypeError('listener must be a function');

  if (!this._events || !this._events[type])
    return this;

  list = this._events[type];
  length = list.length;
  position = -1;

  if (list === listener ||
      (isFunction(list.listener) && list.listener === listener)) {
    delete this._events[type];
    if (this._events.removeListener)
      this.emit('removeListener', type, listener);

  } else if (isObject(list)) {
    for (i = length; i-- > 0;) {
      if (list[i] === listener ||
          (list[i].listener && list[i].listener === listener)) {
        position = i;
        break;
      }
    }

    if (position < 0)
      return this;

    if (list.length === 1) {
      list.length = 0;
      delete this._events[type];
    } else {
      list.splice(position, 1);
    }

    if (this._events.removeListener)
      this.emit('removeListener', type, listener);
  }

  return this;
};

EventEmitter.prototype.removeAllListeners = function(type) {
  var key, listeners;

  if (!this._events)
    return this;

  // not listening for removeListener, no need to emit
  if (!this._events.removeListener) {
    if (arguments.length === 0)
      this._events = {};
    else if (this._events[type])
      delete this._events[type];
    return this;
  }

  // emit removeListener for all listeners on all events
  if (arguments.length === 0) {
    for (key in this._events) {
      if (key === 'removeListener') continue;
      this.removeAllListeners(key);
    }
    this.removeAllListeners('removeListener');
    this._events = {};
    return this;
  }

  listeners = this._events[type];

  if (isFunction(listeners)) {
    this.removeListener(type, listeners);
  } else if (listeners) {
    // LIFO order
    while (listeners.length)
      this.removeListener(type, listeners[listeners.length - 1]);
  }
  delete this._events[type];

  return this;
};

EventEmitter.prototype.listeners = function(type) {
  var ret;
  if (!this._events || !this._events[type])
    ret = [];
  else if (isFunction(this._events[type]))
    ret = [this._events[type]];
  else
    ret = this._events[type].slice();
  return ret;
};

EventEmitter.prototype.listenerCount = function(type) {
  if (this._events) {
    var evlistener = this._events[type];

    if (isFunction(evlistener))
      return 1;
    else if (evlistener)
      return evlistener.length;
  }
  return 0;
};

EventEmitter.listenerCount = function(emitter, type) {
  return emitter.listenerCount(type);
};

function isFunction(arg) {
  return typeof arg === 'function';
}

function isNumber(arg) {
  return typeof arg === 'number';
}

function isObject(arg) {
  return typeof arg === 'object' && arg !== null;
}

function isUndefined(arg) {
  return arg === void 0;
}

},{}],9:[function(require,module,exports){
/**
 * inspired by is-number <https://github.com/jonschlinkert/is-number>
 * but significantly simplified and sped up by ignoring number and string constructors
 * ie these return false:
 *   new Number(1)
 *   new String('1')
 */

'use strict';

/**
 * Is this string all whitespace?
 * This solution kind of makes my brain hurt, but it's significantly faster
 * than !str.trim() or any other solution I could find.
 *
 * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
 * and verified with:
 *
 *  for(var i = 0; i < 65536; i++) {
 *      var s = String.fromCharCode(i);
 *      if(+s===0 && !s.trim()) console.log(i, s);
 *  }
 *
 * which counts a couple of these as *not* whitespace, but finds nothing else
 * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
 * that there are no whitespace characters above this, and code points above
 * this do not map onto white space characters.
 */
function allBlankCharCodes(str){
    var l = str.length,
        a;
    for(var i = 0; i < l; i++) {
        a = str.charCodeAt(i);
        if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
            (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
            (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
            (a !== 8288) && (a !== 12288) && (a !== 65279)) {
                return false;
        }
    }
    return true;
}

module.exports = function(n) {
    var type = typeof n;
    if(type === 'string') {
        var original = n;
        n = +n;
        // whitespace strings cast to zero - filter them out
        if(n===0 && allBlankCharCodes(original)) return false;
    }
    else if(type !== 'number') return false;

    return n - n < 1;
};

},{}],10:[function(require,module,exports){
module.exports = fromQuat;

/**
 * Creates a matrix from a quaternion rotation.
 *
 * @param {mat4} out mat4 receiving operation result
 * @param {quat4} q Rotation quaternion
 * @returns {mat4} out
 */
function fromQuat(out, q) {
    var x = q[0], y = q[1], z = q[2], w = q[3],
        x2 = x + x,
        y2 = y + y,
        z2 = z + z,

        xx = x * x2,
        yx = y * x2,
        yy = y * y2,
        zx = z * x2,
        zy = z * y2,
        zz = z * z2,
        wx = w * x2,
        wy = w * y2,
        wz = w * z2;

    out[0] = 1 - yy - zz;
    out[1] = yx + wz;
    out[2] = zx - wy;
    out[3] = 0;

    out[4] = yx - wz;
    out[5] = 1 - xx - zz;
    out[6] = zy + wx;
    out[7] = 0;

    out[8] = zx + wy;
    out[9] = zy - wx;
    out[10] = 1 - xx - yy;
    out[11] = 0;

    out[12] = 0;
    out[13] = 0;
    out[14] = 0;
    out[15] = 1;

    return out;
};
},{}],11:[function(require,module,exports){
(function (global){
'use strict'

var isBrowser = require('is-browser')
var hasHover

if (typeof global.matchMedia === 'function') {
	hasHover = !global.matchMedia('(hover: none)').matches
}
else {
	hasHover = isBrowser
}

module.exports = hasHover

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"is-browser":13}],12:[function(require,module,exports){
'use strict'

var isBrowser = require('is-browser')

function detect() {
	var supported = false

	try {
		var opts = Object.defineProperty({}, 'passive', {
			get: function() {
				supported = true
			}
		})

		window.addEventListener('test', null, opts)
		window.removeEventListener('test', null, opts)
	} catch(e) {
		supported = false
	}

	return supported
}

module.exports = isBrowser && detect()

},{"is-browser":13}],13:[function(require,module,exports){
module.exports = true;
},{}],14:[function(require,module,exports){
(function (global){
'use strict';(function (f) {
    if (typeof exports === 'object' && typeof module !== 'undefined') {
        module.exports = f();
    } else if (typeof define === 'function' && define.amd) {
        define([], f);
    } else {
        var g;
        if (typeof window !== 'undefined') {
            g = window;
        } else if (typeof global !== 'undefined') {
            g = global;
        } else if (typeof self !== 'undefined') {
            g = self;
        } else {
            g = this;
        }
        g.mapboxgl = f();
    }
}(function () {
    var define, module, exports;
    return function e(t, n, r) {
        function s(o, u) {
            if (!n[o]) {
                if (!t[o]) {
                    var a = typeof require == 'function' && require;
                    if (!u && a) {
                        return a(o, !0);
                    }
                    if (i) {
                        return i(o, !0);
                    }
                    var f = new Error('Cannot find module \'' + o + '\'');
                    throw f.code = 'MODULE_NOT_FOUND', f;
                }
                var l = n[o] = { exports: {} };
                t[o][0].call(l.exports, function (e) {
                    var n = t[o][1][e];
                    return s(n ? n : e);
                }, l, l.exports, e, t, n, r);
            }
            return n[o].exports;
        }
        var i = typeof require == 'function' && require;
        for (var o = 0; o < r.length; o++) {
            s(r[o]);
        }
        return s;
    }({
        1: [
            function (_dereq_, module, exports) {
                function geometry(e) {
                    var r, t = 0;
                    switch (e.type) {
                    case 'Polygon':
                        return polygonArea(e.coordinates);
                    case 'MultiPolygon':
                        for (r = 0; r < e.coordinates.length; r++) {
                            t += polygonArea(e.coordinates[r]);
                        }
                        return t;
                    case 'Point':
                    case 'MultiPoint':
                    case 'LineString':
                    case 'MultiLineString':
                        return 0;
                    case 'GeometryCollection':
                        for (r = 0; r < e.geometries.length; r++) {
                            t += geometry(e.geometries[r]);
                        }
                        return t;
                    }
                }
                function polygonArea(e) {
                    var r = 0;
                    if (e && e.length > 0) {
                        r += Math.abs(ringArea(e[0]));
                        for (var t = 1; t < e.length; t++) {
                            r -= Math.abs(ringArea(e[t]));
                        }
                    }
                    return r;
                }
                function ringArea(e) {
                    var r, t, n, o, a, i, g, s = 0, l = e.length;
                    if (l > 2) {
                        for (g = 0; g < l; g++) {
                            g === l - 2 ? (o = l - 2, a = l - 1, i = 0) : g === l - 1 ? (o = l - 1, a = 0, i = 1) : (o = g, a = g + 1, i = g + 2), r = e[o], t = e[a], n = e[i], s += (rad(n[0]) - rad(r[0])) * Math.sin(rad(t[1]));
                        }
                        s = s * wgs84.RADIUS * wgs84.RADIUS / 2;
                    }
                    return s;
                }
                function rad(e) {
                    return e * Math.PI / 180;
                }
                var wgs84 = _dereq_('wgs84');
                module.exports.geometry = geometry, module.exports.ring = ringArea;
            },
            { 'wgs84': 37 }
        ],
        2: [
            function (_dereq_, module, exports) {
                !function (t, n) {
                    'object' == typeof exports && 'undefined' != typeof module ? module.exports = n() : 'function' == typeof define && define.amd ? define(n) : t.glMatrix = n();
                }(this, function () {
                    'use strict';
                    function t(t, n, r) {
                        var e = n[0], a = n[1], o = n[2];
                        return t[0] = e * r[0] + a * r[3] + o * r[6], t[1] = e * r[1] + a * r[4] + o * r[7], t[2] = e * r[2] + a * r[5] + o * r[8], t;
                    }
                    function n(t, n, r) {
                        var e = n[0], a = n[1], o = n[2], u = n[3];
                        return t[0] = r[0] * e + r[4] * a + r[8] * o + r[12] * u, t[1] = r[1] * e + r[5] * a + r[9] * o + r[13] * u, t[2] = r[2] * e + r[6] * a + r[10] * o + r[14] * u, t[3] = r[3] * e + r[7] * a + r[11] * o + r[15] * u, t;
                    }
                    function r() {
                        var t = new Float32Array(4);
                        return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 1, t;
                    }
                    function e(t, n, r) {
                        var e = n[0], a = n[1], o = n[2], u = n[3], i = Math.sin(r), c = Math.cos(r);
                        return t[0] = e * c + o * i, t[1] = a * c + u * i, t[2] = e * -i + o * c, t[3] = a * -i + u * c, t;
                    }
                    function a(t, n, r) {
                        var e = n[0], a = n[1], o = n[2], u = n[3], i = r[0], c = r[1];
                        return t[0] = e * i, t[1] = a * i, t[2] = o * c, t[3] = u * c, t;
                    }
                    function o() {
                        var t = new Float32Array(9);
                        return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 1, t[5] = 0, t[6] = 0, t[7] = 0, t[8] = 1, t;
                    }
                    function u(t, n) {
                        var r = Math.sin(n), e = Math.cos(n);
                        return t[0] = e, t[1] = r, t[2] = 0, t[3] = -r, t[4] = e, t[5] = 0, t[6] = 0, t[7] = 0, t[8] = 1, t;
                    }
                    function i() {
                        var t = new Float32Array(16);
                        return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = 1, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 1, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t;
                    }
                    function c(t) {
                        return t[0] = 1, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = 1, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 1, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, t;
                    }
                    function f(t, n) {
                        var r = n[0], e = n[1], a = n[2], o = n[3], u = n[4], i = n[5], c = n[6], f = n[7], v = n[8], s = n[9], l = n[10], M = n[11], h = n[12], m = n[13], y = n[14], d = n[15], p = r * i - e * u, w = r * c - a * u, A = r * f - o * u, F = e * c - a * i, x = e * f - o * i, b = a * f - o * c, g = v * m - s * h, j = v * y - l * h, R = v * d - M * h, X = s * y - l * m, Z = s * d - M * m, k = l * d - M * y, q = p * k - w * Z + A * X + F * R - x * j + b * g;
                        return q ? (q = 1 / q, t[0] = (i * k - c * Z + f * X) * q, t[1] = (a * Z - e * k - o * X) * q, t[2] = (m * b - y * x + d * F) * q, t[3] = (l * x - s * b - M * F) * q, t[4] = (c * R - u * k - f * j) * q, t[5] = (r * k - a * R + o * j) * q, t[6] = (y * A - h * b - d * w) * q, t[7] = (v * b - l * A + M * w) * q, t[8] = (u * Z - i * R + f * g) * q, t[9] = (e * R - r * Z - o * g) * q, t[10] = (h * x - m * A + d * p) * q, t[11] = (s * A - v * x - M * p) * q, t[12] = (i * j - u * X - c * g) * q, t[13] = (r * X - e * j + a * g) * q, t[14] = (m * w - h * F - y * p) * q, t[15] = (v * F - s * w + l * p) * q, t) : null;
                    }
                    function v(t, n, r) {
                        var e = n[0], a = n[1], o = n[2], u = n[3], i = n[4], c = n[5], f = n[6], v = n[7], s = n[8], l = n[9], M = n[10], h = n[11], m = n[12], y = n[13], d = n[14], p = n[15], w = r[0], A = r[1], F = r[2], x = r[3];
                        return t[0] = w * e + A * i + F * s + x * m, t[1] = w * a + A * c + F * l + x * y, t[2] = w * o + A * f + F * M + x * d, t[3] = w * u + A * v + F * h + x * p, w = r[4], A = r[5], F = r[6], x = r[7], t[4] = w * e + A * i + F * s + x * m, t[5] = w * a + A * c + F * l + x * y, t[6] = w * o + A * f + F * M + x * d, t[7] = w * u + A * v + F * h + x * p, w = r[8], A = r[9], F = r[10], x = r[11], t[8] = w * e + A * i + F * s + x * m, t[9] = w * a + A * c + F * l + x * y, t[10] = w * o + A * f + F * M + x * d, t[11] = w * u + A * v + F * h + x * p, w = r[12], A = r[13], F = r[14], x = r[15], t[12] = w * e + A * i + F * s + x * m, t[13] = w * a + A * c + F * l + x * y, t[14] = w * o + A * f + F * M + x * d, t[15] = w * u + A * v + F * h + x * p, t;
                    }
                    function s(t, n, r) {
                        var e, a, o, u, i, c, f, v, s, l, M, h, m = r[0], y = r[1], d = r[2];
                        return n === t ? (t[12] = n[0] * m + n[4] * y + n[8] * d + n[12], t[13] = n[1] * m + n[5] * y + n[9] * d + n[13], t[14] = n[2] * m + n[6] * y + n[10] * d + n[14], t[15] = n[3] * m + n[7] * y + n[11] * d + n[15]) : (e = n[0], a = n[1], o = n[2], u = n[3], i = n[4], c = n[5], f = n[6], v = n[7], s = n[8], l = n[9], M = n[10], h = n[11], t[0] = e, t[1] = a, t[2] = o, t[3] = u, t[4] = i, t[5] = c, t[6] = f, t[7] = v, t[8] = s, t[9] = l, t[10] = M, t[11] = h, t[12] = e * m + i * y + s * d + n[12], t[13] = a * m + c * y + l * d + n[13], t[14] = o * m + f * y + M * d + n[14], t[15] = u * m + v * y + h * d + n[15]), t;
                    }
                    function l(t, n, r) {
                        var e = r[0], a = r[1], o = r[2];
                        return t[0] = n[0] * e, t[1] = n[1] * e, t[2] = n[2] * e, t[3] = n[3] * e, t[4] = n[4] * a, t[5] = n[5] * a, t[6] = n[6] * a, t[7] = n[7] * a, t[8] = n[8] * o, t[9] = n[9] * o, t[10] = n[10] * o, t[11] = n[11] * o, t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15], t;
                    }
                    function M(t, n, r) {
                        var e = Math.sin(r), a = Math.cos(r), o = n[4], u = n[5], i = n[6], c = n[7], f = n[8], v = n[9], s = n[10], l = n[11];
                        return n !== t && (t[0] = n[0], t[1] = n[1], t[2] = n[2], t[3] = n[3], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15]), t[4] = o * a + f * e, t[5] = u * a + v * e, t[6] = i * a + s * e, t[7] = c * a + l * e, t[8] = f * a - o * e, t[9] = v * a - u * e, t[10] = s * a - i * e, t[11] = l * a - c * e, t;
                    }
                    function h(t, n, r) {
                        var e = Math.sin(r), a = Math.cos(r), o = n[0], u = n[1], i = n[2], c = n[3], f = n[4], v = n[5], s = n[6], l = n[7];
                        return n !== t && (t[8] = n[8], t[9] = n[9], t[10] = n[10], t[11] = n[11], t[12] = n[12], t[13] = n[13], t[14] = n[14], t[15] = n[15]), t[0] = o * a + f * e, t[1] = u * a + v * e, t[2] = i * a + s * e, t[3] = c * a + l * e, t[4] = f * a - o * e, t[5] = v * a - u * e, t[6] = s * a - i * e, t[7] = l * a - c * e, t;
                    }
                    function m(t, n, r, e, a) {
                        var o = 1 / Math.tan(n / 2), u = 1 / (e - a);
                        return t[0] = o / r, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = o, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = (a + e) * u, t[11] = -1, t[12] = 0, t[13] = 0, t[14] = 2 * a * e * u, t[15] = 0, t;
                    }
                    function y(t, n, r, e, a, o, u) {
                        var i = 1 / (n - r), c = 1 / (e - a), f = 1 / (o - u);
                        return t[0] = -2 * i, t[1] = 0, t[2] = 0, t[3] = 0, t[4] = 0, t[5] = -2 * c, t[6] = 0, t[7] = 0, t[8] = 0, t[9] = 0, t[10] = 2 * f, t[11] = 0, t[12] = (n + r) * i, t[13] = (a + e) * c, t[14] = (u + o) * f, t[15] = 1, t;
                    }
                    (function () {
                        var t = new Float32Array(3);
                        t[0] = 0, t[1] = 0, t[2] = 0;
                    }(), function () {
                        var t = new Float32Array(4);
                        t[0] = 0, t[1] = 0, t[2] = 0, t[3] = 0;
                    }());
                    return {
                        vec3: { transformMat3: t },
                        vec4: { transformMat4: n },
                        mat2: {
                            create: r,
                            rotate: e,
                            scale: a
                        },
                        mat3: {
                            create: o,
                            fromRotation: u
                        },
                        mat4: {
                            create: i,
                            identity: c,
                            translate: s,
                            scale: l,
                            multiply: v,
                            perspective: m,
                            rotateX: M,
                            rotateZ: h,
                            invert: f,
                            ortho: y
                        }
                    };
                });
            },
            {}
        ],
        3: [
            function (_dereq_, module, exports) {
                'use strict';
                function isSupported(e) {
                    return !!(isBrowser() && isArraySupported() && isFunctionSupported() && isObjectSupported() && isJSONSupported() && isWorkerSupported() && isUint8ClampedArraySupported() && isWebGLSupportedCached(e && e.failIfMajorPerformanceCaveat));
                }
                function isBrowser() {
                    return 'undefined' != typeof window && 'undefined' != typeof document;
                }
                function isArraySupported() {
                    return Array.prototype && Array.prototype.every && Array.prototype.filter && Array.prototype.forEach && Array.prototype.indexOf && Array.prototype.lastIndexOf && Array.prototype.map && Array.prototype.some && Array.prototype.reduce && Array.prototype.reduceRight && Array.isArray;
                }
                function isFunctionSupported() {
                    return Function.prototype && Function.prototype.bind;
                }
                function isObjectSupported() {
                    return Object.keys && Object.create && Object.getPrototypeOf && Object.getOwnPropertyNames && Object.isSealed && Object.isFrozen && Object.isExtensible && Object.getOwnPropertyDescriptor && Object.defineProperty && Object.defineProperties && Object.seal && Object.freeze && Object.preventExtensions;
                }
                function isJSONSupported() {
                    return 'JSON' in window && 'parse' in JSON && 'stringify' in JSON;
                }
                function isWorkerSupported() {
                    if (!('Worker' in window && 'Blob' in window)) {
                        return !1;
                    }
                    var e, t, r = new Blob([''], { type: 'text/javascript' }), o = URL.createObjectURL(r);
                    try {
                        t = new Worker(o), e = !0;
                    } catch (t) {
                        e = !1;
                    }
                    return t && t.terminate(), URL.revokeObjectURL(o), e;
                }
                function isUint8ClampedArraySupported() {
                    return 'Uint8ClampedArray' in window;
                }
                function isWebGLSupportedCached(e) {
                    return void 0 === isWebGLSupportedCache[e] && (isWebGLSupportedCache[e] = isWebGLSupported(e)), isWebGLSupportedCache[e];
                }
                function isWebGLSupported(e) {
                    var t = document.createElement('canvas'), r = Object.create(isSupported.webGLContextAttributes);
                    return r.failIfMajorPerformanceCaveat = e, t.probablySupportsContext ? t.probablySupportsContext('webgl', r) || t.probablySupportsContext('experimental-webgl', r) : t.supportsContext ? t.supportsContext('webgl', r) || t.supportsContext('experimental-webgl', r) : t.getContext('webgl', r) || t.getContext('experimental-webgl', r);
                }
                'undefined' != typeof module && module.exports ? module.exports = isSupported : window && (window.mapboxgl = window.mapboxgl || {}, window.mapboxgl.supported = isSupported);
                var isWebGLSupportedCache = {};
                isSupported.webGLContextAttributes = {
                    antialias: !1,
                    alpha: !0,
                    stencil: !0,
                    depth: !0
                };
            },
            {}
        ],
        4: [
            function (_dereq_, module, exports) {
                'use strict';
                function Point(t, n) {
                    this.x = t, this.y = n;
                }
                module.exports = Point, Point.prototype = {
                    clone: function () {
                        return new Point(this.x, this.y);
                    },
                    add: function (t) {
                        return this.clone()._add(t);
                    },
                    sub: function (t) {
                        return this.clone()._sub(t);
                    },
                    multByPoint: function (t) {
                        return this.clone()._multByPoint(t);
                    },
                    divByPoint: function (t) {
                        return this.clone()._divByPoint(t);
                    },
                    mult: function (t) {
                        return this.clone()._mult(t);
                    },
                    div: function (t) {
                        return this.clone()._div(t);
                    },
                    rotate: function (t) {
                        return this.clone()._rotate(t);
                    },
                    rotateAround: function (t, n) {
                        return this.clone()._rotateAround(t, n);
                    },
                    matMult: function (t) {
                        return this.clone()._matMult(t);
                    },
                    unit: function () {
                        return this.clone()._unit();
                    },
                    perp: function () {
                        return this.clone()._perp();
                    },
                    round: function () {
                        return this.clone()._round();
                    },
                    mag: function () {
                        return Math.sqrt(this.x * this.x + this.y * this.y);
                    },
                    equals: function (t) {
                        return this.x === t.x && this.y === t.y;
                    },
                    dist: function (t) {
                        return Math.sqrt(this.distSqr(t));
                    },
                    distSqr: function (t) {
                        var n = t.x - this.x, i = t.y - this.y;
                        return n * n + i * i;
                    },
                    angle: function () {
                        return Math.atan2(this.y, this.x);
                    },
                    angleTo: function (t) {
                        return Math.atan2(this.y - t.y, this.x - t.x);
                    },
                    angleWith: function (t) {
                        return this.angleWithSep(t.x, t.y);
                    },
                    angleWithSep: function (t, n) {
                        return Math.atan2(this.x * n - this.y * t, this.x * t + this.y * n);
                    },
                    _matMult: function (t) {
                        var n = t[0] * this.x + t[1] * this.y, i = t[2] * this.x + t[3] * this.y;
                        return this.x = n, this.y = i, this;
                    },
                    _add: function (t) {
                        return this.x += t.x, this.y += t.y, this;
                    },
                    _sub: function (t) {
                        return this.x -= t.x, this.y -= t.y, this;
                    },
                    _mult: function (t) {
                        return this.x *= t, this.y *= t, this;
                    },
                    _div: function (t) {
                        return this.x /= t, this.y /= t, this;
                    },
                    _multByPoint: function (t) {
                        return this.x *= t.x, this.y *= t.y, this;
                    },
                    _divByPoint: function (t) {
                        return this.x /= t.x, this.y /= t.y, this;
                    },
                    _unit: function () {
                        return this._div(this.mag()), this;
                    },
                    _perp: function () {
                        var t = this.y;
                        return this.y = this.x, this.x = -t, this;
                    },
                    _rotate: function (t) {
                        var n = Math.cos(t), i = Math.sin(t), s = n * this.x - i * this.y, r = i * this.x + n * this.y;
                        return this.x = s, this.y = r, this;
                    },
                    _rotateAround: function (t, n) {
                        var i = Math.cos(t), s = Math.sin(t), r = n.x + i * (this.x - n.x) - s * (this.y - n.y), h = n.y + s * (this.x - n.x) + i * (this.y - n.y);
                        return this.x = r, this.y = h, this;
                    },
                    _round: function () {
                        return this.x = Math.round(this.x), this.y = Math.round(this.y), this;
                    }
                }, Point.convert = function (t) {
                    return t instanceof Point ? t : Array.isArray(t) ? new Point(t[0], t[1]) : t;
                };
            },
            {}
        ],
        5: [
            function (_dereq_, module, exports) {
                !function (t, e) {
                    'object' == typeof exports && 'undefined' != typeof module ? module.exports = e() : 'function' == typeof define && define.amd ? define(e) : t.ShelfPack = e();
                }(this, function () {
                    function t(t, e, i) {
                        i = i || {}, this.w = t || 64, this.h = e || 64, this.autoResize = !!i.autoResize, this.shelves = [], this.freebins = [], this.stats = {}, this.bins = {}, this.maxId = 0;
                    }
                    function e(t, e, i) {
                        this.x = 0, this.y = t, this.w = this.free = e, this.h = i;
                    }
                    function i(t, e, i, s, h, n, r) {
                        this.id = t, this.x = e, this.y = i, this.w = s, this.h = h, this.maxw = n || s, this.maxh = r || h, this.refcount = 0;
                    }
                    return t.prototype.pack = function (t, e) {
                        var this$1 = this;
                        t = [].concat(t), e = e || {};
                        for (var i, s, h, n, r = [], f = 0; f < t.length; f++) {
                            if (i = t[f].w || t[f].width, s = t[f].h || t[f].height, h = t[f].id, i && s) {
                                if (!(n = this$1.packOne(i, s, h))) {
                                    continue;
                                }
                                e.inPlace && (t[f].x = n.x, t[f].y = n.y, t[f].id = n.id), r.push(n);
                            }
                        }
                        return this.shrink(), r;
                    }, t.prototype.packOne = function (t, i, s) {
                        var this$1 = this;
                        var h, n, r, f, o = {
                                freebin: -1,
                                shelf: -1,
                                waste: 1 / 0
                            }, a = 0;
                        if ('string' == typeof s || 'number' == typeof s) {
                            if (h = this.getBin(s)) {
                                return this.ref(h), h;
                            }
                            'number' == typeof s && (this.maxId = Math.max(s, this.maxId));
                        } else {
                            s = ++this.maxId;
                        }
                        for (f = 0; f < this.freebins.length; f++) {
                            if (h = this$1.freebins[f], i === h.maxh && t === h.maxw) {
                                return this$1.allocFreebin(f, t, i, s);
                            }
                            i > h.maxh || t > h.maxw || i <= h.maxh && t <= h.maxw && (r = h.maxw * h.maxh - t * i) < o.waste && (o.waste = r, o.freebin = f);
                        }
                        for (f = 0; f < this.shelves.length; f++) {
                            if (n = this$1.shelves[f], a += n.h, !(t > n.free)) {
                                if (i === n.h) {
                                    return this$1.allocShelf(f, t, i, s);
                                }
                                i > n.h || i < n.h && (r = (n.h - i) * t) < o.waste && (o.freebin = -1, o.waste = r, o.shelf = f);
                            }
                        }
                        if (-1 !== o.freebin) {
                            return this.allocFreebin(o.freebin, t, i, s);
                        }
                        if (-1 !== o.shelf) {
                            return this.allocShelf(o.shelf, t, i, s);
                        }
                        if (i <= this.h - a && t <= this.w) {
                            return n = new e(a, this.w, i), this.allocShelf(this.shelves.push(n) - 1, t, i, s);
                        }
                        if (this.autoResize) {
                            var u, l, c, p;
                            return u = l = this.h, c = p = this.w, (c <= u || t > c) && (p = 2 * Math.max(t, c)), (u < c || i > u) && (l = 2 * Math.max(i, u)), this.resize(p, l), this.packOne(t, i, s);
                        }
                        return null;
                    }, t.prototype.allocFreebin = function (t, e, i, s) {
                        var h = this.freebins.splice(t, 1)[0];
                        return h.id = s, h.w = e, h.h = i, h.refcount = 0, this.bins[s] = h, this.ref(h), h;
                    }, t.prototype.allocShelf = function (t, e, i, s) {
                        var h = this.shelves[t], n = h.alloc(e, i, s);
                        return this.bins[s] = n, this.ref(n), n;
                    }, t.prototype.shrink = function () {
                        var this$1 = this;
                        if (this.shelves.length > 0) {
                            for (var t = 0, e = 0, i = 0; i < this.shelves.length; i++) {
                                var s = this$1.shelves[i];
                                e += s.h, t = Math.max(s.w - s.free, t);
                            }
                            this.resize(t, e);
                        }
                    }, t.prototype.getBin = function (t) {
                        return this.bins[t];
                    }, t.prototype.ref = function (t) {
                        if (1 == ++t.refcount) {
                            var e = t.h;
                            this.stats[e] = 1 + (0 | this.stats[e]);
                        }
                        return t.refcount;
                    }, t.prototype.unref = function (t) {
                        return 0 === t.refcount ? 0 : (0 == --t.refcount && (this.stats[t.h]--, delete this.bins[t.id], this.freebins.push(t)), t.refcount);
                    }, t.prototype.clear = function () {
                        this.shelves = [], this.freebins = [], this.stats = {}, this.bins = {}, this.maxId = 0;
                    }, t.prototype.resize = function (t, e) {
                        var this$1 = this;
                        this.w = t, this.h = e;
                        for (var i = 0; i < this.shelves.length; i++) {
                            this$1.shelves[i].resize(t);
                        }
                        return !0;
                    }, e.prototype.alloc = function (t, e, s) {
                        if (t > this.free || e > this.h) {
                            return null;
                        }
                        var h = this.x;
                        return this.x += t, this.free -= t, new i(s, h, this.y, t, e, t, this.h);
                    }, e.prototype.resize = function (t) {
                        return this.free += t - this.w, this.w = t, !0;
                    }, t;
                });
            },
            {}
        ],
        6: [
            function (_dereq_, module, exports) {
                'use strict';
                function TinySDF(t, i, s, e, h, r) {
                    this.fontSize = t || 24, this.buffer = void 0 === i ? 3 : i, this.cutoff = e || 0.25, this.fontFamily = h || 'sans-serif', this.fontWeight = r || 'normal', this.radius = s || 8;
                    var a = this.size = this.fontSize + 2 * this.buffer;
                    this.canvas = document.createElement('canvas'), this.canvas.width = this.canvas.height = a, this.ctx = this.canvas.getContext('2d'), this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily, this.ctx.textBaseline = 'middle', this.ctx.fillStyle = 'black', this.gridOuter = new Float64Array(a * a), this.gridInner = new Float64Array(a * a), this.f = new Float64Array(a), this.d = new Float64Array(a), this.z = new Float64Array(a + 1), this.v = new Int16Array(a), this.middle = Math.round(a / 2 * (navigator.userAgent.indexOf('Gecko/') >= 0 ? 1.2 : 1));
                }
                function edt(t, i, s, e, h, r, a) {
                    for (var n = 0; n < i; n++) {
                        for (var o = 0; o < s; o++) {
                            e[o] = t[o * i + n];
                        }
                        for (edt1d(e, h, r, a, s), o = 0; o < s; o++) {
                            t[o * i + n] = h[o];
                        }
                    }
                    for (o = 0; o < s; o++) {
                        for (n = 0; n < i; n++) {
                            e[n] = t[o * i + n];
                        }
                        for (edt1d(e, h, r, a, i), n = 0; n < i; n++) {
                            t[o * i + n] = Math.sqrt(h[n]);
                        }
                    }
                }
                function edt1d(t, i, s, e, h) {
                    s[0] = 0, e[0] = -INF, e[1] = +INF;
                    for (var r = 1, a = 0; r < h; r++) {
                        for (var n = (t[r] + r * r - (t[s[a]] + s[a] * s[a])) / (2 * r - 2 * s[a]); n <= e[a];) {
                            a--, n = (t[r] + r * r - (t[s[a]] + s[a] * s[a])) / (2 * r - 2 * s[a]);
                        }
                        a++, s[a] = r, e[a] = n, e[a + 1] = +INF;
                    }
                    for (r = 0, a = 0; r < h; r++) {
                        for (; e[a + 1] < r;) {
                            a++;
                        }
                        i[r] = (r - s[a]) * (r - s[a]) + t[s[a]];
                    }
                }
                module.exports = TinySDF;
                var INF = 100000000000000000000;
                TinySDF.prototype.draw = function (t) {
                    var this$1 = this;
                    this.ctx.clearRect(0, 0, this.size, this.size), this.ctx.fillText(t, this.buffer, this.middle);
                    for (var i = this.ctx.getImageData(0, 0, this.size, this.size), s = new Uint8ClampedArray(this.size * this.size), e = 0; e < this.size * this.size; e++) {
                        var h = i.data[4 * e + 3] / 255;
                        this$1.gridOuter[e] = 1 === h ? 0 : 0 === h ? INF : Math.pow(Math.max(0, 0.5 - h), 2), this$1.gridInner[e] = 1 === h ? INF : 0 === h ? 0 : Math.pow(Math.max(0, h - 0.5), 2);
                    }
                    for (edt(this.gridOuter, this.size, this.size, this.f, this.d, this.v, this.z), edt(this.gridInner, this.size, this.size, this.f, this.d, this.v, this.z), e = 0; e < this.size * this.size; e++) {
                        var r = this$1.gridOuter[e] - this$1.gridInner[e];
                        s[e] = Math.max(0, Math.min(255, Math.round(255 - 255 * (r / this$1.radius + this$1.cutoff))));
                    }
                    return s;
                };
            },
            {}
        ],
        7: [
            function (_dereq_, module, exports) {
                function UnitBezier(t, i, e, r) {
                    this.cx = 3 * t, this.bx = 3 * (e - t) - this.cx, this.ax = 1 - this.cx - this.bx, this.cy = 3 * i, this.by = 3 * (r - i) - this.cy, this.ay = 1 - this.cy - this.by, this.p1x = t, this.p1y = r, this.p2x = e, this.p2y = r;
                }
                module.exports = UnitBezier, UnitBezier.prototype.sampleCurveX = function (t) {
                    return ((this.ax * t + this.bx) * t + this.cx) * t;
                }, UnitBezier.prototype.sampleCurveY = function (t) {
                    return ((this.ay * t + this.by) * t + this.cy) * t;
                }, UnitBezier.prototype.sampleCurveDerivativeX = function (t) {
                    return (3 * this.ax * t + 2 * this.bx) * t + this.cx;
                }, UnitBezier.prototype.solveCurveX = function (t, i) {
                    var this$1 = this;
                    void 0 === i && (i = 0.000001);
                    var e, r, s, h, n;
                    for (s = t, n = 0; n < 8; n++) {
                        if (h = this$1.sampleCurveX(s) - t, Math.abs(h) < i) {
                            return s;
                        }
                        var u = this$1.sampleCurveDerivativeX(s);
                        if (Math.abs(u) < 0.000001) {
                            break;
                        }
                        s -= h / u;
                    }
                    if (e = 0, r = 1, (s = t) < e) {
                        return e;
                    }
                    if (s > r) {
                        return r;
                    }
                    for (; e < r;) {
                        if (h = this$1.sampleCurveX(s), Math.abs(h - t) < i) {
                            return s;
                        }
                        t > h ? e = s : r = s, s = 0.5 * (r - e) + e;
                    }
                    return s;
                }, UnitBezier.prototype.solve = function (t, i) {
                    return this.sampleCurveY(this.solveCurveX(t, i));
                };
            },
            {}
        ],
        8: [
            function (_dereq_, module, exports) {
                module.exports.VectorTile = _dereq_('./lib/vectortile.js'), module.exports.VectorTileFeature = _dereq_('./lib/vectortilefeature.js'), module.exports.VectorTileLayer = _dereq_('./lib/vectortilelayer.js');
            },
            {
                './lib/vectortile.js': 9,
                './lib/vectortilefeature.js': 10,
                './lib/vectortilelayer.js': 11
            }
        ],
        9: [
            function (_dereq_, module, exports) {
                'use strict';
                function VectorTile(e, r) {
                    this.layers = e.readFields(readTile, {}, r);
                }
                function readTile(e, r, i) {
                    if (3 === e) {
                        var t = new VectorTileLayer(i, i.readVarint() + i.pos);
                        t.length && (r[t.name] = t);
                    }
                }
                var VectorTileLayer = _dereq_('./vectortilelayer');
                module.exports = VectorTile;
            },
            { './vectortilelayer': 11 }
        ],
        10: [
            function (_dereq_, module, exports) {
                'use strict';
                function VectorTileFeature(e, t, r, a, i) {
                    this.properties = {}, this.extent = r, this.type = 0, this._pbf = e, this._geometry = -1, this._keys = a, this._values = i, e.readFields(readFeature, this, t);
                }
                function readFeature(e, t, r) {
                    1 == e ? t.id = r.readVarint() : 2 == e ? readTag(r, t) : 3 == e ? t.type = r.readVarint() : 4 == e && (t._geometry = r.pos);
                }
                function readTag(e, t) {
                    for (var r = e.readVarint() + e.pos; e.pos < r;) {
                        var a = t._keys[e.readVarint()], i = t._values[e.readVarint()];
                        t.properties[a] = i;
                    }
                }
                function classifyRings(e) {
                    var t = e.length;
                    if (t <= 1) {
                        return [e];
                    }
                    for (var r, a, i = [], o = 0; o < t; o++) {
                        var n = signedArea(e[o]);
                        0 !== n && (void 0 === a && (a = n < 0), a === n < 0 ? (r && i.push(r), r = [e[o]]) : r.push(e[o]));
                    }
                    return r && i.push(r), i;
                }
                function signedArea(e) {
                    for (var t, r, a = 0, i = 0, o = e.length, n = o - 1; i < o; n = i++) {
                        t = e[i], r = e[n], a += (r.x - t.x) * (t.y + r.y);
                    }
                    return a;
                }
                var Point = _dereq_('@mapbox/point-geometry');
                module.exports = VectorTileFeature, VectorTileFeature.types = [
                    'Unknown',
                    'Point',
                    'LineString',
                    'Polygon'
                ], VectorTileFeature.prototype.loadGeometry = function () {
                    var e = this._pbf;
                    e.pos = this._geometry;
                    for (var t, r = e.readVarint() + e.pos, a = 1, i = 0, o = 0, n = 0, s = []; e.pos < r;) {
                        if (!i) {
                            var p = e.readVarint();
                            a = 7 & p, i = p >> 3;
                        }
                        if (i--, 1 === a || 2 === a) {
                            o += e.readSVarint(), n += e.readSVarint(), 1 === a && (t && s.push(t), t = []), t.push(new Point(o, n));
                        } else {
                            if (7 !== a) {
                                throw new Error('unknown command ' + a);
                            }
                            t && t.push(t[0].clone());
                        }
                    }
                    return t && s.push(t), s;
                }, VectorTileFeature.prototype.bbox = function () {
                    var e = this._pbf;
                    e.pos = this._geometry;
                    for (var t = e.readVarint() + e.pos, r = 1, a = 0, i = 0, o = 0, n = 1 / 0, s = -1 / 0, p = 1 / 0, h = -1 / 0; e.pos < t;) {
                        if (!a) {
                            var u = e.readVarint();
                            r = 7 & u, a = u >> 3;
                        }
                        if (a--, 1 === r || 2 === r) {
                            i += e.readSVarint(), o += e.readSVarint(), i < n && (n = i), i > s && (s = i), o < p && (p = o), o > h && (h = o);
                        } else if (7 !== r) {
                            throw new Error('unknown command ' + r);
                        }
                    }
                    return [
                        n,
                        p,
                        s,
                        h
                    ];
                }, VectorTileFeature.prototype.toGeoJSON = function (e, t, r) {
                    function a(e) {
                        for (var t = 0; t < e.length; t++) {
                            var r = e[t], a = 180 - 360 * (r.y + p) / n;
                            e[t] = [
                                360 * (r.x + s) / n - 180,
                                360 / Math.PI * Math.atan(Math.exp(a * Math.PI / 180)) - 90
                            ];
                        }
                    }
                    var i, o, n = this.extent * Math.pow(2, r), s = this.extent * e, p = this.extent * t, h = this.loadGeometry(), u = VectorTileFeature.types[this.type];
                    switch (this.type) {
                    case 1:
                        var d = [];
                        for (i = 0; i < h.length; i++) {
                            d[i] = h[i][0];
                        }
                        h = d, a(h);
                        break;
                    case 2:
                        for (i = 0; i < h.length; i++) {
                            a(h[i]);
                        }
                        break;
                    case 3:
                        for (h = classifyRings(h), i = 0; i < h.length; i++) {
                            for (o = 0; o < h[i].length; o++) {
                                a(h[i][o]);
                            }
                        }
                    }
                    1 === h.length ? h = h[0] : u = 'Multi' + u;
                    var f = {
                        type: 'Feature',
                        geometry: {
                            type: u,
                            coordinates: h
                        },
                        properties: this.properties
                    };
                    return 'id' in this && (f.id = this.id), f;
                };
            },
            { '@mapbox/point-geometry': 4 }
        ],
        11: [
            function (_dereq_, module, exports) {
                'use strict';
                function VectorTileLayer(e, t) {
                    this.version = 1, this.name = null, this.extent = 4096, this.length = 0, this._pbf = e, this._keys = [], this._values = [], this._features = [], e.readFields(readLayer, this, t), this.length = this._features.length;
                }
                function readLayer(e, t, r) {
                    15 === e ? t.version = r.readVarint() : 1 === e ? t.name = r.readString() : 5 === e ? t.extent = r.readVarint() : 2 === e ? t._features.push(r.pos) : 3 === e ? t._keys.push(r.readString()) : 4 === e && t._values.push(readValueMessage(r));
                }
                function readValueMessage(e) {
                    for (var t = null, r = e.readVarint() + e.pos; e.pos < r;) {
                        var a = e.readVarint() >> 3;
                        t = 1 === a ? e.readString() : 2 === a ? e.readFloat() : 3 === a ? e.readDouble() : 4 === a ? e.readVarint64() : 5 === a ? e.readVarint() : 6 === a ? e.readSVarint() : 7 === a ? e.readBoolean() : null;
                    }
                    return t;
                }
                var VectorTileFeature = _dereq_('./vectortilefeature.js');
                module.exports = VectorTileLayer, VectorTileLayer.prototype.feature = function (e) {
                    if (e < 0 || e >= this._features.length) {
                        throw new Error('feature index out of bounds');
                    }
                    this._pbf.pos = this._features[e];
                    var t = this._pbf.readVarint() + this._pbf.pos;
                    return new VectorTileFeature(this._pbf, t, this.extent, this._keys, this._values);
                };
            },
            { './vectortilefeature.js': 10 }
        ],
        12: [
            function (_dereq_, module, exports) {
                !function (e, t) {
                    'object' == typeof exports && 'undefined' != typeof module ? t(exports) : 'function' == typeof define && define.amd ? define(['exports'], t) : t(e.WhooTS = e.WhooTS || {});
                }(this, function (e) {
                    function t(e, t, r, n, i, s) {
                        return s = s || {}, e + '?' + [
                            'bbox=' + o(r, n, i),
                            'format=' + (s.format || 'image/png'),
                            'service=' + (s.service || 'WMS'),
                            'version=' + (s.version || '1.1.1'),
                            'request=' + (s.request || 'GetMap'),
                            'srs=' + (s.srs || 'EPSG:3857'),
                            'width=' + (s.width || 256),
                            'height=' + (s.height || 256),
                            'layers=' + t
                        ].join('&');
                    }
                    function o(e, t, o) {
                        t = Math.pow(2, o) - t - 1;
                        var n = r(256 * e, 256 * t, o), i = r(256 * (e + 1), 256 * (t + 1), o);
                        return n[0] + ',' + n[1] + ',' + i[0] + ',' + i[1];
                    }
                    function r(e, t, o) {
                        var r = 2 * Math.PI * 6378137 / 256 / Math.pow(2, o);
                        return [
                            e * r - 2 * Math.PI * 6378137 / 2,
                            t * r - 2 * Math.PI * 6378137 / 2
                        ];
                    }
                    e.getURL = t, e.getTileBBox = o, e.getMercCoords = r, Object.defineProperty(e, '__esModule', { value: !0 });
                });
            },
            {}
        ],
        13: [
            function (_dereq_, module, exports) {
                function clamp_css_byte(e) {
                    return e = Math.round(e), e < 0 ? 0 : e > 255 ? 255 : e;
                }
                function clamp_css_float(e) {
                    return e < 0 ? 0 : e > 1 ? 1 : e;
                }
                function parse_css_int(e) {
                    return clamp_css_byte('%' === e[e.length - 1] ? parseFloat(e) / 100 * 255 : parseInt(e));
                }
                function parse_css_float(e) {
                    return clamp_css_float('%' === e[e.length - 1] ? parseFloat(e) / 100 : parseFloat(e));
                }
                function css_hue_to_rgb(e, r, l) {
                    return l < 0 ? l += 1 : l > 1 && (l -= 1), 6 * l < 1 ? e + (r - e) * l * 6 : 2 * l < 1 ? r : 3 * l < 2 ? e + (r - e) * (2 / 3 - l) * 6 : e;
                }
                function parseCSSColor(e) {
                    var r = e.replace(/ /g, '').toLowerCase();
                    if (r in kCSSColorTable) {
                        return kCSSColorTable[r].slice();
                    }
                    if ('#' === r[0]) {
                        if (4 === r.length) {
                            var l = parseInt(r.substr(1), 16);
                            return l >= 0 && l <= 4095 ? [
                                (3840 & l) >> 4 | (3840 & l) >> 8,
                                240 & l | (240 & l) >> 4,
                                15 & l | (15 & l) << 4,
                                1
                            ] : null;
                        }
                        if (7 === r.length) {
                            var l = parseInt(r.substr(1), 16);
                            return l >= 0 && l <= 16777215 ? [
                                (16711680 & l) >> 16,
                                (65280 & l) >> 8,
                                255 & l,
                                1
                            ] : null;
                        }
                        return null;
                    }
                    var a = r.indexOf('('), t = r.indexOf(')');
                    if (-1 !== a && t + 1 === r.length) {
                        var n = r.substr(0, a), s = r.substr(a + 1, t - (a + 1)).split(','), o = 1;
                        switch (n) {
                        case 'rgba':
                            if (4 !== s.length) {
                                return null;
                            }
                            o = parse_css_float(s.pop());
                        case 'rgb':
                            return 3 !== s.length ? null : [
                                parse_css_int(s[0]),
                                parse_css_int(s[1]),
                                parse_css_int(s[2]),
                                o
                            ];
                        case 'hsla':
                            if (4 !== s.length) {
                                return null;
                            }
                            o = parse_css_float(s.pop());
                        case 'hsl':
                            if (3 !== s.length) {
                                return null;
                            }
                            var i = (parseFloat(s[0]) % 360 + 360) % 360 / 360, u = parse_css_float(s[1]), g = parse_css_float(s[2]), d = g <= 0.5 ? g * (u + 1) : g + u - g * u, c = 2 * g - d;
                            return [
                                clamp_css_byte(255 * css_hue_to_rgb(c, d, i + 1 / 3)),
                                clamp_css_byte(255 * css_hue_to_rgb(c, d, i)),
                                clamp_css_byte(255 * css_hue_to_rgb(c, d, i - 1 / 3)),
                                o
                            ];
                        default:
                            return null;
                        }
                    }
                    return null;
                }
                var kCSSColorTable = {
                    transparent: [
                        0,
                        0,
                        0,
                        0
                    ],
                    aliceblue: [
                        240,
                        248,
                        255,
                        1
                    ],
                    antiquewhite: [
                        250,
                        235,
                        215,
                        1
                    ],
                    aqua: [
                        0,
                        255,
                        255,
                        1
                    ],
                    aquamarine: [
                        127,
                        255,
                        212,
                        1
                    ],
                    azure: [
                        240,
                        255,
                        255,
                        1
                    ],
                    beige: [
                        245,
                        245,
                        220,
                        1
                    ],
                    bisque: [
                        255,
                        228,
                        196,
                        1
                    ],
                    black: [
                        0,
                        0,
                        0,
                        1
                    ],
                    blanchedalmond: [
                        255,
                        235,
                        205,
                        1
                    ],
                    blue: [
                        0,
                        0,
                        255,
                        1
                    ],
                    blueviolet: [
                        138,
                        43,
                        226,
                        1
                    ],
                    brown: [
                        165,
                        42,
                        42,
                        1
                    ],
                    burlywood: [
                        222,
                        184,
                        135,
                        1
                    ],
                    cadetblue: [
                        95,
                        158,
                        160,
                        1
                    ],
                    chartreuse: [
                        127,
                        255,
                        0,
                        1
                    ],
                    chocolate: [
                        210,
                        105,
                        30,
                        1
                    ],
                    coral: [
                        255,
                        127,
                        80,
                        1
                    ],
                    cornflowerblue: [
                        100,
                        149,
                        237,
                        1
                    ],
                    cornsilk: [
                        255,
                        248,
                        220,
                        1
                    ],
                    crimson: [
                        220,
                        20,
                        60,
                        1
                    ],
                    cyan: [
                        0,
                        255,
                        255,
                        1
                    ],
                    darkblue: [
                        0,
                        0,
                        139,
                        1
                    ],
                    darkcyan: [
                        0,
                        139,
                        139,
                        1
                    ],
                    darkgoldenrod: [
                        184,
                        134,
                        11,
                        1
                    ],
                    darkgray: [
                        169,
                        169,
                        169,
                        1
                    ],
                    darkgreen: [
                        0,
                        100,
                        0,
                        1
                    ],
                    darkgrey: [
                        169,
                        169,
                        169,
                        1
                    ],
                    darkkhaki: [
                        189,
                        183,
                        107,
                        1
                    ],
                    darkmagenta: [
                        139,
                        0,
                        139,
                        1
                    ],
                    darkolivegreen: [
                        85,
                        107,
                        47,
                        1
                    ],
                    darkorange: [
                        255,
                        140,
                        0,
                        1
                    ],
                    darkorchid: [
                        153,
                        50,
                        204,
                        1
                    ],
                    darkred: [
                        139,
                        0,
                        0,
                        1
                    ],
                    darksalmon: [
                        233,
                        150,
                        122,
                        1
                    ],
                    darkseagreen: [
                        143,
                        188,
                        143,
                        1
                    ],
                    darkslateblue: [
                        72,
                        61,
                        139,
                        1
                    ],
                    darkslategray: [
                        47,
                        79,
                        79,
                        1
                    ],
                    darkslategrey: [
                        47,
                        79,
                        79,
                        1
                    ],
                    darkturquoise: [
                        0,
                        206,
                        209,
                        1
                    ],
                    darkviolet: [
                        148,
                        0,
                        211,
                        1
                    ],
                    deeppink: [
                        255,
                        20,
                        147,
                        1
                    ],
                    deepskyblue: [
                        0,
                        191,
                        255,
                        1
                    ],
                    dimgray: [
                        105,
                        105,
                        105,
                        1
                    ],
                    dimgrey: [
                        105,
                        105,
                        105,
                        1
                    ],
                    dodgerblue: [
                        30,
                        144,
                        255,
                        1
                    ],
                    firebrick: [
                        178,
                        34,
                        34,
                        1
                    ],
                    floralwhite: [
                        255,
                        250,
                        240,
                        1
                    ],
                    forestgreen: [
                        34,
                        139,
                        34,
                        1
                    ],
                    fuchsia: [
                        255,
                        0,
                        255,
                        1
                    ],
                    gainsboro: [
                        220,
                        220,
                        220,
                        1
                    ],
                    ghostwhite: [
                        248,
                        248,
                        255,
                        1
                    ],
                    gold: [
                        255,
                        215,
                        0,
                        1
                    ],
                    goldenrod: [
                        218,
                        165,
                        32,
                        1
                    ],
                    gray: [
                        128,
                        128,
                        128,
                        1
                    ],
                    green: [
                        0,
                        128,
                        0,
                        1
                    ],
                    greenyellow: [
                        173,
                        255,
                        47,
                        1
                    ],
                    grey: [
                        128,
                        128,
                        128,
                        1
                    ],
                    honeydew: [
                        240,
                        255,
                        240,
                        1
                    ],
                    hotpink: [
                        255,
                        105,
                        180,
                        1
                    ],
                    indianred: [
                        205,
                        92,
                        92,
                        1
                    ],
                    indigo: [
                        75,
                        0,
                        130,
                        1
                    ],
                    ivory: [
                        255,
                        255,
                        240,
                        1
                    ],
                    khaki: [
                        240,
                        230,
                        140,
                        1
                    ],
                    lavender: [
                        230,
                        230,
                        250,
                        1
                    ],
                    lavenderblush: [
                        255,
                        240,
                        245,
                        1
                    ],
                    lawngreen: [
                        124,
                        252,
                        0,
                        1
                    ],
                    lemonchiffon: [
                        255,
                        250,
                        205,
                        1
                    ],
                    lightblue: [
                        173,
                        216,
                        230,
                        1
                    ],
                    lightcoral: [
                        240,
                        128,
                        128,
                        1
                    ],
                    lightcyan: [
                        224,
                        255,
                        255,
                        1
                    ],
                    lightgoldenrodyellow: [
                        250,
                        250,
                        210,
                        1
                    ],
                    lightgray: [
                        211,
                        211,
                        211,
                        1
                    ],
                    lightgreen: [
                        144,
                        238,
                        144,
                        1
                    ],
                    lightgrey: [
                        211,
                        211,
                        211,
                        1
                    ],
                    lightpink: [
                        255,
                        182,
                        193,
                        1
                    ],
                    lightsalmon: [
                        255,
                        160,
                        122,
                        1
                    ],
                    lightseagreen: [
                        32,
                        178,
                        170,
                        1
                    ],
                    lightskyblue: [
                        135,
                        206,
                        250,
                        1
                    ],
                    lightslategray: [
                        119,
                        136,
                        153,
                        1
                    ],
                    lightslategrey: [
                        119,
                        136,
                        153,
                        1
                    ],
                    lightsteelblue: [
                        176,
                        196,
                        222,
                        1
                    ],
                    lightyellow: [
                        255,
                        255,
                        224,
                        1
                    ],
                    lime: [
                        0,
                        255,
                        0,
                        1
                    ],
                    limegreen: [
                        50,
                        205,
                        50,
                        1
                    ],
                    linen: [
                        250,
                        240,
                        230,
                        1
                    ],
                    magenta: [
                        255,
                        0,
                        255,
                        1
                    ],
                    maroon: [
                        128,
                        0,
                        0,
                        1
                    ],
                    mediumaquamarine: [
                        102,
                        205,
                        170,
                        1
                    ],
                    mediumblue: [
                        0,
                        0,
                        205,
                        1
                    ],
                    mediumorchid: [
                        186,
                        85,
                        211,
                        1
                    ],
                    mediumpurple: [
                        147,
                        112,
                        219,
                        1
                    ],
                    mediumseagreen: [
                        60,
                        179,
                        113,
                        1
                    ],
                    mediumslateblue: [
                        123,
                        104,
                        238,
                        1
                    ],
                    mediumspringgreen: [
                        0,
                        250,
                        154,
                        1
                    ],
                    mediumturquoise: [
                        72,
                        209,
                        204,
                        1
                    ],
                    mediumvioletred: [
                        199,
                        21,
                        133,
                        1
                    ],
                    midnightblue: [
                        25,
                        25,
                        112,
                        1
                    ],
                    mintcream: [
                        245,
                        255,
                        250,
                        1
                    ],
                    mistyrose: [
                        255,
                        228,
                        225,
                        1
                    ],
                    moccasin: [
                        255,
                        228,
                        181,
                        1
                    ],
                    navajowhite: [
                        255,
                        222,
                        173,
                        1
                    ],
                    navy: [
                        0,
                        0,
                        128,
                        1
                    ],
                    oldlace: [
                        253,
                        245,
                        230,
                        1
                    ],
                    olive: [
                        128,
                        128,
                        0,
                        1
                    ],
                    olivedrab: [
                        107,
                        142,
                        35,
                        1
                    ],
                    orange: [
                        255,
                        165,
                        0,
                        1
                    ],
                    orangered: [
                        255,
                        69,
                        0,
                        1
                    ],
                    orchid: [
                        218,
                        112,
                        214,
                        1
                    ],
                    palegoldenrod: [
                        238,
                        232,
                        170,
                        1
                    ],
                    palegreen: [
                        152,
                        251,
                        152,
                        1
                    ],
                    paleturquoise: [
                        175,
                        238,
                        238,
                        1
                    ],
                    palevioletred: [
                        219,
                        112,
                        147,
                        1
                    ],
                    papayawhip: [
                        255,
                        239,
                        213,
                        1
                    ],
                    peachpuff: [
                        255,
                        218,
                        185,
                        1
                    ],
                    peru: [
                        205,
                        133,
                        63,
                        1
                    ],
                    pink: [
                        255,
                        192,
                        203,
                        1
                    ],
                    plum: [
                        221,
                        160,
                        221,
                        1
                    ],
                    powderblue: [
                        176,
                        224,
                        230,
                        1
                    ],
                    purple: [
                        128,
                        0,
                        128,
                        1
                    ],
                    rebeccapurple: [
                        102,
                        51,
                        153,
                        1
                    ],
                    red: [
                        255,
                        0,
                        0,
                        1
                    ],
                    rosybrown: [
                        188,
                        143,
                        143,
                        1
                    ],
                    royalblue: [
                        65,
                        105,
                        225,
                        1
                    ],
                    saddlebrown: [
                        139,
                        69,
                        19,
                        1
                    ],
                    salmon: [
                        250,
                        128,
                        114,
                        1
                    ],
                    sandybrown: [
                        244,
                        164,
                        96,
                        1
                    ],
                    seagreen: [
                        46,
                        139,
                        87,
                        1
                    ],
                    seashell: [
                        255,
                        245,
                        238,
                        1
                    ],
                    sienna: [
                        160,
                        82,
                        45,
                        1
                    ],
                    silver: [
                        192,
                        192,
                        192,
                        1
                    ],
                    skyblue: [
                        135,
                        206,
                        235,
                        1
                    ],
                    slateblue: [
                        106,
                        90,
                        205,
                        1
                    ],
                    slategray: [
                        112,
                        128,
                        144,
                        1
                    ],
                    slategrey: [
                        112,
                        128,
                        144,
                        1
                    ],
                    snow: [
                        255,
                        250,
                        250,
                        1
                    ],
                    springgreen: [
                        0,
                        255,
                        127,
                        1
                    ],
                    steelblue: [
                        70,
                        130,
                        180,
                        1
                    ],
                    tan: [
                        210,
                        180,
                        140,
                        1
                    ],
                    teal: [
                        0,
                        128,
                        128,
                        1
                    ],
                    thistle: [
                        216,
                        191,
                        216,
                        1
                    ],
                    tomato: [
                        255,
                        99,
                        71,
                        1
                    ],
                    turquoise: [
                        64,
                        224,
                        208,
                        1
                    ],
                    violet: [
                        238,
                        130,
                        238,
                        1
                    ],
                    wheat: [
                        245,
                        222,
                        179,
                        1
                    ],
                    white: [
                        255,
                        255,
                        255,
                        1
                    ],
                    whitesmoke: [
                        245,
                        245,
                        245,
                        1
                    ],
                    yellow: [
                        255,
                        255,
                        0,
                        1
                    ],
                    yellowgreen: [
                        154,
                        205,
                        50,
                        1
                    ]
                };
                try {
                    exports.parseCSSColor = parseCSSColor;
                } catch (e) {
                }
            },
            {}
        ],
        14: [
            function (_dereq_, module, exports) {
                'use strict';
                function earcut(e, n, r) {
                    r = r || 2;
                    var t = n && n.length, i = t ? n[0] * r : e.length, x = linkedList(e, 0, i, r, !0), a = [];
                    if (!x) {
                        return a;
                    }
                    var o, l, u, s, v, f, y;
                    if (t && (x = eliminateHoles(e, n, x, r)), e.length > 80 * r) {
                        o = u = e[0], l = s = e[1];
                        for (var p = r; p < i; p += r) {
                            v = e[p], f = e[p + 1], v < o && (o = v), f < l && (l = f), v > u && (u = v), f > s && (s = f);
                        }
                        y = Math.max(u - o, s - l), y = 0 !== y ? 1 / y : 0;
                    }
                    return earcutLinked(x, a, r, o, l, y), a;
                }
                function linkedList(e, n, r, t, i) {
                    var x, a;
                    if (i === signedArea(e, n, r, t) > 0) {
                        for (x = n; x < r; x += t) {
                            a = insertNode(x, e[x], e[x + 1], a);
                        }
                    } else {
                        for (x = r - t; x >= n; x -= t) {
                            a = insertNode(x, e[x], e[x + 1], a);
                        }
                    }
                    return a && equals(a, a.next) && (removeNode(a), a = a.next), a;
                }
                function filterPoints(e, n) {
                    if (!e) {
                        return e;
                    }
                    n || (n = e);
                    var r, t = e;
                    do {
                        if (r = !1, t.steiner || !equals(t, t.next) && 0 !== area(t.prev, t, t.next)) {
                            t = t.next;
                        } else {
                            if (removeNode(t), (t = n = t.prev) === t.next) {
                                break;
                            }
                            r = !0;
                        }
                    } while (r || t !== n);
                    return n;
                }
                function earcutLinked(e, n, r, t, i, x, a) {
                    if (e) {
                        !a && x && indexCurve(e, t, i, x);
                        for (var o, l, u = e; e.prev !== e.next;) {
                            if (o = e.prev, l = e.next, x ? isEarHashed(e, t, i, x) : isEar(e)) {
                                n.push(o.i / r), n.push(e.i / r), n.push(l.i / r), removeNode(e), e = l.next, u = l.next;
                            } else if ((e = l) === u) {
                                a ? 1 === a ? (e = cureLocalIntersections(e, n, r), earcutLinked(e, n, r, t, i, x, 2)) : 2 === a && splitEarcut(e, n, r, t, i, x) : earcutLinked(filterPoints(e), n, r, t, i, x, 1);
                                break;
                            }
                        }
                    }
                }
                function isEar(e) {
                    var n = e.prev, r = e, t = e.next;
                    if (area(n, r, t) >= 0) {
                        return !1;
                    }
                    for (var i = e.next.next; i !== e.prev;) {
                        if (pointInTriangle(n.x, n.y, r.x, r.y, t.x, t.y, i.x, i.y) && area(i.prev, i, i.next) >= 0) {
                            return !1;
                        }
                        i = i.next;
                    }
                    return !0;
                }
                function isEarHashed(e, n, r, t) {
                    var i = e.prev, x = e, a = e.next;
                    if (area(i, x, a) >= 0) {
                        return !1;
                    }
                    for (var o = i.x < x.x ? i.x < a.x ? i.x : a.x : x.x < a.x ? x.x : a.x, l = i.y < x.y ? i.y < a.y ? i.y : a.y : x.y < a.y ? x.y : a.y, u = i.x > x.x ? i.x > a.x ? i.x : a.x : x.x > a.x ? x.x : a.x, s = i.y > x.y ? i.y > a.y ? i.y : a.y : x.y > a.y ? x.y : a.y, v = zOrder(o, l, n, r, t), f = zOrder(u, s, n, r, t), y = e.prevZ, p = e.nextZ; y && y.z >= v && p && p.z <= f;) {
                        if (y !== e.prev && y !== e.next && pointInTriangle(i.x, i.y, x.x, x.y, a.x, a.y, y.x, y.y) && area(y.prev, y, y.next) >= 0) {
                            return !1;
                        }
                        if (y = y.prevZ, p !== e.prev && p !== e.next && pointInTriangle(i.x, i.y, x.x, x.y, a.x, a.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                            return !1;
                        }
                        p = p.nextZ;
                    }
                    for (; y && y.z >= v;) {
                        if (y !== e.prev && y !== e.next && pointInTriangle(i.x, i.y, x.x, x.y, a.x, a.y, y.x, y.y) && area(y.prev, y, y.next) >= 0) {
                            return !1;
                        }
                        y = y.prevZ;
                    }
                    for (; p && p.z <= f;) {
                        if (p !== e.prev && p !== e.next && pointInTriangle(i.x, i.y, x.x, x.y, a.x, a.y, p.x, p.y) && area(p.prev, p, p.next) >= 0) {
                            return !1;
                        }
                        p = p.nextZ;
                    }
                    return !0;
                }
                function cureLocalIntersections(e, n, r) {
                    var t = e;
                    do {
                        var i = t.prev, x = t.next.next;
                        !equals(i, x) && intersects(i, t, t.next, x) && locallyInside(i, x) && locallyInside(x, i) && (n.push(i.i / r), n.push(t.i / r), n.push(x.i / r), removeNode(t), removeNode(t.next), t = e = x), t = t.next;
                    } while (t !== e);
                    return t;
                }
                function splitEarcut(e, n, r, t, i, x) {
                    var a = e;
                    do {
                        for (var o = a.next.next; o !== a.prev;) {
                            if (a.i !== o.i && isValidDiagonal(a, o)) {
                                var l = splitPolygon(a, o);
                                return a = filterPoints(a, a.next), l = filterPoints(l, l.next), earcutLinked(a, n, r, t, i, x), void earcutLinked(l, n, r, t, i, x);
                            }
                            o = o.next;
                        }
                        a = a.next;
                    } while (a !== e);
                }
                function eliminateHoles(e, n, r, t) {
                    var i, x, a, o, l, u = [];
                    for (i = 0, x = n.length; i < x; i++) {
                        a = n[i] * t, o = i < x - 1 ? n[i + 1] * t : e.length, l = linkedList(e, a, o, t, !1), l === l.next && (l.steiner = !0), u.push(getLeftmost(l));
                    }
                    for (u.sort(compareX), i = 0; i < u.length; i++) {
                        eliminateHole(u[i], r), r = filterPoints(r, r.next);
                    }
                    return r;
                }
                function compareX(e, n) {
                    return e.x - n.x;
                }
                function eliminateHole(e, n) {
                    if (n = findHoleBridge(e, n)) {
                        var r = splitPolygon(n, e);
                        filterPoints(r, r.next);
                    }
                }
                function findHoleBridge(e, n) {
                    var r, t = n, i = e.x, x = e.y, a = -1 / 0;
                    do {
                        if (x <= t.y && x >= t.next.y && t.next.y !== t.y) {
                            var o = t.x + (x - t.y) * (t.next.x - t.x) / (t.next.y - t.y);
                            if (o <= i && o > a) {
                                if (a = o, o === i) {
                                    if (x === t.y) {
                                        return t;
                                    }
                                    if (x === t.next.y) {
                                        return t.next;
                                    }
                                }
                                r = t.x < t.next.x ? t : t.next;
                            }
                        }
                        t = t.next;
                    } while (t !== n);
                    if (!r) {
                        return null;
                    }
                    if (i === a) {
                        return r.prev;
                    }
                    var l, u = r, s = r.x, v = r.y, f = 1 / 0;
                    for (t = r.next; t !== u;) {
                        i >= t.x && t.x >= s && i !== t.x && pointInTriangle(x < v ? i : a, x, s, v, x < v ? a : i, x, t.x, t.y) && ((l = Math.abs(x - t.y) / (i - t.x)) < f || l === f && t.x > r.x) && locallyInside(t, e) && (r = t, f = l), t = t.next;
                    }
                    return r;
                }
                function indexCurve(e, n, r, t) {
                    var i = e;
                    do {
                        null === i.z && (i.z = zOrder(i.x, i.y, n, r, t)), i.prevZ = i.prev, i.nextZ = i.next, i = i.next;
                    } while (i !== e);
                    i.prevZ.nextZ = null, i.prevZ = null, sortLinked(i);
                }
                function sortLinked(e) {
                    var n, r, t, i, x, a, o, l, u = 1;
                    do {
                        for (r = e, e = null, x = null, a = 0; r;) {
                            for (a++, t = r, o = 0, n = 0; n < u && (o++, t = t.nextZ); n++) {
                                ;
                            }
                            for (l = u; o > 0 || l > 0 && t;) {
                                0 !== o && (0 === l || !t || r.z <= t.z) ? (i = r, r = r.nextZ, o--) : (i = t, t = t.nextZ, l--), x ? x.nextZ = i : e = i, i.prevZ = x, x = i;
                            }
                            r = t;
                        }
                        x.nextZ = null, u *= 2;
                    } while (a > 1);
                    return e;
                }
                function zOrder(e, n, r, t, i) {
                    return e = 32767 * (e - r) * i, n = 32767 * (n - t) * i, e = 16711935 & (e | e << 8), e = 252645135 & (e | e << 4), e = 858993459 & (e | e << 2), e = 1431655765 & (e | e << 1), n = 16711935 & (n | n << 8), n = 252645135 & (n | n << 4), n = 858993459 & (n | n << 2), n = 1431655765 & (n | n << 1), e | n << 1;
                }
                function getLeftmost(e) {
                    var n = e, r = e;
                    do {
                        n.x < r.x && (r = n), n = n.next;
                    } while (n !== e);
                    return r;
                }
                function pointInTriangle(e, n, r, t, i, x, a, o) {
                    return (i - a) * (n - o) - (e - a) * (x - o) >= 0 && (e - a) * (t - o) - (r - a) * (n - o) >= 0 && (r - a) * (x - o) - (i - a) * (t - o) >= 0;
                }
                function isValidDiagonal(e, n) {
                    return e.next.i !== n.i && e.prev.i !== n.i && !intersectsPolygon(e, n) && locallyInside(e, n) && locallyInside(n, e) && middleInside(e, n);
                }
                function area(e, n, r) {
                    return (n.y - e.y) * (r.x - n.x) - (n.x - e.x) * (r.y - n.y);
                }
                function equals(e, n) {
                    return e.x === n.x && e.y === n.y;
                }
                function intersects(e, n, r, t) {
                    return !!(equals(e, n) && equals(r, t) || equals(e, t) && equals(r, n)) || area(e, n, r) > 0 != area(e, n, t) > 0 && area(r, t, e) > 0 != area(r, t, n) > 0;
                }
                function intersectsPolygon(e, n) {
                    var r = e;
                    do {
                        if (r.i !== e.i && r.next.i !== e.i && r.i !== n.i && r.next.i !== n.i && intersects(r, r.next, e, n)) {
                            return !0;
                        }
                        r = r.next;
                    } while (r !== e);
                    return !1;
                }
                function locallyInside(e, n) {
                    return area(e.prev, e, e.next) < 0 ? area(e, n, e.next) >= 0 && area(e, e.prev, n) >= 0 : area(e, n, e.prev) < 0 || area(e, e.next, n) < 0;
                }
                function middleInside(e, n) {
                    var r = e, t = !1, i = (e.x + n.x) / 2, x = (e.y + n.y) / 2;
                    do {
                        r.y > x != r.next.y > x && r.next.y !== r.y && i < (r.next.x - r.x) * (x - r.y) / (r.next.y - r.y) + r.x && (t = !t), r = r.next;
                    } while (r !== e);
                    return t;
                }
                function splitPolygon(e, n) {
                    var r = new Node(e.i, e.x, e.y), t = new Node(n.i, n.x, n.y), i = e.next, x = n.prev;
                    return e.next = n, n.prev = e, r.next = i, i.prev = r, t.next = r, r.prev = t, x.next = t, t.prev = x, t;
                }
                function insertNode(e, n, r, t) {
                    var i = new Node(e, n, r);
                    return t ? (i.next = t.next, i.prev = t, t.next.prev = i, t.next = i) : (i.prev = i, i.next = i), i;
                }
                function removeNode(e) {
                    e.next.prev = e.prev, e.prev.next = e.next, e.prevZ && (e.prevZ.nextZ = e.nextZ), e.nextZ && (e.nextZ.prevZ = e.prevZ);
                }
                function Node(e, n, r) {
                    this.i = e, this.x = n, this.y = r, this.prev = null, this.next = null, this.z = null, this.prevZ = null, this.nextZ = null, this.steiner = !1;
                }
                function signedArea(e, n, r, t) {
                    for (var i = 0, x = n, a = r - t; x < r; x += t) {
                        i += (e[a] - e[x]) * (e[x + 1] + e[a + 1]), a = x;
                    }
                    return i;
                }
                module.exports = earcut, module.exports.default = earcut, earcut.deviation = function (e, n, r, t) {
                    var i = n && n.length, x = i ? n[0] * r : e.length, a = Math.abs(signedArea(e, 0, x, r));
                    if (i) {
                        for (var o = 0, l = n.length; o < l; o++) {
                            var u = n[o] * r, s = o < l - 1 ? n[o + 1] * r : e.length;
                            a -= Math.abs(signedArea(e, u, s, r));
                        }
                    }
                    var v = 0;
                    for (o = 0; o < t.length; o += 3) {
                        var f = t[o] * r, y = t[o + 1] * r, p = t[o + 2] * r;
                        v += Math.abs((e[f] - e[p]) * (e[y + 1] - e[f + 1]) - (e[f] - e[y]) * (e[p + 1] - e[f + 1]));
                    }
                    return 0 === a && 0 === v ? 0 : Math.abs((v - a) / a);
                }, earcut.flatten = function (e) {
                    for (var n = e[0][0].length, r = {
                                vertices: [],
                                holes: [],
                                dimensions: n
                            }, t = 0, i = 0; i < e.length; i++) {
                        for (var x = 0; x < e[i].length; x++) {
                            for (var a = 0; a < n; a++) {
                                r.vertices.push(e[i][x][a]);
                            }
                        }
                        i > 0 && (t += e[i - 1].length, r.holes.push(t));
                    }
                    return r;
                };
            },
            {}
        ],
        15: [
            function (_dereq_, module, exports) {
                function rewind(r, e) {
                    switch (r && r.type || null) {
                    case 'FeatureCollection':
                        return r.features = r.features.map(curryOuter(rewind, e)), r;
                    case 'Feature':
                        return r.geometry = rewind(r.geometry, e), r;
                    case 'Polygon':
                    case 'MultiPolygon':
                        return correct(r, e);
                    default:
                        return r;
                    }
                }
                function curryOuter(r, e) {
                    return function (n) {
                        return r(n, e);
                    };
                }
                function correct(r, e) {
                    return 'Polygon' === r.type ? r.coordinates = correctRings(r.coordinates, e) : 'MultiPolygon' === r.type && (r.coordinates = r.coordinates.map(curryOuter(correctRings, e))), r;
                }
                function correctRings(r, e) {
                    e = !!e, r[0] = wind(r[0], e);
                    for (var n = 1; n < r.length; n++) {
                        r[n] = wind(r[n], !e);
                    }
                    return r;
                }
                function wind(r, e) {
                    return cw(r) === e ? r : r.reverse();
                }
                function cw(r) {
                    return geojsonArea.ring(r) >= 0;
                }
                var geojsonArea = _dereq_('@mapbox/geojson-area');
                module.exports = rewind;
            },
            { '@mapbox/geojson-area': 1 }
        ],
        16: [
            function (_dereq_, module, exports) {
                'use strict';
                function clip(i, n, e, t, l, r, u) {
                    if (e /= n, t /= n, r >= e && u <= t) {
                        return i;
                    }
                    if (r > t || u < e) {
                        return null;
                    }
                    for (var s = [], o = 0; o < i.length; o++) {
                        var h = i[o], p = h.geometry, c = h.type, a = 0 === l ? h.minX : h.minY, g = 0 === l ? h.maxX : h.maxY;
                        if (a >= e && g <= t) {
                            s.push(h);
                        } else if (!(a > t || g < e)) {
                            var f = [];
                            if ('Point' === c || 'MultiPoint' === c) {
                                clipPoints(p, f, e, t, l);
                            } else if ('LineString' === c) {
                                clipLine(p, f, e, t, l, !1);
                            } else if ('MultiLineString' === c) {
                                clipLines(p, f, e, t, l, !1);
                            } else if ('Polygon' === c) {
                                clipLines(p, f, e, t, l, !0);
                            } else if ('MultiPolygon' === c) {
                                for (var P = 0; P < p.length; P++) {
                                    var L = [];
                                    clipLines(p[P], L, e, t, l, !0), L.length && f.push(L);
                                }
                            }
                            f.length && ('LineString' !== c && 'MultiLineString' !== c || (1 === f.length ? (c = 'LineString', f = f[0]) : c = 'MultiLineString'), 'Point' !== c && 'MultiPoint' !== c || (c = 3 === f.length ? 'Point' : 'MultiPoint'), s.push(createFeature(h.id, c, f, h.tags)));
                        }
                    }
                    return s.length ? s : null;
                }
                function clipPoints(i, n, e, t, l) {
                    for (var r = 0; r < i.length; r += 3) {
                        var u = i[r + l];
                        u >= e && u <= t && (n.push(i[r]), n.push(i[r + 1]), n.push(i[r + 2]));
                    }
                }
                function clipLine(i, n, e, t, l, r) {
                    for (var u = [], s = 0 === l ? intersectX : intersectY, o = 0; o < i.length - 3; o += 3) {
                        var h = i[o], p = i[o + 1], c = i[o + 2], a = i[o + 3], g = i[o + 4], f = 0 === l ? h : p, P = 0 === l ? a : g, L = !1;
                        f < e ? P >= e && s(u, h, p, a, g, e) : f > t ? P <= t && s(u, h, p, a, g, t) : addPoint(u, h, p, c), P < e && f >= e && (s(u, h, p, a, g, e), L = !0), P > t && f <= t && (s(u, h, p, a, g, t), L = !0), !r && L && (u.size = i.size, n.push(u), u = []);
                    }
                    var v = i.length - 3;
                    h = i[v], p = i[v + 1], c = i[v + 2], f = 0 === l ? h : p, f >= e && f <= t && addPoint(u, h, p, c), v = u.length - 3, r && v >= 3 && (u[v] !== u[0] || u[v + 1] !== u[1]) && addPoint(u, u[0], u[1], u[2]), u.length && (u.size = i.size, n.push(u));
                }
                function clipLines(i, n, e, t, l, r) {
                    for (var u = 0; u < i.length; u++) {
                        clipLine(i[u], n, e, t, l, r);
                    }
                }
                function addPoint(i, n, e, t) {
                    i.push(n), i.push(e), i.push(t);
                }
                function intersectX(i, n, e, t, l, r) {
                    i.push(r), i.push(e + (r - n) * (l - e) / (t - n)), i.push(1);
                }
                function intersectY(i, n, e, t, l, r) {
                    i.push(n + (r - e) * (t - n) / (l - e)), i.push(r), i.push(1);
                }
                module.exports = clip;
                var createFeature = _dereq_('./feature');
            },
            { './feature': 18 }
        ],
        17: [
            function (_dereq_, module, exports) {
                'use strict';
                function convert(e, t) {
                    var r = [];
                    if ('FeatureCollection' === e.type) {
                        for (var o = 0; o < e.features.length; o++) {
                            convertFeature(r, e.features[o], t);
                        }
                    } else {
                        'Feature' === e.type ? convertFeature(r, e, t) : convertFeature(r, { geometry: e }, t);
                    }
                    return r;
                }
                function convertFeature(e, t, r) {
                    if (t.geometry) {
                        var o = t.geometry.coordinates, n = t.geometry.type, i = r * r, a = [];
                        if ('Point' === n) {
                            convertPoint(o, a);
                        } else if ('MultiPoint' === n) {
                            for (var u = 0; u < o.length; u++) {
                                convertPoint(o[u], a);
                            }
                        } else if ('LineString' === n) {
                            convertLine(o, a, i, !1);
                        } else if ('MultiLineString' === n) {
                            convertLines(o, a, i, !1);
                        } else if ('Polygon' === n) {
                            convertLines(o, a, i, !0);
                        } else {
                            if ('MultiPolygon' !== n) {
                                if ('GeometryCollection' === n) {
                                    for (u = 0; u < t.geometry.geometries.length; u++) {
                                        convertFeature(e, {
                                            geometry: t.geometry.geometries[u],
                                            properties: t.properties
                                        }, r);
                                    }
                                    return;
                                }
                                throw new Error('Input data is not a valid GeoJSON object.');
                            }
                            for (u = 0; u < o.length; u++) {
                                var s = [];
                                convertLines(o[u], s, i, !0), a.push(s);
                            }
                        }
                        e.push(createFeature(t.id, n, a, t.properties));
                    }
                }
                function convertPoint(e, t) {
                    t.push(projectX(e[0])), t.push(projectY(e[1])), t.push(0);
                }
                function convertLine(e, t, r, o) {
                    for (var n, i, a = 0, u = 0; u < e.length; u++) {
                        var s = projectX(e[u][0]), c = projectY(e[u][1]);
                        t.push(s), t.push(c), t.push(0), u > 0 && (a += o ? (n * c - s * i) / 2 : Math.sqrt(Math.pow(s - n, 2) + Math.pow(c - i, 2))), n = s, i = c;
                    }
                    var p = t.length - 3;
                    t[2] = 1, simplify(t, 0, p, r), t[p + 2] = 1, t.size = Math.abs(a);
                }
                function convertLines(e, t, r, o) {
                    for (var n = 0; n < e.length; n++) {
                        var i = [];
                        convertLine(e[n], i, r, o), t.push(i);
                    }
                }
                function projectX(e) {
                    return e / 360 + 0.5;
                }
                function projectY(e) {
                    var t = Math.sin(e * Math.PI / 180), r = 0.5 - 0.25 * Math.log((1 + t) / (1 - t)) / Math.PI;
                    return r < 0 ? 0 : r > 1 ? 1 : r;
                }
                module.exports = convert;
                var simplify = _dereq_('./simplify'), createFeature = _dereq_('./feature');
            },
            {
                './feature': 18,
                './simplify': 20
            }
        ],
        18: [
            function (_dereq_, module, exports) {
                'use strict';
                function createFeature(e, n, t, i) {
                    var a = {
                        id: e || null,
                        type: n,
                        geometry: t,
                        tags: i,
                        minX: 1 / 0,
                        minY: 1 / 0,
                        maxX: -1 / 0,
                        maxY: -1 / 0
                    };
                    return calcBBox(a), a;
                }
                function calcBBox(e) {
                    var n = e.geometry, t = e.type;
                    if ('Point' === t || 'MultiPoint' === t || 'LineString' === t) {
                        calcLineBBox(e, n);
                    } else if ('Polygon' === t || 'MultiLineString' === t) {
                        for (var i = 0; i < n.length; i++) {
                            calcLineBBox(e, n[i]);
                        }
                    } else if ('MultiPolygon' === t) {
                        for (i = 0; i < n.length; i++) {
                            for (var a = 0; a < n[i].length; a++) {
                                calcLineBBox(e, n[i][a]);
                            }
                        }
                    }
                }
                function calcLineBBox(e, n) {
                    for (var t = 0; t < n.length; t += 3) {
                        e.minX = Math.min(e.minX, n[t]), e.minY = Math.min(e.minY, n[t + 1]), e.maxX = Math.max(e.maxX, n[t]), e.maxY = Math.max(e.maxY, n[t + 1]);
                    }
                }
                module.exports = createFeature;
            },
            {}
        ],
        19: [
            function (_dereq_, module, exports) {
                'use strict';
                function geojsonvt(e, t) {
                    return new GeoJSONVT(e, t);
                }
                function GeoJSONVT(e, t) {
                    t = this.options = extend(Object.create(this.options), t);
                    var o = t.debug;
                    if (o && console.time('preprocess data'), t.maxZoom < 0 || t.maxZoom > 24) {
                        throw new Error('maxZoom should be in the 0-24 range');
                    }
                    var i = 1 << t.maxZoom, n = convert(e, t.tolerance / (i * t.extent));
                    this.tiles = {}, this.tileCoords = [], o && (console.timeEnd('preprocess data'), console.log('index: maxZoom: %d, maxPoints: %d', t.indexMaxZoom, t.indexMaxPoints), console.time('generate tiles'), this.stats = {}, this.total = 0), n = wrap(n, t.buffer / t.extent), n.length && this.splitTile(n, 0, 0, 0), o && (n.length && console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints), console.timeEnd('generate tiles'), console.log('tiles generated:', this.total, JSON.stringify(this.stats)));
                }
                function toID(e, t, o) {
                    return 32 * ((1 << e) * o + t) + e;
                }
                function extend(e, t) {
                    for (var o in t) {
                        e[o] = t[o];
                    }
                    return e;
                }
                module.exports = geojsonvt;
                var convert = _dereq_('./convert'), transform = _dereq_('./transform'), clip = _dereq_('./clip'), wrap = _dereq_('./wrap'), createTile = _dereq_('./tile');
                GeoJSONVT.prototype.options = {
                    maxZoom: 14,
                    indexMaxZoom: 5,
                    indexMaxPoints: 100000,
                    tolerance: 3,
                    extent: 4096,
                    buffer: 64,
                    debug: 0
                }, GeoJSONVT.prototype.splitTile = function (e, t, o, i, n, s, l) {
                    var this$1 = this;
                    for (var r = [
                                e,
                                t,
                                o,
                                i
                            ], a = this.options, u = a.debug; r.length;) {
                        i = r.pop(), o = r.pop(), t = r.pop(), e = r.pop();
                        var m = 1 << t, c = toID(t, o, i), p = this$1.tiles[c], d = t === a.maxZoom ? 0 : a.tolerance / (m * a.extent);
                        if (!p && (u > 1 && console.time('creation'), p = this$1.tiles[c] = createTile(e, m, o, i, d, t === a.maxZoom), this$1.tileCoords.push({
                                z: t,
                                x: o,
                                y: i
                            }), u)) {
                            u > 1 && (console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)', t, o, i, p.numFeatures, p.numPoints, p.numSimplified), console.timeEnd('creation'));
                            var h = 'z' + t;
                            this$1.stats[h] = (this$1.stats[h] || 0) + 1, this$1.total++;
                        }
                        if (p.source = e, n) {
                            if (t === a.maxZoom || t === n) {
                                continue;
                            }
                            var x = 1 << n - t;
                            if (o !== Math.floor(s / x) || i !== Math.floor(l / x)) {
                                continue;
                            }
                        } else if (t === a.indexMaxZoom || p.numPoints <= a.indexMaxPoints) {
                            continue;
                        }
                        if (p.source = null, 0 !== e.length) {
                            u > 1 && console.time('clipping');
                            var f, g, v, Z, T, M, b = 0.5 * a.buffer / a.extent, w = 0.5 - b, Y = 0.5 + b, O = 1 + b;
                            f = g = v = Z = null, T = clip(e, m, o - b, o + Y, 0, p.minX, p.maxX), M = clip(e, m, o + w, o + O, 0, p.minX, p.maxX), e = null, T && (f = clip(T, m, i - b, i + Y, 1, p.minY, p.maxY), g = clip(T, m, i + w, i + O, 1, p.minY, p.maxY), T = null), M && (v = clip(M, m, i - b, i + Y, 1, p.minY, p.maxY), Z = clip(M, m, i + w, i + O, 1, p.minY, p.maxY), M = null), u > 1 && console.timeEnd('clipping'), r.push(f || [], t + 1, 2 * o, 2 * i), r.push(g || [], t + 1, 2 * o, 2 * i + 1), r.push(v || [], t + 1, 2 * o + 1, 2 * i), r.push(Z || [], t + 1, 2 * o + 1, 2 * i + 1);
                        }
                    }
                }, GeoJSONVT.prototype.getTile = function (e, t, o) {
                    var this$1 = this;
                    var i = this.options, n = i.extent, s = i.debug;
                    if (e < 0 || e > 24) {
                        return null;
                    }
                    var l = 1 << e;
                    t = (t % l + l) % l;
                    var r = toID(e, t, o);
                    if (this.tiles[r]) {
                        return transform.tile(this.tiles[r], n);
                    }
                    s > 1 && console.log('drilling down to z%d-%d-%d', e, t, o);
                    for (var a, u = e, m = t, c = o; !a && u > 0;) {
                        u--, m = Math.floor(m / 2), c = Math.floor(c / 2), a = this$1.tiles[toID(u, m, c)];
                    }
                    return a && a.source ? (s > 1 && console.log('found parent tile z%d-%d-%d', u, m, c), s > 1 && console.time('drilling down'), this.splitTile(a.source, u, m, c, e, t, o), s > 1 && console.timeEnd('drilling down'), this.tiles[r] ? transform.tile(this.tiles[r], n) : null) : null;
                };
            },
            {
                './clip': 16,
                './convert': 17,
                './tile': 21,
                './transform': 22,
                './wrap': 23
            }
        ],
        20: [
            function (_dereq_, module, exports) {
                'use strict';
                function simplify(i, t, r, s) {
                    for (var e, f = s, l = i[t], m = i[t + 1], n = i[r], o = i[r + 1], p = t + 3; p < r; p += 3) {
                        var u = getSqSegDist(i[p], i[p + 1], l, m, n, o);
                        u > f && (e = p, f = u);
                    }
                    f > s && (e - t > 3 && simplify(i, t, e, s), i[e + 2] = f, r - e > 3 && simplify(i, e, r, s));
                }
                function getSqSegDist(i, t, r, s, e, f) {
                    var l = e - r, m = f - s;
                    if (0 !== l || 0 !== m) {
                        var n = ((i - r) * l + (t - s) * m) / (l * l + m * m);
                        n > 1 ? (r = e, s = f) : n > 0 && (r += l * n, s += m * n);
                    }
                    return l = i - r, m = t - s, l * l + m * m;
                }
                module.exports = simplify;
            },
            {}
        ],
        21: [
            function (_dereq_, module, exports) {
                'use strict';
                function createTile(n, e, i, t, r, u) {
                    for (var a = {
                                features: [],
                                numPoints: 0,
                                numSimplified: 0,
                                numFeatures: 0,
                                source: null,
                                x: i,
                                y: t,
                                z2: e,
                                transformed: !1,
                                minX: 2,
                                minY: 1,
                                maxX: -1,
                                maxY: 0
                            }, l = 0; l < n.length; l++) {
                        a.numFeatures++, addFeature(a, n[l], r, u);
                        var o = n[l].minX, m = n[l].minY, f = n[l].maxX, s = n[l].maxY;
                        o < a.minX && (a.minX = o), m < a.minY && (a.minY = m), f > a.maxX && (a.maxX = f), s > a.maxY && (a.maxY = s);
                    }
                    return a;
                }
                function addFeature(n, e, i, t) {
                    var r = e.geometry, u = e.type, a = [];
                    if ('Point' === u || 'MultiPoint' === u) {
                        for (var l = 0; l < r.length; l += 3) {
                            a.push(r[l]), a.push(r[l + 1]), n.numPoints++, n.numSimplified++;
                        }
                    } else if ('LineString' === u) {
                        addLine(a, r, n, i, t, !1, !1);
                    } else if ('MultiLineString' === u || 'Polygon' === u) {
                        for (l = 0; l < r.length; l++) {
                            addLine(a, r[l], n, i, t, 'Polygon' === u, 0 === l);
                        }
                    } else if ('MultiPolygon' === u) {
                        for (var o = 0; o < r.length; o++) {
                            var m = r[o];
                            for (l = 0; l < m.length; l++) {
                                addLine(a, m[l], n, i, t, !0, 0 === l);
                            }
                        }
                    }
                    if (a.length) {
                        var f = {
                            geometry: a,
                            type: 'Polygon' === u || 'MultiPolygon' === u ? 3 : 'LineString' === u || 'MultiLineString' === u ? 2 : 1,
                            tags: e.tags || null
                        };
                        null !== e.id && (f.id = e.id), n.features.push(f);
                    }
                }
                function addLine(n, e, i, t, r, u, a) {
                    var l = t * t;
                    if (!r && e.size < (u ? l : t)) {
                        return void (i.numPoints += e.length / 3);
                    }
                    for (var o = [], m = 0; m < e.length; m += 3) {
                        (r || e[m + 2] > l) && (i.numSimplified++, o.push(e[m]), o.push(e[m + 1])), i.numPoints++;
                    }
                    u && rewind(o, a), n.push(o);
                }
                function rewind(n, e) {
                    for (var i = 0, t = 0, r = n.length, u = r - 2; t < r; u = t, t += 2) {
                        i += (n[t] - n[u]) * (n[t + 1] + n[u + 1]);
                    }
                    if (i > 0 === e) {
                        for (t = 0, r = n.length; t < r / 2; t += 2) {
                            var a = n[t], l = n[t + 1];
                            n[t] = n[r - 2 - t], n[t + 1] = n[r - 1 - t], n[r - 2 - t] = a, n[r - 1 - t] = l;
                        }
                    }
                }
                module.exports = createTile;
            },
            {}
        ],
        22: [
            function (_dereq_, module, exports) {
                'use strict';
                function transformTile(r, t) {
                    if (r.transformed) {
                        return r;
                    }
                    var e, o, n, f = r.z2, s = r.x, a = r.y;
                    for (e = 0; e < r.features.length; e++) {
                        var i = r.features[e], u = i.geometry, m = i.type;
                        if (i.geometry = [], 1 === m) {
                            for (o = 0; o < u.length; o += 2) {
                                i.geometry.push(transformPoint(u[o], u[o + 1], t, f, s, a));
                            }
                        } else {
                            for (o = 0; o < u.length; o++) {
                                var h = [];
                                for (n = 0; n < u[o].length; n += 2) {
                                    h.push(transformPoint(u[o][n], u[o][n + 1], t, f, s, a));
                                }
                                i.geometry.push(h);
                            }
                        }
                    }
                    return r.transformed = !0, r;
                }
                function transformPoint(r, t, e, o, n, f) {
                    return [
                        Math.round(e * (r * o - n)),
                        Math.round(e * (t * o - f))
                    ];
                }
                exports.tile = transformTile, exports.point = transformPoint;
            },
            {}
        ],
        23: [
            function (_dereq_, module, exports) {
                'use strict';
                function wrap(e, r) {
                    var t = e, o = clip(e, 1, -1 - r, r, 0, -1, 2), i = clip(e, 1, 1 - r, 2 + r, 0, -1, 2);
                    return (o || i) && (t = clip(e, 1, -r, 1 + r, 0, -1, 2) || [], o && (t = shiftFeatureCoords(o, 1).concat(t)), i && (t = t.concat(shiftFeatureCoords(i, -1)))), t;
                }
                function shiftFeatureCoords(e, r) {
                    for (var t = [], o = 0; o < e.length; o++) {
                        var i, s = e[o], n = s.type;
                        if ('Point' === n || 'MultiPoint' === n || 'LineString' === n) {
                            i = shiftCoords(s.geometry, r);
                        } else if ('MultiLineString' === n || 'Polygon' === n) {
                            i = [];
                            for (var u = 0; u < s.geometry.length; u++) {
                                i.push(shiftCoords(s.geometry[u], r));
                            }
                        } else if ('MultiPolygon' === n) {
                            for (i = [], u = 0; u < s.geometry.length; u++) {
                                for (var a = [], f = 0; f < s.geometry[u].length; f++) {
                                    a.push(shiftCoords(s.geometry[u][f], r));
                                }
                                i.push(a);
                            }
                        }
                        t.push(createFeature(s.id, n, i, s.tags));
                    }
                    return t;
                }
                function shiftCoords(e, r) {
                    var t = [];
                    t.size = e.size;
                    for (var o = 0; o < e.length; o += 3) {
                        t.push(e[o] + r, e[o + 1], e[o + 2]);
                    }
                    return t;
                }
                var clip = _dereq_('./clip'), createFeature = _dereq_('./feature');
                module.exports = wrap;
            },
            {
                './clip': 16,
                './feature': 18
            }
        ],
        24: [
            function (_dereq_, module, exports) {
                'use strict';
                function GridIndex(t, r, e) {
                    var s = this.cells = [];
                    if (t instanceof ArrayBuffer) {
                        this.arrayBuffer = t;
                        var i = new Int32Array(this.arrayBuffer);
                        t = i[0], r = i[1], e = i[2], this.d = r + 2 * e;
                        for (var h = 0; h < this.d * this.d; h++) {
                            var n = i[NUM_PARAMS + h], o = i[NUM_PARAMS + h + 1];
                            s.push(n === o ? null : i.subarray(n, o));
                        }
                        var l = i[NUM_PARAMS + s.length], a = i[NUM_PARAMS + s.length + 1];
                        this.keys = i.subarray(l, a), this.bboxes = i.subarray(a), this.insert = this._insertReadonly;
                    } else {
                        this.d = r + 2 * e;
                        for (var d = 0; d < this.d * this.d; d++) {
                            s.push([]);
                        }
                        this.keys = [], this.bboxes = [];
                    }
                    this.n = r, this.extent = t, this.padding = e, this.scale = r / t, this.uid = 0;
                    var f = e / r * t;
                    this.min = -f, this.max = t + f;
                }
                module.exports = GridIndex;
                var NUM_PARAMS = 3;
                GridIndex.prototype.insert = function (t, r, e, s, i) {
                    this._forEachCell(r, e, s, i, this._insertCell, this.uid++), this.keys.push(t), this.bboxes.push(r), this.bboxes.push(e), this.bboxes.push(s), this.bboxes.push(i);
                }, GridIndex.prototype._insertReadonly = function () {
                    throw 'Cannot insert into a GridIndex created from an ArrayBuffer.';
                }, GridIndex.prototype._insertCell = function (t, r, e, s, i, h) {
                    this.cells[i].push(h);
                }, GridIndex.prototype.query = function (t, r, e, s) {
                    var i = this.min, h = this.max;
                    if (t <= i && r <= i && h <= e && h <= s) {
                        return Array.prototype.slice.call(this.keys);
                    }
                    var n = [], o = {};
                    return this._forEachCell(t, r, e, s, this._queryCell, n, o), n;
                }, GridIndex.prototype._queryCell = function (t, r, e, s, i, h, n) {
                    var o = this.cells[i];
                    if (null !== o) {
                        for (var l = this.keys, a = this.bboxes, d = 0; d < o.length; d++) {
                            var f = o[d];
                            if (void 0 === n[f]) {
                                var u = 4 * f;
                                t <= a[u + 2] && r <= a[u + 3] && e >= a[u + 0] && s >= a[u + 1] ? (n[f] = !0, h.push(l[f])) : n[f] = !1;
                            }
                        }
                    }
                }, GridIndex.prototype._forEachCell = function (t, r, e, s, i, h, n) {
                    var this$1 = this;
                    for (var o = this._convertToCellCoord(t), l = this._convertToCellCoord(r), a = this._convertToCellCoord(e), d = this._convertToCellCoord(s), f = o; f <= a; f++) {
                        for (var u = l; u <= d; u++) {
                            var y = this$1.d * u + f;
                            if (i.call(this$1, t, r, e, s, y, h, n)) {
                                return;
                            }
                        }
                    }
                }, GridIndex.prototype._convertToCellCoord = function (t) {
                    return Math.max(0, Math.min(this.d - 1, Math.floor(t * this.scale) + this.padding));
                }, GridIndex.prototype.toArrayBuffer = function () {
                    var this$1 = this;
                    if (this.arrayBuffer) {
                        return this.arrayBuffer;
                    }
                    for (var t = this.cells, r = NUM_PARAMS + this.cells.length + 1 + 1, e = 0, s = 0; s < this.cells.length; s++) {
                        e += this$1.cells[s].length;
                    }
                    var i = new Int32Array(r + e + this.keys.length + this.bboxes.length);
                    i[0] = this.extent, i[1] = this.n, i[2] = this.padding;
                    for (var h = r, n = 0; n < t.length; n++) {
                        var o = t[n];
                        i[NUM_PARAMS + n] = h, i.set(o, h), h += o.length;
                    }
                    return i[NUM_PARAMS + t.length] = h, i.set(this.keys, h), h += this.keys.length, i[NUM_PARAMS + t.length + 1] = h, i.set(this.bboxes, h), h += this.bboxes.length, i.buffer;
                };
            },
            {}
        ],
        25: [
            function (_dereq_, module, exports) {
                exports.read = function (a, o, t, r, h) {
                    var M, p, w = 8 * h - r - 1, f = (1 << w) - 1, e = f >> 1, i = -7, N = t ? h - 1 : 0, n = t ? -1 : 1, s = a[o + N];
                    for (N += n, M = s & (1 << -i) - 1, s >>= -i, i += w; i > 0; M = 256 * M + a[o + N], N += n, i -= 8) {
                        ;
                    }
                    for (p = M & (1 << -i) - 1, M >>= -i, i += r; i > 0; p = 256 * p + a[o + N], N += n, i -= 8) {
                        ;
                    }
                    if (0 === M) {
                        M = 1 - e;
                    } else {
                        if (M === f) {
                            return p ? NaN : 1 / 0 * (s ? -1 : 1);
                        }
                        p += Math.pow(2, r), M -= e;
                    }
                    return (s ? -1 : 1) * p * Math.pow(2, M - r);
                }, exports.write = function (a, o, t, r, h, M) {
                    var p, w, f, e = 8 * M - h - 1, i = (1 << e) - 1, N = i >> 1, n = 23 === h ? Math.pow(2, -24) - Math.pow(2, -77) : 0, s = r ? 0 : M - 1, u = r ? 1 : -1, l = o < 0 || 0 === o && 1 / o < 0 ? 1 : 0;
                    for (o = Math.abs(o), isNaN(o) || o === 1 / 0 ? (w = isNaN(o) ? 1 : 0, p = i) : (p = Math.floor(Math.log(o) / Math.LN2), o * (f = Math.pow(2, -p)) < 1 && (p--, f *= 2), o += p + N >= 1 ? n / f : n * Math.pow(2, 1 - N), o * f >= 2 && (p++, f /= 2), p + N >= i ? (w = 0, p = i) : p + N >= 1 ? (w = (o * f - 1) * Math.pow(2, h), p += N) : (w = o * Math.pow(2, N - 1) * Math.pow(2, h), p = 0)); h >= 8; a[t + s] = 255 & w, s += u, w /= 256, h -= 8) {
                        ;
                    }
                    for (p = p << h | w, e += h; e > 0; a[t + s] = 255 & p, s += u, p /= 256, e -= 8) {
                        ;
                    }
                    a[t + s - u] |= 128 * l;
                };
            },
            {}
        ],
        26: [
            function (_dereq_, module, exports) {
                'use strict';
                function kdbush(t, i, e, s, n) {
                    return new KDBush(t, i, e, s, n);
                }
                function KDBush(t, i, e, s, n) {
                    var this$1 = this;
                    i = i || defaultGetX, e = e || defaultGetY, n = n || Array, this.nodeSize = s || 64, this.points = t, this.ids = new n(t.length), this.coords = new n(2 * t.length);
                    for (var r = 0; r < t.length; r++) {
                        this$1.ids[r] = r, this$1.coords[2 * r] = i(t[r]), this$1.coords[2 * r + 1] = e(t[r]);
                    }
                    sort(this.ids, this.coords, this.nodeSize, 0, this.ids.length - 1, 0);
                }
                function defaultGetX(t) {
                    return t[0];
                }
                function defaultGetY(t) {
                    return t[1];
                }
                var sort = _dereq_('./sort'), range = _dereq_('./range'), within = _dereq_('./within');
                module.exports = kdbush, KDBush.prototype = {
                    range: function (t, i, e, s) {
                        return range(this.ids, this.coords, t, i, e, s, this.nodeSize);
                    },
                    within: function (t, i, e) {
                        return within(this.ids, this.coords, t, i, e, this.nodeSize);
                    }
                };
            },
            {
                './range': 27,
                './sort': 28,
                './within': 29
            }
        ],
        27: [
            function (_dereq_, module, exports) {
                'use strict';
                function range(p, r, s, u, h, e, o) {
                    for (var a, t, n = [
                                0,
                                p.length - 1,
                                0
                            ], f = []; n.length;) {
                        var l = n.pop(), v = n.pop(), g = n.pop();
                        if (v - g <= o) {
                            for (var i = g; i <= v; i++) {
                                a = r[2 * i], t = r[2 * i + 1], a >= s && a <= h && t >= u && t <= e && f.push(p[i]);
                            }
                        } else {
                            var c = Math.floor((g + v) / 2);
                            a = r[2 * c], t = r[2 * c + 1], a >= s && a <= h && t >= u && t <= e && f.push(p[c]);
                            var d = (l + 1) % 2;
                            (0 === l ? s <= a : u <= t) && (n.push(g), n.push(c - 1), n.push(d)), (0 === l ? h >= a : e >= t) && (n.push(c + 1), n.push(v), n.push(d));
                        }
                    }
                    return f;
                }
                module.exports = range;
            },
            {}
        ],
        28: [
            function (_dereq_, module, exports) {
                'use strict';
                function sortKD(t, a, o, s, r, e) {
                    if (!(r - s <= o)) {
                        var f = Math.floor((s + r) / 2);
                        select(t, a, f, s, r, e % 2), sortKD(t, a, o, s, f - 1, e + 1), sortKD(t, a, o, f + 1, r, e + 1);
                    }
                }
                function select(t, a, o, s, r, e) {
                    for (; r > s;) {
                        if (r - s > 600) {
                            var f = r - s + 1, p = o - s + 1, w = Math.log(f), m = 0.5 * Math.exp(2 * w / 3), n = 0.5 * Math.sqrt(w * m * (f - m) / f) * (p - f / 2 < 0 ? -1 : 1);
                            select(t, a, o, Math.max(s, Math.floor(o - p * m / f + n)), Math.min(r, Math.floor(o + (f - p) * m / f + n)), e);
                        }
                        var c = a[2 * o + e], h = s, i = r;
                        for (swapItem(t, a, s, o), a[2 * r + e] > c && swapItem(t, a, s, r); h < i;) {
                            for (swapItem(t, a, h, i), h++, i--; a[2 * h + e] < c;) {
                                h++;
                            }
                            for (; a[2 * i + e] > c;) {
                                i--;
                            }
                        }
                        a[2 * s + e] === c ? swapItem(t, a, s, i) : (i++, swapItem(t, a, i, r)), i <= o && (s = i + 1), o <= i && (r = i - 1);
                    }
                }
                function swapItem(t, a, o, s) {
                    swap(t, o, s), swap(a, 2 * o, 2 * s), swap(a, 2 * o + 1, 2 * s + 1);
                }
                function swap(t, a, o) {
                    var s = t[a];
                    t[a] = t[o], t[o] = s;
                }
                module.exports = sortKD;
            },
            {}
        ],
        29: [
            function (_dereq_, module, exports) {
                'use strict';
                function within(s, p, r, t, u, h) {
                    for (var i = [
                                0,
                                s.length - 1,
                                0
                            ], o = [], n = u * u; i.length;) {
                        var e = i.pop(), a = i.pop(), f = i.pop();
                        if (a - f <= h) {
                            for (var v = f; v <= a; v++) {
                                sqDist(p[2 * v], p[2 * v + 1], r, t) <= n && o.push(s[v]);
                            }
                        } else {
                            var l = Math.floor((f + a) / 2), c = p[2 * l], q = p[2 * l + 1];
                            sqDist(c, q, r, t) <= n && o.push(s[l]);
                            var D = (e + 1) % 2;
                            (0 === e ? r - u <= c : t - u <= q) && (i.push(f), i.push(l - 1), i.push(D)), (0 === e ? r + u >= c : t + u >= q) && (i.push(l + 1), i.push(a), i.push(D));
                        }
                    }
                    return o;
                }
                function sqDist(s, p, r, t) {
                    var u = s - r, h = p - t;
                    return u * u + h * h;
                }
                module.exports = within;
            },
            {}
        ],
        30: [
            function (_dereq_, module, exports) {
                'use strict';
                function Pbf(t) {
                    this.buf = ArrayBuffer.isView && ArrayBuffer.isView(t) ? t : new Uint8Array(t || 0), this.pos = 0, this.type = 0, this.length = this.buf.length;
                }
                function readVarintRemainder(t, i, e) {
                    var r, s, n = e.buf;
                    if (s = n[e.pos++], r = (112 & s) >> 4, s < 128) {
                        return toNum(t, r, i);
                    }
                    if (s = n[e.pos++], r |= (127 & s) << 3, s < 128) {
                        return toNum(t, r, i);
                    }
                    if (s = n[e.pos++], r |= (127 & s) << 10, s < 128) {
                        return toNum(t, r, i);
                    }
                    if (s = n[e.pos++], r |= (127 & s) << 17, s < 128) {
                        return toNum(t, r, i);
                    }
                    if (s = n[e.pos++], r |= (127 & s) << 24, s < 128) {
                        return toNum(t, r, i);
                    }
                    if (s = n[e.pos++], r |= (1 & s) << 31, s < 128) {
                        return toNum(t, r, i);
                    }
                    throw new Error('Expected varint not more than 10 bytes');
                }
                function readPackedEnd(t) {
                    return t.type === Pbf.Bytes ? t.readVarint() + t.pos : t.pos + 1;
                }
                function toNum(t, i, e) {
                    return e ? 4294967296 * i + (t >>> 0) : 4294967296 * (i >>> 0) + (t >>> 0);
                }
                function writeBigVarint(t, i) {
                    var e, r;
                    if (t >= 0 ? (e = t % 4294967296 | 0, r = t / 4294967296 | 0) : (e = ~(-t % 4294967296), r = ~(-t / 4294967296), 4294967295 ^ e ? e = e + 1 | 0 : (e = 0, r = r + 1 | 0)), t >= 18446744073709552000 || t < -18446744073709552000) {
                        throw new Error('Given varint doesn\'t fit into 10 bytes');
                    }
                    i.realloc(10), writeBigVarintLow(e, r, i), writeBigVarintHigh(r, i);
                }
                function writeBigVarintLow(t, i, e) {
                    e.buf[e.pos++] = 127 & t | 128, t >>>= 7, e.buf[e.pos++] = 127 & t | 128, t >>>= 7, e.buf[e.pos++] = 127 & t | 128, t >>>= 7, e.buf[e.pos++] = 127 & t | 128, t >>>= 7, e.buf[e.pos] = 127 & t;
                }
                function writeBigVarintHigh(t, i) {
                    var e = (7 & t) << 4;
                    i.buf[i.pos++] |= e | ((t >>>= 3) ? 128 : 0), t && (i.buf[i.pos++] = 127 & t | ((t >>>= 7) ? 128 : 0), t && (i.buf[i.pos++] = 127 & t | ((t >>>= 7) ? 128 : 0), t && (i.buf[i.pos++] = 127 & t | ((t >>>= 7) ? 128 : 0), t && (i.buf[i.pos++] = 127 & t | ((t >>>= 7) ? 128 : 0), t && (i.buf[i.pos++] = 127 & t)))));
                }
                function makeRoomForExtraLength(t, i, e) {
                    var r = i <= 16383 ? 1 : i <= 2097151 ? 2 : i <= 268435455 ? 3 : Math.ceil(Math.log(i) / (7 * Math.LN2));
                    e.realloc(r);
                    for (var s = e.pos - 1; s >= t; s--) {
                        e.buf[s + r] = e.buf[s];
                    }
                }
                function writePackedVarint(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeVarint(t[e]);
                    }
                }
                function writePackedSVarint(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeSVarint(t[e]);
                    }
                }
                function writePackedFloat(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeFloat(t[e]);
                    }
                }
                function writePackedDouble(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeDouble(t[e]);
                    }
                }
                function writePackedBoolean(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeBoolean(t[e]);
                    }
                }
                function writePackedFixed32(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeFixed32(t[e]);
                    }
                }
                function writePackedSFixed32(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeSFixed32(t[e]);
                    }
                }
                function writePackedFixed64(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeFixed64(t[e]);
                    }
                }
                function writePackedSFixed64(t, i) {
                    for (var e = 0; e < t.length; e++) {
                        i.writeSFixed64(t[e]);
                    }
                }
                function readUInt32(t, i) {
                    return (t[i] | t[i + 1] << 8 | t[i + 2] << 16) + 16777216 * t[i + 3];
                }
                function writeInt32(t, i, e) {
                    t[e] = i, t[e + 1] = i >>> 8, t[e + 2] = i >>> 16, t[e + 3] = i >>> 24;
                }
                function readInt32(t, i) {
                    return (t[i] | t[i + 1] << 8 | t[i + 2] << 16) + (t[i + 3] << 24);
                }
                function readUtf8(t, i, e) {
                    for (var r = '', s = i; s < e;) {
                        var n = t[s], o = null, a = n > 239 ? 4 : n > 223 ? 3 : n > 191 ? 2 : 1;
                        if (s + a > e) {
                            break;
                        }
                        var h, u, f;
                        1 === a ? n < 128 && (o = n) : 2 === a ? 128 == (192 & (h = t[s + 1])) && (o = (31 & n) << 6 | 63 & h) <= 127 && (o = null) : 3 === a ? (h = t[s + 1], u = t[s + 2], 128 == (192 & h) && 128 == (192 & u) && ((o = (15 & n) << 12 | (63 & h) << 6 | 63 & u) <= 2047 || o >= 55296 && o <= 57343) && (o = null)) : 4 === a && (h = t[s + 1], u = t[s + 2], f = t[s + 3], 128 == (192 & h) && 128 == (192 & u) && 128 == (192 & f) && ((o = (15 & n) << 18 | (63 & h) << 12 | (63 & u) << 6 | 63 & f) <= 65535 || o >= 1114112) && (o = null)), null === o ? (o = 65533, a = 1) : o > 65535 && (o -= 65536, r += String.fromCharCode(o >>> 10 & 1023 | 55296), o = 56320 | 1023 & o), r += String.fromCharCode(o), s += a;
                    }
                    return r;
                }
                function writeUtf8(t, i, e) {
                    for (var r, s, n = 0; n < i.length; n++) {
                        if ((r = i.charCodeAt(n)) > 55295 && r < 57344) {
                            if (!s) {
                                r > 56319 || n + 1 === i.length ? (t[e++] = 239, t[e++] = 191, t[e++] = 189) : s = r;
                                continue;
                            }
                            if (r < 56320) {
                                t[e++] = 239, t[e++] = 191, t[e++] = 189, s = r;
                                continue;
                            }
                            r = s - 55296 << 10 | r - 56320 | 65536, s = null;
                        } else {
                            s && (t[e++] = 239, t[e++] = 191, t[e++] = 189, s = null);
                        }
                        r < 128 ? t[e++] = r : (r < 2048 ? t[e++] = r >> 6 | 192 : (r < 65536 ? t[e++] = r >> 12 | 224 : (t[e++] = r >> 18 | 240, t[e++] = r >> 12 & 63 | 128), t[e++] = r >> 6 & 63 | 128), t[e++] = 63 & r | 128);
                    }
                    return e;
                }
                module.exports = Pbf;
                var ieee754 = _dereq_('ieee754');
                Pbf.Varint = 0, Pbf.Fixed64 = 1, Pbf.Bytes = 2, Pbf.Fixed32 = 5;
                var SHIFT_LEFT_32 = 4294967296, SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;
                Pbf.prototype = {
                    destroy: function () {
                        this.buf = null;
                    },
                    readFields: function (t, i, e) {
                        var this$1 = this;
                        for (e = e || this.length; this.pos < e;) {
                            var r = this$1.readVarint(), s = r >> 3, n = this$1.pos;
                            this$1.type = 7 & r, t(s, i, this$1), this$1.pos === n && this$1.skip(r);
                        }
                        return i;
                    },
                    readMessage: function (t, i) {
                        return this.readFields(t, i, this.readVarint() + this.pos);
                    },
                    readFixed32: function () {
                        var t = readUInt32(this.buf, this.pos);
                        return this.pos += 4, t;
                    },
                    readSFixed32: function () {
                        var t = readInt32(this.buf, this.pos);
                        return this.pos += 4, t;
                    },
                    readFixed64: function () {
                        var t = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
                        return this.pos += 8, t;
                    },
                    readSFixed64: function () {
                        var t = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;
                        return this.pos += 8, t;
                    },
                    readFloat: function () {
                        var t = ieee754.read(this.buf, this.pos, !0, 23, 4);
                        return this.pos += 4, t;
                    },
                    readDouble: function () {
                        var t = ieee754.read(this.buf, this.pos, !0, 52, 8);
                        return this.pos += 8, t;
                    },
                    readVarint: function (t) {
                        var i, e, r = this.buf;
                        return e = r[this.pos++], i = 127 & e, e < 128 ? i : (e = r[this.pos++], i |= (127 & e) << 7, e < 128 ? i : (e = r[this.pos++], i |= (127 & e) << 14, e < 128 ? i : (e = r[this.pos++], i |= (127 & e) << 21, e < 128 ? i : (e = r[this.pos], i |= (15 & e) << 28, readVarintRemainder(i, t, this)))));
                    },
                    readVarint64: function () {
                        return this.readVarint(!0);
                    },
                    readSVarint: function () {
                        var t = this.readVarint();
                        return t % 2 == 1 ? (t + 1) / -2 : t / 2;
                    },
                    readBoolean: function () {
                        return Boolean(this.readVarint());
                    },
                    readString: function () {
                        var t = this.readVarint() + this.pos, i = readUtf8(this.buf, this.pos, t);
                        return this.pos = t, i;
                    },
                    readBytes: function () {
                        var t = this.readVarint() + this.pos, i = this.buf.subarray(this.pos, t);
                        return this.pos = t, i;
                    },
                    readPackedVarint: function (t, i) {
                        var this$1 = this;
                        var e = readPackedEnd(this);
                        for (t = t || []; this.pos < e;) {
                            t.push(this$1.readVarint(i));
                        }
                        return t;
                    },
                    readPackedSVarint: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readSVarint());
                        }
                        return t;
                    },
                    readPackedBoolean: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readBoolean());
                        }
                        return t;
                    },
                    readPackedFloat: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readFloat());
                        }
                        return t;
                    },
                    readPackedDouble: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readDouble());
                        }
                        return t;
                    },
                    readPackedFixed32: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readFixed32());
                        }
                        return t;
                    },
                    readPackedSFixed32: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readSFixed32());
                        }
                        return t;
                    },
                    readPackedFixed64: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readFixed64());
                        }
                        return t;
                    },
                    readPackedSFixed64: function (t) {
                        var this$1 = this;
                        var i = readPackedEnd(this);
                        for (t = t || []; this.pos < i;) {
                            t.push(this$1.readSFixed64());
                        }
                        return t;
                    },
                    skip: function (t) {
                        var i = 7 & t;
                        if (i === Pbf.Varint) {
                            for (; this.buf[this.pos++] > 127;) {
                                ;
                            }
                        } else if (i === Pbf.Bytes) {
                            this.pos = this.readVarint() + this.pos;
                        } else if (i === Pbf.Fixed32) {
                            this.pos += 4;
                        } else {
                            if (i !== Pbf.Fixed64) {
                                throw new Error('Unimplemented type: ' + i);
                            }
                            this.pos += 8;
                        }
                    },
                    writeTag: function (t, i) {
                        this.writeVarint(t << 3 | i);
                    },
                    realloc: function (t) {
                        for (var i = this.length || 16; i < this.pos + t;) {
                            i *= 2;
                        }
                        if (i !== this.length) {
                            var e = new Uint8Array(i);
                            e.set(this.buf), this.buf = e, this.length = i;
                        }
                    },
                    finish: function () {
                        return this.length = this.pos, this.pos = 0, this.buf.subarray(0, this.length);
                    },
                    writeFixed32: function (t) {
                        this.realloc(4), writeInt32(this.buf, t, this.pos), this.pos += 4;
                    },
                    writeSFixed32: function (t) {
                        this.realloc(4), writeInt32(this.buf, t, this.pos), this.pos += 4;
                    },
                    writeFixed64: function (t) {
                        this.realloc(8), writeInt32(this.buf, -1 & t, this.pos), writeInt32(this.buf, Math.floor(t * SHIFT_RIGHT_32), this.pos + 4), this.pos += 8;
                    },
                    writeSFixed64: function (t) {
                        this.realloc(8), writeInt32(this.buf, -1 & t, this.pos), writeInt32(this.buf, Math.floor(t * SHIFT_RIGHT_32), this.pos + 4), this.pos += 8;
                    },
                    writeVarint: function (t) {
                        if ((t = +t || 0) > 268435455 || t < 0) {
                            return void writeBigVarint(t, this);
                        }
                        this.realloc(4), this.buf[this.pos++] = 127 & t | (t > 127 ? 128 : 0), t <= 127 || (this.buf[this.pos++] = 127 & (t >>>= 7) | (t > 127 ? 128 : 0), t <= 127 || (this.buf[this.pos++] = 127 & (t >>>= 7) | (t > 127 ? 128 : 0), t <= 127 || (this.buf[this.pos++] = t >>> 7 & 127)));
                    },
                    writeSVarint: function (t) {
                        this.writeVarint(t < 0 ? 2 * -t - 1 : 2 * t);
                    },
                    writeBoolean: function (t) {
                        this.writeVarint(Boolean(t));
                    },
                    writeString: function (t) {
                        t = String(t), this.realloc(4 * t.length), this.pos++;
                        var i = this.pos;
                        this.pos = writeUtf8(this.buf, t, this.pos);
                        var e = this.pos - i;
                        e >= 128 && makeRoomForExtraLength(i, e, this), this.pos = i - 1, this.writeVarint(e), this.pos += e;
                    },
                    writeFloat: function (t) {
                        this.realloc(4), ieee754.write(this.buf, t, this.pos, !0, 23, 4), this.pos += 4;
                    },
                    writeDouble: function (t) {
                        this.realloc(8), ieee754.write(this.buf, t, this.pos, !0, 52, 8), this.pos += 8;
                    },
                    writeBytes: function (t) {
                        var this$1 = this;
                        var i = t.length;
                        this.writeVarint(i), this.realloc(i);
                        for (var e = 0; e < i; e++) {
                            this$1.buf[this$1.pos++] = t[e];
                        }
                    },
                    writeRawMessage: function (t, i) {
                        this.pos++;
                        var e = this.pos;
                        t(i, this);
                        var r = this.pos - e;
                        r >= 128 && makeRoomForExtraLength(e, r, this), this.pos = e - 1, this.writeVarint(r), this.pos += r;
                    },
                    writeMessage: function (t, i, e) {
                        this.writeTag(t, Pbf.Bytes), this.writeRawMessage(i, e);
                    },
                    writePackedVarint: function (t, i) {
                        this.writeMessage(t, writePackedVarint, i);
                    },
                    writePackedSVarint: function (t, i) {
                        this.writeMessage(t, writePackedSVarint, i);
                    },
                    writePackedBoolean: function (t, i) {
                        this.writeMessage(t, writePackedBoolean, i);
                    },
                    writePackedFloat: function (t, i) {
                        this.writeMessage(t, writePackedFloat, i);
                    },
                    writePackedDouble: function (t, i) {
                        this.writeMessage(t, writePackedDouble, i);
                    },
                    writePackedFixed32: function (t, i) {
                        this.writeMessage(t, writePackedFixed32, i);
                    },
                    writePackedSFixed32: function (t, i) {
                        this.writeMessage(t, writePackedSFixed32, i);
                    },
                    writePackedFixed64: function (t, i) {
                        this.writeMessage(t, writePackedFixed64, i);
                    },
                    writePackedSFixed64: function (t, i) {
                        this.writeMessage(t, writePackedSFixed64, i);
                    },
                    writeBytesField: function (t, i) {
                        this.writeTag(t, Pbf.Bytes), this.writeBytes(i);
                    },
                    writeFixed32Field: function (t, i) {
                        this.writeTag(t, Pbf.Fixed32), this.writeFixed32(i);
                    },
                    writeSFixed32Field: function (t, i) {
                        this.writeTag(t, Pbf.Fixed32), this.writeSFixed32(i);
                    },
                    writeFixed64Field: function (t, i) {
                        this.writeTag(t, Pbf.Fixed64), this.writeFixed64(i);
                    },
                    writeSFixed64Field: function (t, i) {
                        this.writeTag(t, Pbf.Fixed64), this.writeSFixed64(i);
                    },
                    writeVarintField: function (t, i) {
                        this.writeTag(t, Pbf.Varint), this.writeVarint(i);
                    },
                    writeSVarintField: function (t, i) {
                        this.writeTag(t, Pbf.Varint), this.writeSVarint(i);
                    },
                    writeStringField: function (t, i) {
                        this.writeTag(t, Pbf.Bytes), this.writeString(i);
                    },
                    writeFloatField: function (t, i) {
                        this.writeTag(t, Pbf.Fixed32), this.writeFloat(i);
                    },
                    writeDoubleField: function (t, i) {
                        this.writeTag(t, Pbf.Fixed64), this.writeDouble(i);
                    },
                    writeBooleanField: function (t, i) {
                        this.writeVarintField(t, Boolean(i));
                    }
                };
            },
            { 'ieee754': 25 }
        ],
        31: [
            function (_dereq_, module, exports) {
                'use strict';
                function partialSort(a, t, r, o, p) {
                    for (r = r || 0, o = o || a.length - 1, p = p || defaultCompare; o > r;) {
                        if (o - r > 600) {
                            var f = o - r + 1, e = t - r + 1, l = Math.log(f), s = 0.5 * Math.exp(2 * l / 3), i = 0.5 * Math.sqrt(l * s * (f - s) / f) * (e - f / 2 < 0 ? -1 : 1);
                            partialSort(a, t, Math.max(r, Math.floor(t - e * s / f + i)), Math.min(o, Math.floor(t + (f - e) * s / f + i)), p);
                        }
                        var n = a[t], h = r, u = o;
                        for (swap(a, r, t), p(a[o], n) > 0 && swap(a, r, o); h < u;) {
                            for (swap(a, h, u), h++, u--; p(a[h], n) < 0;) {
                                h++;
                            }
                            for (; p(a[u], n) > 0;) {
                                u--;
                            }
                        }
                        0 === p(a[r], n) ? swap(a, r, u) : (u++, swap(a, u, o)), u <= t && (r = u + 1), t <= u && (o = u - 1);
                    }
                }
                function swap(a, t, r) {
                    var o = a[t];
                    a[t] = a[r], a[r] = o;
                }
                function defaultCompare(a, t) {
                    return a < t ? -1 : a > t ? 1 : 0;
                }
                module.exports = partialSort;
            },
            {}
        ],
        32: [
            function (_dereq_, module, exports) {
                'use strict';
                function supercluster(t) {
                    return new SuperCluster(t);
                }
                function SuperCluster(t) {
                    this.options = extend(Object.create(this.options), t), this.trees = new Array(this.options.maxZoom + 1);
                }
                function createCluster(t, e, n, o, i) {
                    return {
                        x: t,
                        y: e,
                        zoom: 1 / 0,
                        id: o,
                        properties: i,
                        parentId: -1,
                        numPoints: n
                    };
                }
                function createPointCluster(t, e) {
                    var n = t.geometry.coordinates;
                    return {
                        x: lngX(n[0]),
                        y: latY(n[1]),
                        zoom: 1 / 0,
                        id: e,
                        parentId: -1
                    };
                }
                function getClusterJSON(t) {
                    return {
                        type: 'Feature',
                        properties: getClusterProperties(t),
                        geometry: {
                            type: 'Point',
                            coordinates: [
                                xLng(t.x),
                                yLat(t.y)
                            ]
                        }
                    };
                }
                function getClusterProperties(t) {
                    var e = t.numPoints, n = e >= 10000 ? Math.round(e / 1000) + 'k' : e >= 1000 ? Math.round(e / 100) / 10 + 'k' : e;
                    return extend(extend({}, t.properties), {
                        cluster: !0,
                        cluster_id: t.id,
                        point_count: e,
                        point_count_abbreviated: n
                    });
                }
                function lngX(t) {
                    return t / 360 + 0.5;
                }
                function latY(t) {
                    var e = Math.sin(t * Math.PI / 180), n = 0.5 - 0.25 * Math.log((1 + e) / (1 - e)) / Math.PI;
                    return n < 0 ? 0 : n > 1 ? 1 : n;
                }
                function xLng(t) {
                    return 360 * (t - 0.5);
                }
                function yLat(t) {
                    var e = (180 - 360 * t) * Math.PI / 180;
                    return 360 * Math.atan(Math.exp(e)) / Math.PI - 90;
                }
                function extend(t, e) {
                    for (var n in e) {
                        t[n] = e[n];
                    }
                    return t;
                }
                function getX(t) {
                    return t.x;
                }
                function getY(t) {
                    return t.y;
                }
                var kdbush = _dereq_('kdbush');
                module.exports = supercluster, SuperCluster.prototype = {
                    options: {
                        minZoom: 0,
                        maxZoom: 16,
                        radius: 40,
                        extent: 512,
                        nodeSize: 64,
                        log: !1,
                        reduce: null,
                        initial: function () {
                            return {};
                        },
                        map: function (t) {
                            return t;
                        }
                    },
                    load: function (t) {
                        var this$1 = this;
                        var e = this.options.log;
                        e && console.time('total time');
                        var n = 'prepare ' + t.length + ' points';
                        e && console.time(n), this.points = t;
                        var o = t.map(createPointCluster);
                        e && console.timeEnd(n);
                        for (var i = this.options.maxZoom; i >= this.options.minZoom; i--) {
                            var r = +Date.now();
                            this$1.trees[i + 1] = kdbush(o, getX, getY, this$1.options.nodeSize, Float32Array), o = this$1._cluster(o, i), e && console.log('z%d: %d clusters in %dms', i, o.length, +Date.now() - r);
                        }
                        return this.trees[this.options.minZoom] = kdbush(o, getX, getY, this.options.nodeSize, Float32Array), e && console.timeEnd('total time'), this;
                    },
                    getClusters: function (t, e) {
                        var this$1 = this;
                        for (var n = this.trees[this._limitZoom(e)], o = n.range(lngX(t[0]), latY(t[3]), lngX(t[2]), latY(t[1])), i = [], r = 0; r < o.length; r++) {
                            var s = n.points[o[r]];
                            i.push(s.numPoints ? getClusterJSON(s) : this$1.points[s.id]);
                        }
                        return i;
                    },
                    getChildren: function (t, e) {
                        var this$1 = this;
                        for (var n = this.trees[e + 1].points[t], o = this.options.radius / (this.options.extent * Math.pow(2, e)), i = this.trees[e + 1].within(n.x, n.y, o), r = [], s = 0; s < i.length; s++) {
                            var u = this$1.trees[e + 1].points[i[s]];
                            u.parentId === t && r.push(u.numPoints ? getClusterJSON(u) : this$1.points[u.id]);
                        }
                        return r;
                    },
                    getLeaves: function (t, e, n, o) {
                        n = n || 10, o = o || 0;
                        var i = [];
                        return this._appendLeaves(i, t, e, n, o, 0), i;
                    },
                    getTile: function (t, e, n) {
                        var o = this.trees[this._limitZoom(t)], i = Math.pow(2, t), r = this.options.extent, s = this.options.radius, u = s / r, a = (n - u) / i, p = (n + 1 + u) / i, h = { features: [] };
                        return this._addTileFeatures(o.range((e - u) / i, a, (e + 1 + u) / i, p), o.points, e, n, i, h), 0 === e && this._addTileFeatures(o.range(1 - u / i, a, 1, p), o.points, i, n, i, h), e === i - 1 && this._addTileFeatures(o.range(0, a, u / i, p), o.points, -1, n, i, h), h.features.length ? h : null;
                    },
                    getClusterExpansionZoom: function (t, e) {
                        var this$1 = this;
                        for (; e < this.options.maxZoom;) {
                            var n = this$1.getChildren(t, e);
                            if (e++, 1 !== n.length) {
                                break;
                            }
                            t = n[0].properties.cluster_id;
                        }
                        return e;
                    },
                    _appendLeaves: function (t, e, n, o, i, r) {
                        var this$1 = this;
                        for (var s = this.getChildren(e, n), u = 0; u < s.length; u++) {
                            var a = s[u].properties;
                            if (a.cluster ? r + a.point_count <= i ? r += a.point_count : r = this$1._appendLeaves(t, a.cluster_id, n + 1, o, i, r) : r < i ? r++ : t.push(s[u]), t.length === o) {
                                break;
                            }
                        }
                        return r;
                    },
                    _addTileFeatures: function (t, e, n, o, i, r) {
                        var this$1 = this;
                        for (var s = 0; s < t.length; s++) {
                            var u = e[t[s]];
                            r.features.push({
                                type: 1,
                                geometry: [[
                                        Math.round(this$1.options.extent * (u.x * i - n)),
                                        Math.round(this$1.options.extent * (u.y * i - o))
                                    ]],
                                tags: u.numPoints ? getClusterProperties(u) : this$1.points[u.id].properties
                            });
                        }
                    },
                    _limitZoom: function (t) {
                        return Math.max(this.options.minZoom, Math.min(t, this.options.maxZoom + 1));
                    },
                    _cluster: function (t, e) {
                        var this$1 = this;
                        for (var n = [], o = this.options.radius / (this.options.extent * Math.pow(2, e)), i = 0; i < t.length; i++) {
                            var r = t[i];
                            if (!(r.zoom <= e)) {
                                r.zoom = e;
                                var s = this$1.trees[e + 1], u = s.within(r.x, r.y, o), a = r.numPoints || 1, p = r.x * a, h = r.y * a, l = null;
                                this$1.options.reduce && (l = this$1.options.initial(), this$1._accumulate(l, r));
                                for (var c = 0; c < u.length; c++) {
                                    var d = s.points[u[c]];
                                    if (e < d.zoom) {
                                        var m = d.numPoints || 1;
                                        d.zoom = e, p += d.x * m, h += d.y * m, a += m, d.parentId = i, this$1.options.reduce && this$1._accumulate(l, d);
                                    }
                                }
                                1 === a ? n.push(r) : (r.parentId = i, n.push(createCluster(p / a, h / a, a, i, l)));
                            }
                        }
                        return n;
                    },
                    _accumulate: function (t, e) {
                        var n = e.numPoints ? e.properties : this.options.map(this.points[e.id].properties);
                        this.options.reduce(t, n);
                    }
                };
            },
            { 'kdbush': 26 }
        ],
        33: [
            function (_dereq_, module, exports) {
                'use strict';
                function TinyQueue(t, i) {
                    var this$1 = this;
                    if (!(this instanceof TinyQueue)) {
                        return new TinyQueue(t, i);
                    }
                    if (this.data = t || [], this.length = this.data.length, this.compare = i || defaultCompare, this.length > 0) {
                        for (var e = this.length >> 1; e >= 0; e--) {
                            this$1._down(e);
                        }
                    }
                }
                function defaultCompare(t, i) {
                    return t < i ? -1 : t > i ? 1 : 0;
                }
                module.exports = TinyQueue, TinyQueue.prototype = {
                    push: function (t) {
                        this.data.push(t), this.length++, this._up(this.length - 1);
                    },
                    pop: function () {
                        if (0 !== this.length) {
                            var t = this.data[0];
                            return this.length--, this.length > 0 && (this.data[0] = this.data[this.length], this._down(0)), this.data.pop(), t;
                        }
                    },
                    peek: function () {
                        return this.data[0];
                    },
                    _up: function (t) {
                        for (var i = this.data, e = this.compare, h = i[t]; t > 0;) {
                            var n = t - 1 >> 1, a = i[n];
                            if (e(h, a) >= 0) {
                                break;
                            }
                            i[t] = a, t = n;
                        }
                        i[t] = h;
                    },
                    _down: function (t) {
                        for (var i = this.data, e = this.compare, h = this.length, n = h >> 1, a = i[t]; t < n;) {
                            var s = 1 + (t << 1), u = s + 1, r = i[s];
                            if (u < h && e(i[u], r) < 0 && (s = u, r = i[u]), e(r, a) >= 0) {
                                break;
                            }
                            i[t] = r, t = s;
                        }
                        i[t] = a;
                    }
                };
            },
            {}
        ],
        34: [
            function (_dereq_, module, exports) {
                function fromVectorTileJs(e) {
                    var r = new Pbf();
                    return writeTile(e, r), r.finish();
                }
                function fromGeojsonVt(e) {
                    var r = {};
                    for (var t in e) {
                        r[t] = new GeoJSONWrapper(e[t].features), r[t].name = t;
                    }
                    return fromVectorTileJs({ layers: r });
                }
                function writeTile(e, r) {
                    for (var t in e.layers) {
                        r.writeMessage(3, writeLayer, e.layers[t]);
                    }
                }
                function writeLayer(e, r) {
                    r.writeVarintField(15, e.version || 1), r.writeStringField(1, e.name || ''), r.writeVarintField(5, e.extent || 4096);
                    var t, i = {
                            keys: [],
                            values: [],
                            keycache: {},
                            valuecache: {}
                        };
                    for (t = 0; t < e.length; t++) {
                        i.feature = e.feature(t), r.writeMessage(2, writeFeature, i);
                    }
                    var a = i.keys;
                    for (t = 0; t < a.length; t++) {
                        r.writeStringField(3, a[t]);
                    }
                    var o = i.values;
                    for (t = 0; t < o.length; t++) {
                        r.writeMessage(4, writeValue, o[t]);
                    }
                }
                function writeFeature(e, r) {
                    var t = e.feature;
                    void 0 !== t.id && r.writeVarintField(1, t.id), r.writeMessage(2, writeProperties, e), r.writeVarintField(3, t.type), r.writeMessage(4, writeGeometry, t);
                }
                function writeProperties(e, r) {
                    var t = e.feature, i = e.keys, a = e.values, o = e.keycache, n = e.valuecache;
                    for (var l in t.properties) {
                        var s = o[l];
                        void 0 === s && (i.push(l), s = i.length - 1, o[l] = s), r.writeVarint(s);
                        var u = t.properties[l], f = typeof u;
                        'string' !== f && 'boolean' !== f && 'number' !== f && (u = JSON.stringify(u));
                        var w = f + ':' + u, v = n[w];
                        void 0 === v && (a.push(u), v = a.length - 1, n[w] = v), r.writeVarint(v);
                    }
                }
                function command(e, r) {
                    return (r << 3) + (7 & e);
                }
                function zigzag(e) {
                    return e << 1 ^ e >> 31;
                }
                function writeGeometry(e, r) {
                    for (var t = e.loadGeometry(), i = e.type, a = 0, o = 0, n = t.length, l = 0; l < n; l++) {
                        var s = t[l], u = 1;
                        1 === i && (u = s.length), r.writeVarint(command(1, u));
                        for (var f = 0; f < s.length; f++) {
                            1 === f && 1 !== i && r.writeVarint(command(2, s.length - 1));
                            var w = s[f].x - a, v = s[f].y - o;
                            r.writeVarint(zigzag(w)), r.writeVarint(zigzag(v)), a += w, o += v;
                        }
                    }
                }
                function writeValue(e, r) {
                    var t = typeof e;
                    'string' === t ? r.writeStringField(1, e) : 'boolean' === t ? r.writeBooleanField(7, e) : 'number' === t && (e % 1 != 0 ? r.writeDoubleField(3, e) : e < 0 ? r.writeSVarintField(6, e) : r.writeVarintField(5, e));
                }
                var Pbf = _dereq_('pbf'), GeoJSONWrapper = _dereq_('./lib/geojson_wrapper');
                module.exports = fromVectorTileJs, module.exports.fromVectorTileJs = fromVectorTileJs, module.exports.fromGeojsonVt = fromGeojsonVt, module.exports.GeoJSONWrapper = GeoJSONWrapper;
            },
            {
                './lib/geojson_wrapper': 35,
                'pbf': 30
            }
        ],
        35: [
            function (_dereq_, module, exports) {
                'use strict';
                function GeoJSONWrapper(e) {
                    this.features = e, this.length = e.length;
                }
                function FeatureWrapper(e) {
                    this.id = 'number' == typeof e.id ? e.id : void 0, this.type = e.type, this.rawGeometry = 1 === e.type ? [e.geometry] : e.geometry, this.properties = e.tags, this.extent = 4096;
                }
                var Point = _dereq_('@mapbox/point-geometry'), VectorTileFeature = _dereq_('@mapbox/vector-tile').VectorTileFeature;
                module.exports = GeoJSONWrapper, GeoJSONWrapper.prototype.feature = function (e) {
                    return new FeatureWrapper(this.features[e]);
                }, FeatureWrapper.prototype.loadGeometry = function () {
                    var this$1 = this;
                    var e = this.rawGeometry;
                    this.geometry = [];
                    for (var t = 0; t < e.length; t++) {
                        for (var r = e[t], o = [], a = 0; a < r.length; a++) {
                            o.push(new Point(r[a][0], r[a][1]));
                        }
                        this$1.geometry.push(o);
                    }
                    return this.geometry;
                }, FeatureWrapper.prototype.bbox = function () {
                    this.geometry || this.loadGeometry();
                    for (var e = this.geometry, t = 1 / 0, r = -1 / 0, o = 1 / 0, a = -1 / 0, p = 0; p < e.length; p++) {
                        for (var i = e[p], n = 0; n < i.length; n++) {
                            var h = i[n];
                            t = Math.min(t, h.x), r = Math.max(r, h.x), o = Math.min(o, h.y), a = Math.max(a, h.y);
                        }
                    }
                    return [
                        t,
                        o,
                        r,
                        a
                    ];
                }, FeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON;
            },
            {
                '@mapbox/point-geometry': 4,
                '@mapbox/vector-tile': 8
            }
        ],
        36: [
            function (_dereq_, module, exports) {
                var bundleFn = arguments[3], sources = arguments[4], cache = arguments[5], stringify = JSON.stringify;
                module.exports = function (r, e) {
                    function t(r) {
                        d[r] = !0;
                        for (var e in sources[r][1]) {
                            var o = sources[r][1][e];
                            d[o] || t(o);
                        }
                    }
                    for (var o, n = Object.keys(cache), a = 0, i = n.length; a < i; a++) {
                        var s = n[a], u = cache[s].exports;
                        if (u === r || u && u.default === r) {
                            o = s;
                            break;
                        }
                    }
                    if (!o) {
                        o = Math.floor(Math.pow(16, 8) * Math.random()).toString(16);
                        for (var f = {}, a = 0, i = n.length; a < i; a++) {
                            var s = n[a];
                            f[s] = s;
                        }
                        sources[o] = [
                            'function(require,module,exports){' + r + '(self); }',
                            f
                        ];
                    }
                    var c = Math.floor(Math.pow(16, 8) * Math.random()).toString(16), l = {};
                    l[o] = o, sources[c] = [
                        'function(require,module,exports){var f = require(' + stringify(o) + ');(f.default ? f.default : f)(self);}',
                        l
                    ];
                    var d = {};
                    t(c);
                    var g = '(' + bundleFn + ')({' + Object.keys(d).map(function (r) {
                            return stringify(r) + ':[' + sources[r][0] + ',' + stringify(sources[r][1]) + ']';
                        }).join(',') + '},{},[' + stringify(c) + '])', v = window.URL || window.webkitURL || window.mozURL || window.msURL, w = new Blob([g], { type: 'text/javascript' });
                    if (e && e.bare) {
                        return w;
                    }
                    var h = v.createObjectURL(w), m = new Worker(h);
                    return m.objectURL = h, m;
                };
            },
            {}
        ],
        37: [
            function (_dereq_, module, exports) {
                module.exports.RADIUS = 6378137, module.exports.FLATTENING = 1 / 298.257223563, module.exports.POLAR_RADIUS = 6356752.3142;
            },
            {}
        ],
        38: [
            function (_dereq_, module, exports) {
                module.exports = { 'version': '0.44.1' };
            },
            {}
        ],
        39: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/struct_array'), StructArray = ref.StructArray, ref$1 = _dereq_('../util/struct_array'), Struct = ref$1.Struct, ref$2 = _dereq_('../util/web_worker_transfer'), register = ref$2.register, Point = _dereq_('@mapbox/point-geometry'), StructArrayLayout2i4 = function (t) {
                        function r() {
                            t.apply(this, arguments);
                        }
                        return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                            this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
                        }, r.prototype.emplaceBack = function (t, r) {
                            var i = this.length;
                            this.resize(i + 1);
                            var e = 2 * i;
                            return this.int16[e + 0] = t, this.int16[e + 1] = r, i;
                        }, r;
                    }(StructArray);
                StructArrayLayout2i4.prototype.bytesPerElement = 4, register('StructArrayLayout2i4', StructArrayLayout2i4);
                var StructArrayLayout4i8 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e) {
                        var o = this.length;
                        this.resize(o + 1);
                        var u = 4 * o;
                        return this.int16[u + 0] = t, this.int16[u + 1] = r, this.int16[u + 2] = i, this.int16[u + 3] = e, o;
                    }, r;
                }(StructArray);
                StructArrayLayout4i8.prototype.bytesPerElement = 8, register('StructArrayLayout4i8', StructArrayLayout4i8);
                var StructArrayLayout2i4i12 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e, o, u) {
                        var n = this.length;
                        this.resize(n + 1);
                        var a = 6 * n;
                        return this.int16[a + 0] = t, this.int16[a + 1] = r, this.int16[a + 2] = i, this.int16[a + 3] = e, this.int16[a + 4] = o, this.int16[a + 5] = u, n;
                    }, r;
                }(StructArray);
                StructArrayLayout2i4i12.prototype.bytesPerElement = 12, register('StructArrayLayout2i4i12', StructArrayLayout2i4i12);
                var StructArrayLayout4i4ub12 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e, o, u, n, a) {
                        var y = this.length;
                        this.resize(y + 1);
                        var s = 6 * y, c = 12 * y;
                        return this.int16[s + 0] = t, this.int16[s + 1] = r, this.int16[s + 2] = i, this.int16[s + 3] = e, this.uint8[c + 8] = o, this.uint8[c + 9] = u, this.uint8[c + 10] = n, this.uint8[c + 11] = a, y;
                    }, r;
                }(StructArray);
                StructArrayLayout4i4ub12.prototype.bytesPerElement = 12, register('StructArrayLayout4i4ub12', StructArrayLayout4i4ub12);
                var StructArrayLayout4i4ui16 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e, o, u, n, a) {
                        var y = this.length;
                        this.resize(y + 1);
                        var s = 8 * y;
                        return this.int16[s + 0] = t, this.int16[s + 1] = r, this.int16[s + 2] = i, this.int16[s + 3] = e, this.uint16[s + 4] = o, this.uint16[s + 5] = u, this.uint16[s + 6] = n, this.uint16[s + 7] = a, y;
                    }, r;
                }(StructArray);
                StructArrayLayout4i4ui16.prototype.bytesPerElement = 16, register('StructArrayLayout4i4ui16', StructArrayLayout4i4ui16);
                var StructArrayLayout3f12 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i) {
                        var e = this.length;
                        this.resize(e + 1);
                        var o = 3 * e;
                        return this.float32[o + 0] = t, this.float32[o + 1] = r, this.float32[o + 2] = i, e;
                    }, r;
                }(StructArray);
                StructArrayLayout3f12.prototype.bytesPerElement = 12, register('StructArrayLayout3f12', StructArrayLayout3f12);
                var StructArrayLayout1ul4 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t) {
                        var r = this.length;
                        this.resize(r + 1);
                        var i = 1 * r;
                        return this.uint32[i + 0] = t, r;
                    }, r;
                }(StructArray);
                StructArrayLayout1ul4.prototype.bytesPerElement = 4, register('StructArrayLayout1ul4', StructArrayLayout1ul4);
                var StructArrayLayout6i1ul2ui2i24 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e, o, u, n, a, y, s, c) {
                        var p = this.length;
                        this.resize(p + 1);
                        var h = 12 * p, f = 6 * p;
                        return this.int16[h + 0] = t, this.int16[h + 1] = r, this.int16[h + 2] = i, this.int16[h + 3] = e, this.int16[h + 4] = o, this.int16[h + 5] = u, this.uint32[f + 3] = n, this.uint16[h + 8] = a, this.uint16[h + 9] = y, this.int16[h + 10] = s, this.int16[h + 11] = c, p;
                    }, r;
                }(StructArray);
                StructArrayLayout6i1ul2ui2i24.prototype.bytesPerElement = 24, register('StructArrayLayout6i1ul2ui2i24', StructArrayLayout6i1ul2ui2i24);
                var StructArrayLayout2i2i2i12 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e, o, u) {
                        var n = this.length;
                        this.resize(n + 1);
                        var a = 6 * n;
                        return this.int16[a + 0] = t, this.int16[a + 1] = r, this.int16[a + 2] = i, this.int16[a + 3] = e, this.int16[a + 4] = o, this.int16[a + 5] = u, n;
                    }, r;
                }(StructArray);
                StructArrayLayout2i2i2i12.prototype.bytesPerElement = 12, register('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12);
                var StructArrayLayout2ub4 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r) {
                        var i = this.length;
                        this.resize(i + 1);
                        var e = 4 * i;
                        return this.uint8[e + 0] = t, this.uint8[e + 1] = r, i;
                    }, r;
                }(StructArray);
                StructArrayLayout2ub4.prototype.bytesPerElement = 4, register('StructArrayLayout2ub4', StructArrayLayout2ub4);
                var StructArrayLayout2i2ui3ul3ui2f2ub40 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e, o, u, n, a, y, s, c, p, h, f) {
                        var A = this.length;
                        this.resize(A + 1);
                        var _ = 20 * A, l = 10 * A, S = 40 * A;
                        return this.int16[_ + 0] = t, this.int16[_ + 1] = r, this.uint16[_ + 2] = i, this.uint16[_ + 3] = e, this.uint32[l + 2] = o, this.uint32[l + 3] = u, this.uint32[l + 4] = n, this.uint16[_ + 10] = a, this.uint16[_ + 11] = y, this.uint16[_ + 12] = s, this.float32[l + 7] = c, this.float32[l + 8] = p, this.uint8[S + 36] = h, this.uint8[S + 37] = f, A;
                    }, r;
                }(StructArray);
                StructArrayLayout2i2ui3ul3ui2f2ub40.prototype.bytesPerElement = 40, register('StructArrayLayout2i2ui3ul3ui2f2ub40', StructArrayLayout2i2ui3ul3ui2f2ub40);
                var StructArrayLayout1f4 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t) {
                        var r = this.length;
                        this.resize(r + 1);
                        var i = 1 * r;
                        return this.float32[i + 0] = t, r;
                    }, r;
                }(StructArray);
                StructArrayLayout1f4.prototype.bytesPerElement = 4, register('StructArrayLayout1f4', StructArrayLayout1f4);
                var StructArrayLayout3i6 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.int16 = new Int16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i) {
                        var e = this.length;
                        this.resize(e + 1);
                        var o = 3 * e;
                        return this.int16[o + 0] = t, this.int16[o + 1] = r, this.int16[o + 2] = i, e;
                    }, r;
                }(StructArray);
                StructArrayLayout3i6.prototype.bytesPerElement = 6, register('StructArrayLayout3i6', StructArrayLayout3i6);
                var StructArrayLayout1ul2ui8 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.uint32 = new Uint32Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i) {
                        var e = this.length;
                        this.resize(e + 1);
                        var o = 2 * e, u = 4 * e;
                        return this.uint32[o + 0] = t, this.uint16[u + 2] = r, this.uint16[u + 3] = i, e;
                    }, r;
                }(StructArray);
                StructArrayLayout1ul2ui8.prototype.bytesPerElement = 8, register('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8);
                var StructArrayLayout3ui6 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i) {
                        var e = this.length;
                        this.resize(e + 1);
                        var o = 3 * e;
                        return this.uint16[o + 0] = t, this.uint16[o + 1] = r, this.uint16[o + 2] = i, e;
                    }, r;
                }(StructArray);
                StructArrayLayout3ui6.prototype.bytesPerElement = 6, register('StructArrayLayout3ui6', StructArrayLayout3ui6);
                var StructArrayLayout2ui4 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.uint16 = new Uint16Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r) {
                        var i = this.length;
                        this.resize(i + 1);
                        var e = 2 * i;
                        return this.uint16[e + 0] = t, this.uint16[e + 1] = r, i;
                    }, r;
                }(StructArray);
                StructArrayLayout2ui4.prototype.bytesPerElement = 4, register('StructArrayLayout2ui4', StructArrayLayout2ui4);
                var StructArrayLayout2f8 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r) {
                        var i = this.length;
                        this.resize(i + 1);
                        var e = 2 * i;
                        return this.float32[e + 0] = t, this.float32[e + 1] = r, i;
                    }, r;
                }(StructArray);
                StructArrayLayout2f8.prototype.bytesPerElement = 8, register('StructArrayLayout2f8', StructArrayLayout2f8);
                var StructArrayLayout4f16 = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype._refreshViews = function () {
                        this.uint8 = new Uint8Array(this.arrayBuffer), this.float32 = new Float32Array(this.arrayBuffer);
                    }, r.prototype.emplaceBack = function (t, r, i, e) {
                        var o = this.length;
                        this.resize(o + 1);
                        var u = 4 * o;
                        return this.float32[u + 0] = t, this.float32[u + 1] = r, this.float32[u + 2] = i, this.float32[u + 3] = e, o;
                    }, r;
                }(StructArray);
                StructArrayLayout4f16.prototype.bytesPerElement = 16, register('StructArrayLayout4f16', StructArrayLayout4f16);
                var CollisionBoxStruct = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r;
                    var i = {
                        anchorPointX: {},
                        anchorPointY: {},
                        x1: {},
                        y1: {},
                        x2: {},
                        y2: {},
                        featureIndex: {},
                        sourceLayerIndex: {},
                        bucketIndex: {},
                        radius: {},
                        signedDistanceFromAnchor: {},
                        anchorPoint: {}
                    };
                    return i.anchorPointX.get = function () {
                        return this._structArray.int16[this._pos2 + 0];
                    }, i.anchorPointX.set = function (t) {
                        this._structArray.int16[this._pos2 + 0] = t;
                    }, i.anchorPointY.get = function () {
                        return this._structArray.int16[this._pos2 + 1];
                    }, i.anchorPointY.set = function (t) {
                        this._structArray.int16[this._pos2 + 1] = t;
                    }, i.x1.get = function () {
                        return this._structArray.int16[this._pos2 + 2];
                    }, i.x1.set = function (t) {
                        this._structArray.int16[this._pos2 + 2] = t;
                    }, i.y1.get = function () {
                        return this._structArray.int16[this._pos2 + 3];
                    }, i.y1.set = function (t) {
                        this._structArray.int16[this._pos2 + 3] = t;
                    }, i.x2.get = function () {
                        return this._structArray.int16[this._pos2 + 4];
                    }, i.x2.set = function (t) {
                        this._structArray.int16[this._pos2 + 4] = t;
                    }, i.y2.get = function () {
                        return this._structArray.int16[this._pos2 + 5];
                    }, i.y2.set = function (t) {
                        this._structArray.int16[this._pos2 + 5] = t;
                    }, i.featureIndex.get = function () {
                        return this._structArray.uint32[this._pos4 + 3];
                    }, i.featureIndex.set = function (t) {
                        this._structArray.uint32[this._pos4 + 3] = t;
                    }, i.sourceLayerIndex.get = function () {
                        return this._structArray.uint16[this._pos2 + 8];
                    }, i.sourceLayerIndex.set = function (t) {
                        this._structArray.uint16[this._pos2 + 8] = t;
                    }, i.bucketIndex.get = function () {
                        return this._structArray.uint16[this._pos2 + 9];
                    }, i.bucketIndex.set = function (t) {
                        this._structArray.uint16[this._pos2 + 9] = t;
                    }, i.radius.get = function () {
                        return this._structArray.int16[this._pos2 + 10];
                    }, i.radius.set = function (t) {
                        this._structArray.int16[this._pos2 + 10] = t;
                    }, i.signedDistanceFromAnchor.get = function () {
                        return this._structArray.int16[this._pos2 + 11];
                    }, i.signedDistanceFromAnchor.set = function (t) {
                        this._structArray.int16[this._pos2 + 11] = t;
                    }, i.anchorPoint.get = function () {
                        return new Point(this.anchorPointX, this.anchorPointY);
                    }, Object.defineProperties(r.prototype, i), r;
                }(Struct);
                CollisionBoxStruct.prototype.size = 24;
                var CollisionBoxArray = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype.get = function (t) {
                        return new CollisionBoxStruct(this, t);
                    }, r;
                }(StructArrayLayout6i1ul2ui2i24);
                register('CollisionBoxArray', CollisionBoxArray);
                var PlacedSymbolStruct = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r;
                    var i = {
                        anchorX: {},
                        anchorY: {},
                        glyphStartIndex: {},
                        numGlyphs: {},
                        vertexStartIndex: {},
                        lineStartIndex: {},
                        lineLength: {},
                        segment: {},
                        lowerSize: {},
                        upperSize: {},
                        lineOffsetX: {},
                        lineOffsetY: {},
                        writingMode: {},
                        hidden: {}
                    };
                    return i.anchorX.get = function () {
                        return this._structArray.int16[this._pos2 + 0];
                    }, i.anchorX.set = function (t) {
                        this._structArray.int16[this._pos2 + 0] = t;
                    }, i.anchorY.get = function () {
                        return this._structArray.int16[this._pos2 + 1];
                    }, i.anchorY.set = function (t) {
                        this._structArray.int16[this._pos2 + 1] = t;
                    }, i.glyphStartIndex.get = function () {
                        return this._structArray.uint16[this._pos2 + 2];
                    }, i.glyphStartIndex.set = function (t) {
                        this._structArray.uint16[this._pos2 + 2] = t;
                    }, i.numGlyphs.get = function () {
                        return this._structArray.uint16[this._pos2 + 3];
                    }, i.numGlyphs.set = function (t) {
                        this._structArray.uint16[this._pos2 + 3] = t;
                    }, i.vertexStartIndex.get = function () {
                        return this._structArray.uint32[this._pos4 + 2];
                    }, i.vertexStartIndex.set = function (t) {
                        this._structArray.uint32[this._pos4 + 2] = t;
                    }, i.lineStartIndex.get = function () {
                        return this._structArray.uint32[this._pos4 + 3];
                    }, i.lineStartIndex.set = function (t) {
                        this._structArray.uint32[this._pos4 + 3] = t;
                    }, i.lineLength.get = function () {
                        return this._structArray.uint32[this._pos4 + 4];
                    }, i.lineLength.set = function (t) {
                        this._structArray.uint32[this._pos4 + 4] = t;
                    }, i.segment.get = function () {
                        return this._structArray.uint16[this._pos2 + 10];
                    }, i.segment.set = function (t) {
                        this._structArray.uint16[this._pos2 + 10] = t;
                    }, i.lowerSize.get = function () {
                        return this._structArray.uint16[this._pos2 + 11];
                    }, i.lowerSize.set = function (t) {
                        this._structArray.uint16[this._pos2 + 11] = t;
                    }, i.upperSize.get = function () {
                        return this._structArray.uint16[this._pos2 + 12];
                    }, i.upperSize.set = function (t) {
                        this._structArray.uint16[this._pos2 + 12] = t;
                    }, i.lineOffsetX.get = function () {
                        return this._structArray.float32[this._pos4 + 7];
                    }, i.lineOffsetX.set = function (t) {
                        this._structArray.float32[this._pos4 + 7] = t;
                    }, i.lineOffsetY.get = function () {
                        return this._structArray.float32[this._pos4 + 8];
                    }, i.lineOffsetY.set = function (t) {
                        this._structArray.float32[this._pos4 + 8] = t;
                    }, i.writingMode.get = function () {
                        return this._structArray.uint8[this._pos1 + 36];
                    }, i.writingMode.set = function (t) {
                        this._structArray.uint8[this._pos1 + 36] = t;
                    }, i.hidden.get = function () {
                        return this._structArray.uint8[this._pos1 + 37];
                    }, i.hidden.set = function (t) {
                        this._structArray.uint8[this._pos1 + 37] = t;
                    }, Object.defineProperties(r.prototype, i), r;
                }(Struct);
                PlacedSymbolStruct.prototype.size = 40;
                var PlacedSymbolArray = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype.get = function (t) {
                        return new PlacedSymbolStruct(this, t);
                    }, r;
                }(StructArrayLayout2i2ui3ul3ui2f2ub40);
                register('PlacedSymbolArray', PlacedSymbolArray);
                var GlyphOffsetStruct = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r;
                    var i = { offsetX: {} };
                    return i.offsetX.get = function () {
                        return this._structArray.float32[this._pos4 + 0];
                    }, i.offsetX.set = function (t) {
                        this._structArray.float32[this._pos4 + 0] = t;
                    }, Object.defineProperties(r.prototype, i), r;
                }(Struct);
                GlyphOffsetStruct.prototype.size = 4;
                var GlyphOffsetArray = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype.getoffsetX = function (t) {
                        return this.float32[1 * t + 0];
                    }, r.prototype.get = function (t) {
                        return new GlyphOffsetStruct(this, t);
                    }, r;
                }(StructArrayLayout1f4);
                register('GlyphOffsetArray', GlyphOffsetArray);
                var SymbolLineVertexStruct = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r;
                    var i = {
                        x: {},
                        y: {},
                        tileUnitDistanceFromAnchor: {}
                    };
                    return i.x.get = function () {
                        return this._structArray.int16[this._pos2 + 0];
                    }, i.x.set = function (t) {
                        this._structArray.int16[this._pos2 + 0] = t;
                    }, i.y.get = function () {
                        return this._structArray.int16[this._pos2 + 1];
                    }, i.y.set = function (t) {
                        this._structArray.int16[this._pos2 + 1] = t;
                    }, i.tileUnitDistanceFromAnchor.get = function () {
                        return this._structArray.int16[this._pos2 + 2];
                    }, i.tileUnitDistanceFromAnchor.set = function (t) {
                        this._structArray.int16[this._pos2 + 2] = t;
                    }, Object.defineProperties(r.prototype, i), r;
                }(Struct);
                SymbolLineVertexStruct.prototype.size = 6;
                var SymbolLineVertexArray = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype.getx = function (t) {
                        return this.int16[3 * t + 0];
                    }, r.prototype.gety = function (t) {
                        return this.int16[3 * t + 1];
                    }, r.prototype.gettileUnitDistanceFromAnchor = function (t) {
                        return this.int16[3 * t + 2];
                    }, r.prototype.get = function (t) {
                        return new SymbolLineVertexStruct(this, t);
                    }, r;
                }(StructArrayLayout3i6);
                register('SymbolLineVertexArray', SymbolLineVertexArray);
                var FeatureIndexStruct = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r;
                    var i = {
                        featureIndex: {},
                        sourceLayerIndex: {},
                        bucketIndex: {}
                    };
                    return i.featureIndex.get = function () {
                        return this._structArray.uint32[this._pos4 + 0];
                    }, i.featureIndex.set = function (t) {
                        this._structArray.uint32[this._pos4 + 0] = t;
                    }, i.sourceLayerIndex.get = function () {
                        return this._structArray.uint16[this._pos2 + 2];
                    }, i.sourceLayerIndex.set = function (t) {
                        this._structArray.uint16[this._pos2 + 2] = t;
                    }, i.bucketIndex.get = function () {
                        return this._structArray.uint16[this._pos2 + 3];
                    }, i.bucketIndex.set = function (t) {
                        this._structArray.uint16[this._pos2 + 3] = t;
                    }, Object.defineProperties(r.prototype, i), r;
                }(Struct);
                FeatureIndexStruct.prototype.size = 8;
                var FeatureIndexArray = function (t) {
                    function r() {
                        t.apply(this, arguments);
                    }
                    return t && (r.__proto__ = t), r.prototype = Object.create(t && t.prototype), r.prototype.constructor = r, r.prototype.get = function (t) {
                        return new FeatureIndexStruct(this, t);
                    }, r;
                }(StructArrayLayout1ul2ui8);
                register('FeatureIndexArray', FeatureIndexArray), module.exports = {
                    StructArrayLayout2i4: StructArrayLayout2i4,
                    StructArrayLayout4i8: StructArrayLayout4i8,
                    StructArrayLayout2i4i12: StructArrayLayout2i4i12,
                    StructArrayLayout4i4ub12: StructArrayLayout4i4ub12,
                    StructArrayLayout4i4ui16: StructArrayLayout4i4ui16,
                    StructArrayLayout3f12: StructArrayLayout3f12,
                    StructArrayLayout1ul4: StructArrayLayout1ul4,
                    StructArrayLayout6i1ul2ui2i24: StructArrayLayout6i1ul2ui2i24,
                    StructArrayLayout2i2i2i12: StructArrayLayout2i2i2i12,
                    StructArrayLayout2ub4: StructArrayLayout2ub4,
                    StructArrayLayout2i2ui3ul3ui2f2ub40: StructArrayLayout2i2ui3ul3ui2f2ub40,
                    StructArrayLayout1f4: StructArrayLayout1f4,
                    StructArrayLayout3i6: StructArrayLayout3i6,
                    StructArrayLayout1ul2ui8: StructArrayLayout1ul2ui8,
                    StructArrayLayout3ui6: StructArrayLayout3ui6,
                    StructArrayLayout2ui4: StructArrayLayout2ui4,
                    StructArrayLayout2f8: StructArrayLayout2f8,
                    StructArrayLayout4f16: StructArrayLayout4f16,
                    PosArray: StructArrayLayout2i4,
                    RasterBoundsArray: StructArrayLayout4i8,
                    CircleLayoutArray: StructArrayLayout2i4,
                    FillLayoutArray: StructArrayLayout2i4,
                    FillExtrusionLayoutArray: StructArrayLayout2i4i12,
                    HeatmapLayoutArray: StructArrayLayout2i4,
                    LineLayoutArray: StructArrayLayout4i4ub12,
                    SymbolLayoutArray: StructArrayLayout4i4ui16,
                    SymbolDynamicLayoutArray: StructArrayLayout3f12,
                    SymbolOpacityArray: StructArrayLayout1ul4,
                    CollisionBoxLayoutArray: StructArrayLayout2i2i2i12,
                    CollisionCircleLayoutArray: StructArrayLayout2i2i2i12,
                    CollisionVertexArray: StructArrayLayout2ub4,
                    TriangleIndexArray: StructArrayLayout3ui6,
                    LineIndexArray: StructArrayLayout2ui4,
                    CollisionBoxArray: CollisionBoxArray,
                    PlacedSymbolArray: PlacedSymbolArray,
                    GlyphOffsetArray: GlyphOffsetArray,
                    SymbolLineVertexArray: SymbolLineVertexArray,
                    FeatureIndexArray: FeatureIndexArray
                };
            },
            {
                '../util/struct_array': 271,
                '../util/web_worker_transfer': 278,
                '@mapbox/point-geometry': 4
            }
        ],
        40: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = {
                    deserialize: function (r, e) {
                        var t = {};
                        if (!e) {
                            return t;
                        }
                        for (var n = 0, a = r; n < a.length; n += 1) {
                            var i = a[n], l = i.layerIds.map(function (r) {
                                    return e.getLayer(r);
                                }).filter(Boolean);
                            if (0 !== l.length) {
                                i.layers = l;
                                for (var o = 0, f = l; o < f.length; o += 1) {
                                    t[f[o].id] = i;
                                }
                            }
                        }
                        return t;
                    }
                };
            },
            {}
        ],
        41: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../../util/struct_array'), createLayout = ref.createLayout;
                module.exports = createLayout([{
                        name: 'a_pos',
                        components: 2,
                        type: 'Int16'
                    }], 4);
            },
            { '../../util/struct_array': 271 }
        ],
        42: [
            function (_dereq_, module, exports) {
                'use strict';
                function addCircleVertex(e, r, t, a, i) {
                    e.emplaceBack(2 * r + (a + 1) / 2, 2 * t + (i + 1) / 2);
                }
                var ref = _dereq_('../array_types'), CircleLayoutArray = ref.CircleLayoutArray, layoutAttributes = _dereq_('./circle_attributes').members, ref$1 = _dereq_('../segment'), SegmentVector = ref$1.SegmentVector, ref$2 = _dereq_('../program_configuration'), ProgramConfigurationSet = ref$2.ProgramConfigurationSet, ref$3 = _dereq_('../index_array_type'), TriangleIndexArray = ref$3.TriangleIndexArray, loadGeometry = _dereq_('../load_geometry'), EXTENT = _dereq_('../extent'), ref$4 = _dereq_('../../util/web_worker_transfer'), register = ref$4.register, CircleBucket = function (e) {
                        this.zoom = e.zoom, this.overscaling = e.overscaling, this.layers = e.layers, this.layerIds = this.layers.map(function (e) {
                            return e.id;
                        }), this.index = e.index, this.layoutVertexArray = new CircleLayoutArray(), this.indexArray = new TriangleIndexArray(), this.segments = new SegmentVector(), this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, e.layers, e.zoom);
                    };
                CircleBucket.prototype.populate = function (e, r) {
                    for (var t = this, a = 0, i = e; a < i.length; a += 1) {
                        var o = i[a], n = o.feature, u = o.index, s = o.sourceLayerIndex;
                        if (t.layers[0]._featureFilter({ zoom: t.zoom }, n)) {
                            var y = loadGeometry(n);
                            t.addFeature(n, y), r.featureIndex.insert(n, y, u, s, t.index);
                        }
                    }
                }, CircleBucket.prototype.isEmpty = function () {
                    return 0 === this.layoutVertexArray.length;
                }, CircleBucket.prototype.upload = function (e) {
                    this.layoutVertexBuffer = e.createVertexBuffer(this.layoutVertexArray, layoutAttributes), this.indexBuffer = e.createIndexBuffer(this.indexArray), this.programConfigurations.upload(e);
                }, CircleBucket.prototype.destroy = function () {
                    this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy());
                }, CircleBucket.prototype.addFeature = function (e, r) {
                    for (var t = this, a = 0, i = r; a < i.length; a += 1) {
                        for (var o = i[a], n = 0, u = o; n < u.length; n += 1) {
                            var s = u[n], y = s.x, l = s.y;
                            if (!(y < 0 || y >= EXTENT || l < 0 || l >= EXTENT)) {
                                var c = t.segments.prepareSegment(4, t.layoutVertexArray, t.indexArray), f = c.vertexLength;
                                addCircleVertex(t.layoutVertexArray, y, l, -1, -1), addCircleVertex(t.layoutVertexArray, y, l, 1, -1), addCircleVertex(t.layoutVertexArray, y, l, 1, 1), addCircleVertex(t.layoutVertexArray, y, l, -1, 1), t.indexArray.emplaceBack(f, f + 1, f + 2), t.indexArray.emplaceBack(f, f + 3, f + 2), c.vertexLength += 4, c.primitiveLength += 2;
                            }
                        }
                    }
                    this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, e);
                }, register('CircleBucket', CircleBucket, { omit: ['layers'] }), module.exports = CircleBucket;
            },
            {
                '../../util/web_worker_transfer': 278,
                '../array_types': 39,
                '../extent': 53,
                '../index_array_type': 55,
                '../load_geometry': 56,
                '../program_configuration': 58,
                '../segment': 60,
                './circle_attributes': 41
            }
        ],
        43: [
            function (_dereq_, module, exports) {
                arguments[4][41][0].apply(exports, arguments);
            },
            {
                '../../util/struct_array': 271,
                'dup': 41
            }
        ],
        44: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../array_types'), FillLayoutArray = ref.FillLayoutArray, layoutAttributes = _dereq_('./fill_attributes').members, ref$1 = _dereq_('../segment'), SegmentVector = ref$1.SegmentVector, ref$2 = _dereq_('../program_configuration'), ProgramConfigurationSet = ref$2.ProgramConfigurationSet, ref$3 = _dereq_('../index_array_type'), LineIndexArray = ref$3.LineIndexArray, TriangleIndexArray = ref$3.TriangleIndexArray, loadGeometry = _dereq_('../load_geometry'), earcut = _dereq_('earcut'), classifyRings = _dereq_('../../util/classify_rings'), EARCUT_MAX_RINGS = 500, ref$4 = _dereq_('../../util/web_worker_transfer'), register = ref$4.register, FillBucket = function (e) {
                        this.zoom = e.zoom, this.overscaling = e.overscaling, this.layers = e.layers, this.layerIds = this.layers.map(function (e) {
                            return e.id;
                        }), this.index = e.index, this.layoutVertexArray = new FillLayoutArray(), this.indexArray = new TriangleIndexArray(), this.indexArray2 = new LineIndexArray(), this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, e.layers, e.zoom), this.segments = new SegmentVector(), this.segments2 = new SegmentVector();
                    };
                FillBucket.prototype.populate = function (e, r) {
                    for (var t = this, i = 0, a = e; i < a.length; i += 1) {
                        var n = a[i], o = n.feature, s = n.index, u = n.sourceLayerIndex;
                        if (t.layers[0]._featureFilter({ zoom: t.zoom }, o)) {
                            var l = loadGeometry(o);
                            t.addFeature(o, l), r.featureIndex.insert(o, l, s, u, t.index);
                        }
                    }
                }, FillBucket.prototype.isEmpty = function () {
                    return 0 === this.layoutVertexArray.length;
                }, FillBucket.prototype.upload = function (e) {
                    this.layoutVertexBuffer = e.createVertexBuffer(this.layoutVertexArray, layoutAttributes), this.indexBuffer = e.createIndexBuffer(this.indexArray), this.indexBuffer2 = e.createIndexBuffer(this.indexArray2), this.programConfigurations.upload(e);
                }, FillBucket.prototype.destroy = function () {
                    this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.indexBuffer2.destroy(), this.programConfigurations.destroy(), this.segments.destroy(), this.segments2.destroy());
                }, FillBucket.prototype.addFeature = function (e, r) {
                    for (var t = this, i = 0, a = classifyRings(r, EARCUT_MAX_RINGS); i < a.length; i += 1) {
                        for (var n = a[i], o = 0, s = 0, u = n; s < u.length; s += 1) {
                            o += u[s].length;
                        }
                        for (var l = t.segments.prepareSegment(o, t.layoutVertexArray, t.indexArray), y = l.vertexLength, g = [], f = [], h = 0, x = n; h < x.length; h += 1) {
                            var d = x[h];
                            if (0 !== d.length) {
                                d !== n[0] && f.push(g.length / 2);
                                var c = t.segments2.prepareSegment(d.length, t.layoutVertexArray, t.indexArray2), m = c.vertexLength;
                                t.layoutVertexArray.emplaceBack(d[0].x, d[0].y), t.indexArray2.emplaceBack(m + d.length - 1, m), g.push(d[0].x), g.push(d[0].y);
                                for (var p = 1; p < d.length; p++) {
                                    t.layoutVertexArray.emplaceBack(d[p].x, d[p].y), t.indexArray2.emplaceBack(m + p - 1, m + p), g.push(d[p].x), g.push(d[p].y);
                                }
                                c.vertexLength += d.length, c.primitiveLength += d.length;
                            }
                        }
                        for (var A = earcut(g, f), B = 0; B < A.length; B += 3) {
                            t.indexArray.emplaceBack(y + A[B], y + A[B + 1], y + A[B + 2]);
                        }
                        l.vertexLength += o, l.primitiveLength += A.length / 3;
                    }
                    this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, e);
                }, register('FillBucket', FillBucket, { omit: ['layers'] }), module.exports = FillBucket;
            },
            {
                '../../util/classify_rings': 255,
                '../../util/web_worker_transfer': 278,
                '../array_types': 39,
                '../index_array_type': 55,
                '../load_geometry': 56,
                '../program_configuration': 58,
                '../segment': 60,
                './fill_attributes': 43,
                'earcut': 14
            }
        ],
        45: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../../util/struct_array'), createLayout = ref.createLayout;
                module.exports = createLayout([
                    {
                        name: 'a_pos',
                        components: 2,
                        type: 'Int16'
                    },
                    {
                        name: 'a_normal_ed',
                        components: 4,
                        type: 'Int16'
                    }
                ], 4);
            },
            { '../../util/struct_array': 271 }
        ],
        46: [
            function (_dereq_, module, exports) {
                'use strict';
                function addVertex(e, r, t, i, a, n, o, u) {
                    e.emplaceBack(r, t, 2 * Math.floor(i * FACTOR) + o, a * FACTOR * 2, n * FACTOR * 2, Math.round(u));
                }
                function isBoundaryEdge(e, r) {
                    return e.x === r.x && (e.x < 0 || e.x > EXTENT) || e.y === r.y && (e.y < 0 || e.y > EXTENT);
                }
                function isEntirelyOutside(e) {
                    return e.every(function (e) {
                        return e.x < 0;
                    }) || e.every(function (e) {
                        return e.x > EXTENT;
                    }) || e.every(function (e) {
                        return e.y < 0;
                    }) || e.every(function (e) {
                        return e.y > EXTENT;
                    });
                }
                var ref = _dereq_('../array_types'), FillExtrusionLayoutArray = ref.FillExtrusionLayoutArray, layoutAttributes = _dereq_('./fill_extrusion_attributes').members, ref$1 = _dereq_('../segment'), SegmentVector = ref$1.SegmentVector, MAX_VERTEX_ARRAY_LENGTH = ref$1.MAX_VERTEX_ARRAY_LENGTH, ref$2 = _dereq_('../program_configuration'), ProgramConfigurationSet = ref$2.ProgramConfigurationSet, ref$3 = _dereq_('../index_array_type'), TriangleIndexArray = ref$3.TriangleIndexArray, loadGeometry = _dereq_('../load_geometry'), EXTENT = _dereq_('../extent'), earcut = _dereq_('earcut'), classifyRings = _dereq_('../../util/classify_rings'), EARCUT_MAX_RINGS = 500, ref$4 = _dereq_('../../util/web_worker_transfer'), register = ref$4.register, FACTOR = Math.pow(2, 13), FillExtrusionBucket = function (e) {
                        this.zoom = e.zoom, this.overscaling = e.overscaling, this.layers = e.layers, this.layerIds = this.layers.map(function (e) {
                            return e.id;
                        }), this.index = e.index, this.layoutVertexArray = new FillExtrusionLayoutArray(), this.indexArray = new TriangleIndexArray(), this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, e.layers, e.zoom), this.segments = new SegmentVector();
                    };
                FillExtrusionBucket.prototype.populate = function (e, r) {
                    for (var t = this, i = 0, a = e; i < a.length; i += 1) {
                        var n = a[i], o = n.feature, u = n.index, s = n.sourceLayerIndex;
                        if (t.layers[0]._featureFilter({ zoom: t.zoom }, o)) {
                            var y = loadGeometry(o);
                            t.addFeature(o, y), r.featureIndex.insert(o, y, u, s, t.index);
                        }
                    }
                }, FillExtrusionBucket.prototype.isEmpty = function () {
                    return 0 === this.layoutVertexArray.length;
                }, FillExtrusionBucket.prototype.upload = function (e) {
                    this.layoutVertexBuffer = e.createVertexBuffer(this.layoutVertexArray, layoutAttributes), this.indexBuffer = e.createIndexBuffer(this.indexArray), this.programConfigurations.upload(e);
                }, FillExtrusionBucket.prototype.destroy = function () {
                    this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy());
                }, FillExtrusionBucket.prototype.addFeature = function (e, r) {
                    for (var t = this, i = 0, a = classifyRings(r, EARCUT_MAX_RINGS); i < a.length; i += 1) {
                        for (var n = a[i], o = 0, u = 0, s = n; u < s.length; u += 1) {
                            o += s[u].length;
                        }
                        for (var y = t.segments.prepareSegment(4, t.layoutVertexArray, t.indexArray), l = 0, x = n; l < x.length; l += 1) {
                            var f = x[l];
                            if (0 !== f.length && !isEntirelyOutside(f)) {
                                for (var g = 0, d = 0; d < f.length; d++) {
                                    var h = f[d];
                                    if (d >= 1) {
                                        var A = f[d - 1];
                                        if (!isBoundaryEdge(h, A)) {
                                            y.vertexLength + 4 > MAX_VERTEX_ARRAY_LENGTH && (y = t.segments.prepareSegment(4, t.layoutVertexArray, t.indexArray));
                                            var c = h.sub(A)._perp()._unit(), p = A.dist(h);
                                            g + p > 32768 && (g = 0), addVertex(t.layoutVertexArray, h.x, h.y, c.x, c.y, 0, 0, g), addVertex(t.layoutVertexArray, h.x, h.y, c.x, c.y, 0, 1, g), g += p, addVertex(t.layoutVertexArray, A.x, A.y, c.x, c.y, 0, 0, g), addVertex(t.layoutVertexArray, A.x, A.y, c.x, c.y, 0, 1, g);
                                            var E = y.vertexLength;
                                            t.indexArray.emplaceBack(E, E + 1, E + 2), t.indexArray.emplaceBack(E + 1, E + 2, E + 3), y.vertexLength += 4, y.primitiveLength += 2;
                                        }
                                    }
                                }
                            }
                        }
                        y.vertexLength + o > MAX_VERTEX_ARRAY_LENGTH && (y = t.segments.prepareSegment(o, t.layoutVertexArray, t.indexArray));
                        for (var m = [], v = [], V = y.vertexLength, _ = 0, T = n; _ < T.length; _ += 1) {
                            var B = T[_];
                            if (0 !== B.length) {
                                B !== n[0] && v.push(m.length / 2);
                                for (var R = 0; R < B.length; R++) {
                                    var F = B[R];
                                    addVertex(t.layoutVertexArray, F.x, F.y, 0, 0, 1, 1, 0), m.push(F.x), m.push(F.y);
                                }
                            }
                        }
                        for (var L = earcut(m, v), X = 0; X < L.length; X += 3) {
                            t.indexArray.emplaceBack(V + L[X], V + L[X + 1], V + L[X + 2]);
                        }
                        y.primitiveLength += L.length / 3, y.vertexLength += o;
                    }
                    this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, e);
                }, register('FillExtrusionBucket', FillExtrusionBucket, { omit: ['layers'] }), module.exports = FillExtrusionBucket;
            },
            {
                '../../util/classify_rings': 255,
                '../../util/web_worker_transfer': 278,
                '../array_types': 39,
                '../extent': 53,
                '../index_array_type': 55,
                '../load_geometry': 56,
                '../program_configuration': 58,
                '../segment': 60,
                './fill_extrusion_attributes': 45,
                'earcut': 14
            }
        ],
        47: [
            function (_dereq_, module, exports) {
                'use strict';
                var CircleBucket = _dereq_('./circle_bucket'), ref = _dereq_('../../util/web_worker_transfer'), register = ref.register, HeatmapBucket = function (e) {
                        function t() {
                            e.apply(this, arguments);
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t;
                    }(CircleBucket);
                register('HeatmapBucket', HeatmapBucket, { omit: ['layers'] }), module.exports = HeatmapBucket;
            },
            {
                '../../util/web_worker_transfer': 278,
                './circle_bucket': 42
            }
        ],
        48: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../../util/struct_array'), createLayout = ref.createLayout;
                module.exports = createLayout([
                    {
                        name: 'a_pos_normal',
                        components: 4,
                        type: 'Int16'
                    },
                    {
                        name: 'a_data',
                        components: 4,
                        type: 'Uint8'
                    }
                ], 4);
            },
            { '../../util/struct_array': 271 }
        ],
        49: [
            function (_dereq_, module, exports) {
                'use strict';
                function addLineVertex(e, t, r, i, a, n, s) {
                    e.emplaceBack(t.x, t.y, i ? 1 : 0, a ? 1 : -1, Math.round(EXTRUDE_SCALE * r.x) + 128, Math.round(EXTRUDE_SCALE * r.y) + 128, 1 + (0 === n ? 0 : n < 0 ? -1 : 1) | (s * LINE_DISTANCE_SCALE & 63) << 2, s * LINE_DISTANCE_SCALE >> 6);
                }
                var ref = _dereq_('../array_types'), LineLayoutArray = ref.LineLayoutArray, layoutAttributes = _dereq_('./line_attributes').members, ref$1 = _dereq_('../segment'), SegmentVector = ref$1.SegmentVector, ref$2 = _dereq_('../program_configuration'), ProgramConfigurationSet = ref$2.ProgramConfigurationSet, ref$3 = _dereq_('../index_array_type'), TriangleIndexArray = ref$3.TriangleIndexArray, loadGeometry = _dereq_('../load_geometry'), EXTENT = _dereq_('../extent'), vectorTileFeatureTypes = _dereq_('@mapbox/vector-tile').VectorTileFeature.types, ref$4 = _dereq_('../../util/web_worker_transfer'), register = ref$4.register, EXTRUDE_SCALE = 63, COS_HALF_SHARP_CORNER = Math.cos(Math.PI / 180 * 37.5), SHARP_CORNER_OFFSET = 15, LINE_DISTANCE_BUFFER_BITS = 15, LINE_DISTANCE_SCALE = 0.5, MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE, LineBucket = function (e) {
                        this.zoom = e.zoom, this.overscaling = e.overscaling, this.layers = e.layers, this.layerIds = this.layers.map(function (e) {
                            return e.id;
                        }), this.index = e.index, this.layoutVertexArray = new LineLayoutArray(), this.indexArray = new TriangleIndexArray(), this.programConfigurations = new ProgramConfigurationSet(layoutAttributes, e.layers, e.zoom), this.segments = new SegmentVector();
                    };
                LineBucket.prototype.populate = function (e, t) {
                    for (var r = this, i = 0, a = e; i < a.length; i += 1) {
                        var n = a[i], s = n.feature, u = n.index, d = n.sourceLayerIndex;
                        if (r.layers[0]._featureFilter({ zoom: r.zoom }, s)) {
                            var o = loadGeometry(s);
                            r.addFeature(s, o), t.featureIndex.insert(s, o, u, d, r.index);
                        }
                    }
                }, LineBucket.prototype.isEmpty = function () {
                    return 0 === this.layoutVertexArray.length;
                }, LineBucket.prototype.upload = function (e) {
                    this.layoutVertexBuffer = e.createVertexBuffer(this.layoutVertexArray, layoutAttributes), this.indexBuffer = e.createIndexBuffer(this.indexArray), this.programConfigurations.upload(e);
                }, LineBucket.prototype.destroy = function () {
                    this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy());
                }, LineBucket.prototype.addFeature = function (e, t) {
                    for (var r = this, i = this.layers[0].layout, a = i.get('line-join').evaluate(e), n = i.get('line-cap'), s = i.get('line-miter-limit'), u = i.get('line-round-limit'), d = 0, o = t; d < o.length; d += 1) {
                        var l = o[d];
                        r.addLine(l, e, a, n, s, u);
                    }
                }, LineBucket.prototype.addLine = function (e, t, r, i, a, n) {
                    for (var s = this, u = 'Polygon' === vectorTileFeatureTypes[t.type], d = e.length; d >= 2 && e[d - 1].equals(e[d - 2]);) {
                        d--;
                    }
                    for (var o = 0; o < d - 1 && e[o].equals(e[o + 1]);) {
                        o++;
                    }
                    if (!(d < (u ? 3 : 2))) {
                        'bevel' === r && (a = 1.05);
                        var l = SHARP_CORNER_OFFSET * (EXTENT / (512 * this.overscaling)), h = e[o], y = this.segments.prepareSegment(10 * d, this.layoutVertexArray, this.indexArray);
                        this.distance = 0;
                        var c, f, x, m = i, p = u ? 'butt' : i, _ = !0, g = void 0, v = void 0, L = void 0, A = void 0;
                        this.e1 = this.e2 = this.e3 = -1, u && (c = e[d - 2], A = h.sub(c)._unit()._perp());
                        for (var C = o; C < d; C++) {
                            if (!(v = u && C === d - 1 ? e[o + 1] : e[C + 1]) || !e[C].equals(v)) {
                                A && (L = A), c && (g = c), c = e[C], A = v ? v.sub(c)._unit()._perp() : L, L = L || A;
                                var E = L.add(A);
                                0 === E.x && 0 === E.y || E._unit();
                                var V = E.x * A.x + E.y * A.y, S = 0 !== V ? 1 / V : 1 / 0, B = V < COS_HALF_SHARP_CORNER && g && v;
                                if (B && C > o) {
                                    var T = c.dist(g);
                                    if (T > 2 * l) {
                                        var I = c.sub(c.sub(g)._mult(l / T)._round());
                                        s.distance += I.dist(g), s.addCurrentVertex(I, s.distance, L.mult(1), 0, 0, !1, y), g = I;
                                    }
                                }
                                var b = g && v, N = b ? r : v ? m : p;
                                if (b && 'round' === N && (S < n ? N = 'miter' : S <= 2 && (N = 'fakeround')), 'miter' === N && S > a && (N = 'bevel'), 'bevel' === N && (S > 2 && (N = 'flipbevel'), S < a && (N = 'miter')), g && (s.distance += c.dist(g)), 'miter' === N) {
                                    E._mult(S), s.addCurrentVertex(c, s.distance, E, 0, 0, !1, y);
                                } else if ('flipbevel' === N) {
                                    if (S > 100) {
                                        E = A.clone().mult(-1);
                                    } else {
                                        var k = L.x * A.y - L.y * A.x > 0 ? -1 : 1, R = S * L.add(A).mag() / L.sub(A).mag();
                                        E._perp()._mult(R * k);
                                    }
                                    s.addCurrentVertex(c, s.distance, E, 0, 0, !1, y), s.addCurrentVertex(c, s.distance, E.mult(-1), 0, 0, !1, y);
                                } else if ('bevel' === N || 'fakeround' === N) {
                                    var F = L.x * A.y - L.y * A.x > 0, q = -Math.sqrt(S * S - 1);
                                    if (F ? (x = 0, f = q) : (f = 0, x = q), _ || s.addCurrentVertex(c, s.distance, L, f, x, !1, y), 'fakeround' === N) {
                                        for (var P = Math.floor(8 * (0.5 - (V - 0.5))), D = void 0, M = 0; M < P; M++) {
                                            D = A.mult((M + 1) / (P + 1))._add(L)._unit(), s.addPieSliceVertex(c, s.distance, D, F, y);
                                        }
                                        s.addPieSliceVertex(c, s.distance, E, F, y);
                                        for (var O = P - 1; O >= 0; O--) {
                                            D = L.mult((O + 1) / (P + 1))._add(A)._unit(), s.addPieSliceVertex(c, s.distance, D, F, y);
                                        }
                                    }
                                    v && s.addCurrentVertex(c, s.distance, A, -f, -x, !1, y);
                                } else {
                                    'butt' === N ? (_ || s.addCurrentVertex(c, s.distance, L, 0, 0, !1, y), v && s.addCurrentVertex(c, s.distance, A, 0, 0, !1, y)) : 'square' === N ? (_ || (s.addCurrentVertex(c, s.distance, L, 1, 1, !1, y), s.e1 = s.e2 = -1), v && s.addCurrentVertex(c, s.distance, A, -1, -1, !1, y)) : 'round' === N && (_ || (s.addCurrentVertex(c, s.distance, L, 0, 0, !1, y), s.addCurrentVertex(c, s.distance, L, 1, 1, !0, y), s.e1 = s.e2 = -1), v && (s.addCurrentVertex(c, s.distance, A, -1, -1, !0, y), s.addCurrentVertex(c, s.distance, A, 0, 0, !1, y)));
                                }
                                if (B && C < d - 1) {
                                    var $ = c.dist(v);
                                    if ($ > 2 * l) {
                                        var w = c.add(v.sub(c)._mult(l / $)._round());
                                        s.distance += w.dist(c), s.addCurrentVertex(w, s.distance, A.mult(1), 0, 0, !1, y), c = w;
                                    }
                                }
                                _ = !1;
                            }
                        }
                        this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, t);
                    }
                }, LineBucket.prototype.addCurrentVertex = function (e, t, r, i, a, n, s) {
                    var u, d = this.layoutVertexArray, o = this.indexArray;
                    u = r.clone(), i && u._sub(r.perp()._mult(i)), addLineVertex(d, e, u, n, !1, i, t), this.e3 = s.vertexLength++, this.e1 >= 0 && this.e2 >= 0 && (o.emplaceBack(this.e1, this.e2, this.e3), s.primitiveLength++), this.e1 = this.e2, this.e2 = this.e3, u = r.mult(-1), a && u._sub(r.perp()._mult(a)), addLineVertex(d, e, u, n, !0, -a, t), this.e3 = s.vertexLength++, this.e1 >= 0 && this.e2 >= 0 && (o.emplaceBack(this.e1, this.e2, this.e3), s.primitiveLength++), this.e1 = this.e2, this.e2 = this.e3, t > MAX_LINE_DISTANCE / 2 && (this.distance = 0, this.addCurrentVertex(e, this.distance, r, i, a, n, s));
                }, LineBucket.prototype.addPieSliceVertex = function (e, t, r, i, a) {
                    r = r.mult(i ? -1 : 1);
                    var n = this.layoutVertexArray, s = this.indexArray;
                    addLineVertex(n, e, r, !1, i, 0, t), this.e3 = a.vertexLength++, this.e1 >= 0 && this.e2 >= 0 && (s.emplaceBack(this.e1, this.e2, this.e3), a.primitiveLength++), i ? this.e2 = this.e3 : this.e1 = this.e3;
                }, register('LineBucket', LineBucket, { omit: ['layers'] }), module.exports = LineBucket;
            },
            {
                '../../util/web_worker_transfer': 278,
                '../array_types': 39,
                '../extent': 53,
                '../index_array_type': 55,
                '../load_geometry': 56,
                '../program_configuration': 58,
                '../segment': 60,
                './line_attributes': 48,
                '@mapbox/vector-tile': 8
            }
        ],
        50: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../../util/struct_array'), createLayout = ref.createLayout, symbolLayoutAttributes = createLayout([
                        {
                            name: 'a_pos_offset',
                            components: 4,
                            type: 'Int16'
                        },
                        {
                            name: 'a_data',
                            components: 4,
                            type: 'Uint16'
                        }
                    ]), dynamicLayoutAttributes = createLayout([{
                            name: 'a_projected_pos',
                            components: 3,
                            type: 'Float32'
                        }], 4), placementOpacityAttributes = createLayout([{
                            name: 'a_fade_opacity',
                            components: 1,
                            type: 'Uint32'
                        }], 4), collisionVertexAttributes = createLayout([{
                            name: 'a_placed',
                            components: 2,
                            type: 'Uint8'
                        }], 4), symbolAttributes = {
                        symbolLayoutAttributes: symbolLayoutAttributes,
                        dynamicLayoutAttributes: dynamicLayoutAttributes,
                        placementOpacityAttributes: placementOpacityAttributes,
                        collisionVertexAttributes: collisionVertexAttributes,
                        collisionBox: createLayout([
                            {
                                type: 'Int16',
                                name: 'anchorPointX'
                            },
                            {
                                type: 'Int16',
                                name: 'anchorPointY'
                            },
                            {
                                type: 'Int16',
                                name: 'x1'
                            },
                            {
                                type: 'Int16',
                                name: 'y1'
                            },
                            {
                                type: 'Int16',
                                name: 'x2'
                            },
                            {
                                type: 'Int16',
                                name: 'y2'
                            },
                            {
                                type: 'Uint32',
                                name: 'featureIndex'
                            },
                            {
                                type: 'Uint16',
                                name: 'sourceLayerIndex'
                            },
                            {
                                type: 'Uint16',
                                name: 'bucketIndex'
                            },
                            {
                                type: 'Int16',
                                name: 'radius'
                            },
                            {
                                type: 'Int16',
                                name: 'signedDistanceFromAnchor'
                            }
                        ]),
                        collisionBoxLayout: createLayout([
                            {
                                name: 'a_pos',
                                components: 2,
                                type: 'Int16'
                            },
                            {
                                name: 'a_anchor_pos',
                                components: 2,
                                type: 'Int16'
                            },
                            {
                                name: 'a_extrude',
                                components: 2,
                                type: 'Int16'
                            }
                        ], 4),
                        collisionCircleLayout: createLayout([
                            {
                                name: 'a_pos',
                                components: 2,
                                type: 'Int16'
                            },
                            {
                                name: 'a_anchor_pos',
                                components: 2,
                                type: 'Int16'
                            },
                            {
                                name: 'a_extrude',
                                components: 2,
                                type: 'Int16'
                            }
                        ], 4),
                        placement: createLayout([
                            {
                                type: 'Int16',
                                name: 'anchorX'
                            },
                            {
                                type: 'Int16',
                                name: 'anchorY'
                            },
                            {
                                type: 'Uint16',
                                name: 'glyphStartIndex'
                            },
                            {
                                type: 'Uint16',
                                name: 'numGlyphs'
                            },
                            {
                                type: 'Uint32',
                                name: 'vertexStartIndex'
                            },
                            {
                                type: 'Uint32',
                                name: 'lineStartIndex'
                            },
                            {
                                type: 'Uint32',
                                name: 'lineLength'
                            },
                            {
                                type: 'Uint16',
                                name: 'segment'
                            },
                            {
                                type: 'Uint16',
                                name: 'lowerSize'
                            },
                            {
                                type: 'Uint16',
                                name: 'upperSize'
                            },
                            {
                                type: 'Float32',
                                name: 'lineOffsetX'
                            },
                            {
                                type: 'Float32',
                                name: 'lineOffsetY'
                            },
                            {
                                type: 'Uint8',
                                name: 'writingMode'
                            },
                            {
                                type: 'Uint8',
                                name: 'hidden'
                            }
                        ]),
                        glyphOffset: createLayout([{
                                type: 'Float32',
                                name: 'offsetX'
                            }]),
                        lineVertex: createLayout([
                            {
                                type: 'Int16',
                                name: 'x'
                            },
                            {
                                type: 'Int16',
                                name: 'y'
                            },
                            {
                                type: 'Int16',
                                name: 'tileUnitDistanceFromAnchor'
                            }
                        ])
                    };
                module.exports = symbolAttributes;
            },
            { '../../util/struct_array': 271 }
        ],
        51: [
            function (_dereq_, module, exports) {
                'use strict';
                function addVertex(e, t, r, o, i, a, n, s) {
                    e.emplaceBack(t, r, Math.round(64 * o), Math.round(64 * i), a, n, s ? s[0] : 0, s ? s[1] : 0);
                }
                function addDynamicAttributes(e, t, r) {
                    e.emplaceBack(t.x, t.y, r), e.emplaceBack(t.x, t.y, r), e.emplaceBack(t.x, t.y, r), e.emplaceBack(t.x, t.y, r);
                }
                var ref = _dereq_('./symbol_attributes'), symbolLayoutAttributes = ref.symbolLayoutAttributes, collisionVertexAttributes = ref.collisionVertexAttributes, collisionBoxLayout = ref.collisionBoxLayout, collisionCircleLayout = ref.collisionCircleLayout, dynamicLayoutAttributes = ref.dynamicLayoutAttributes, ref$1 = _dereq_('../array_types'), SymbolLayoutArray = ref$1.SymbolLayoutArray, SymbolDynamicLayoutArray = ref$1.SymbolDynamicLayoutArray, SymbolOpacityArray = ref$1.SymbolOpacityArray, CollisionBoxLayoutArray = ref$1.CollisionBoxLayoutArray, CollisionCircleLayoutArray = ref$1.CollisionCircleLayoutArray, CollisionVertexArray = ref$1.CollisionVertexArray, PlacedSymbolArray = ref$1.PlacedSymbolArray, GlyphOffsetArray = ref$1.GlyphOffsetArray, SymbolLineVertexArray = ref$1.SymbolLineVertexArray, Point = _dereq_('@mapbox/point-geometry'), ref$2 = _dereq_('../segment'), SegmentVector = ref$2.SegmentVector, ref$3 = _dereq_('../program_configuration'), ProgramConfigurationSet = ref$3.ProgramConfigurationSet, ref$4 = _dereq_('../index_array_type'), TriangleIndexArray = ref$4.TriangleIndexArray, LineIndexArray = ref$4.LineIndexArray, transformText = _dereq_('../../symbol/transform_text'), mergeLines = _dereq_('../../symbol/mergelines'), scriptDetection = _dereq_('../../util/script_detection'), loadGeometry = _dereq_('../load_geometry'), vectorTileFeatureTypes = _dereq_('@mapbox/vector-tile').VectorTileFeature.types, verticalizePunctuation = _dereq_('../../util/verticalize_punctuation'), Anchor = _dereq_('../../symbol/anchor'), ref$5 = _dereq_('../../symbol/symbol_size'), getSizeData = ref$5.getSizeData, ref$6 = _dereq_('../../util/web_worker_transfer'), register = ref$6.register, shaderOpacityAttributes = [{
                            name: 'a_fade_opacity',
                            components: 1,
                            type: 'Uint8',
                            offset: 0
                        }], SymbolBuffers = function (e) {
                        this.layoutVertexArray = new SymbolLayoutArray(), this.indexArray = new TriangleIndexArray(), this.programConfigurations = e, this.segments = new SegmentVector(), this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray(), this.opacityVertexArray = new SymbolOpacityArray(), this.placedSymbolArray = new PlacedSymbolArray();
                    };
                SymbolBuffers.prototype.upload = function (e, t) {
                    this.layoutVertexBuffer = e.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members), this.indexBuffer = e.createIndexBuffer(this.indexArray, t), this.programConfigurations.upload(e), this.dynamicLayoutVertexBuffer = e.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, !0), this.opacityVertexBuffer = e.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, !0), this.opacityVertexBuffer.itemSize = 1;
                }, SymbolBuffers.prototype.destroy = function () {
                    this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.programConfigurations.destroy(), this.segments.destroy(), this.dynamicLayoutVertexBuffer.destroy(), this.opacityVertexBuffer.destroy());
                }, register('SymbolBuffers', SymbolBuffers);
                var CollisionBuffers = function (e, t, r) {
                    this.layoutVertexArray = new e(), this.layoutAttributes = t, this.indexArray = new r(), this.segments = new SegmentVector(), this.collisionVertexArray = new CollisionVertexArray();
                };
                CollisionBuffers.prototype.upload = function (e) {
                    this.layoutVertexBuffer = e.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes), this.indexBuffer = e.createIndexBuffer(this.indexArray), this.collisionVertexBuffer = e.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, !0);
                }, CollisionBuffers.prototype.destroy = function () {
                    this.layoutVertexBuffer && (this.layoutVertexBuffer.destroy(), this.indexBuffer.destroy(), this.segments.destroy(), this.collisionVertexBuffer.destroy());
                }, register('CollisionBuffers', CollisionBuffers);
                var SymbolBucket = function (e) {
                    this.collisionBoxArray = e.collisionBoxArray, this.zoom = e.zoom, this.overscaling = e.overscaling, this.layers = e.layers, this.layerIds = this.layers.map(function (e) {
                        return e.id;
                    }), this.index = e.index, this.pixelRatio = e.pixelRatio;
                    var t = this.layers[0], r = t._unevaluatedLayout._values;
                    this.textSizeData = getSizeData(this.zoom, r['text-size']), this.iconSizeData = getSizeData(this.zoom, r['icon-size']);
                    var o = this.layers[0].layout;
                    this.sortFeaturesByY = o.get('text-allow-overlap') || o.get('icon-allow-overlap') || o.get('text-ignore-placement') || o.get('icon-ignore-placement');
                };
                SymbolBucket.prototype.createArrays = function () {
                    this.text = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, function (e) {
                        return /^text/.test(e);
                    })), this.icon = new SymbolBuffers(new ProgramConfigurationSet(symbolLayoutAttributes.members, this.layers, this.zoom, function (e) {
                        return /^icon/.test(e);
                    })), this.collisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray), this.collisionCircle = new CollisionBuffers(CollisionCircleLayoutArray, collisionCircleLayout.members, TriangleIndexArray), this.glyphOffsetArray = new GlyphOffsetArray(), this.lineVertexArray = new SymbolLineVertexArray();
                }, SymbolBucket.prototype.populate = function (e, t) {
                    var r = this, o = this.layers[0], i = o.layout, a = i.get('text-font'), n = i.get('text-field'), s = i.get('icon-image'), l = ('constant' !== n.value.kind || n.value.value.length > 0) && ('constant' !== a.value.kind || a.value.value.length > 0), y = 'constant' !== s.value.kind || s.value.value && s.value.value.length > 0;
                    if (this.features = [], l || y) {
                        for (var c = t.iconDependencies, u = t.glyphDependencies, x = { zoom: this.zoom }, f = 0, h = e; f < h.length; f += 1) {
                            var m = h[f], d = m.feature, p = m.index, g = m.sourceLayerIndex;
                            if (o._featureFilter(x, d)) {
                                var A = void 0;
                                l && (A = o.getValueAndResolveTokens('text-field', d), A = transformText(A, o, d));
                                var b = void 0;
                                if (y && (b = o.getValueAndResolveTokens('icon-image', d)), A || b) {
                                    var B = {
                                        text: A,
                                        icon: b,
                                        index: p,
                                        sourceLayerIndex: g,
                                        geometry: loadGeometry(d),
                                        properties: d.properties,
                                        type: vectorTileFeatureTypes[d.type]
                                    };
                                    if (void 0 !== d.id && (B.id = d.id), r.features.push(B), b && (c[b] = !0), A) {
                                        for (var v = a.evaluate(d).join(','), S = u[v] = u[v] || {}, V = 'map' === i.get('text-rotation-alignment') && 'line' === i.get('symbol-placement'), C = scriptDetection.allowsVerticalWritingMode(A), k = 0; k < A.length; k++) {
                                            if (S[A.charCodeAt(k)] = !0, V && C) {
                                                var L = verticalizePunctuation.lookup[A.charAt(k)];
                                                L && (S[L.charCodeAt(0)] = !0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        'line' === i.get('symbol-placement') && (this.features = mergeLines(this.features));
                    }
                }, SymbolBucket.prototype.isEmpty = function () {
                    return 0 === this.symbolInstances.length;
                }, SymbolBucket.prototype.upload = function (e) {
                    this.text.upload(e, this.sortFeaturesByY), this.icon.upload(e, this.sortFeaturesByY), this.collisionBox.upload(e), this.collisionCircle.upload(e);
                }, SymbolBucket.prototype.destroy = function () {
                    this.text.destroy(), this.icon.destroy(), this.collisionBox.destroy(), this.collisionCircle.destroy();
                }, SymbolBucket.prototype.addToLineVertexArray = function (e, t) {
                    var r = this, o = this.lineVertexArray.length;
                    if (void 0 !== e.segment) {
                        for (var i = e.dist(t[e.segment + 1]), a = e.dist(t[e.segment]), n = {}, s = e.segment + 1; s < t.length; s++) {
                            n[s] = {
                                x: t[s].x,
                                y: t[s].y,
                                tileUnitDistanceFromAnchor: i
                            }, s < t.length - 1 && (i += t[s + 1].dist(t[s]));
                        }
                        for (var l = e.segment || 0; l >= 0; l--) {
                            n[l] = {
                                x: t[l].x,
                                y: t[l].y,
                                tileUnitDistanceFromAnchor: a
                            }, l > 0 && (a += t[l - 1].dist(t[l]));
                        }
                        for (var y = 0; y < t.length; y++) {
                            var c = n[y];
                            r.lineVertexArray.emplaceBack(c.x, c.y, c.tileUnitDistanceFromAnchor);
                        }
                    }
                    return {
                        lineStartIndex: o,
                        lineLength: this.lineVertexArray.length - o
                    };
                }, SymbolBucket.prototype.addSymbols = function (e, t, r, o, i, a, n, s, l, y) {
                    for (var c = this, u = e.indexArray, x = e.layoutVertexArray, f = e.dynamicLayoutVertexArray, h = e.segments.prepareSegment(4 * t.length, e.layoutVertexArray, e.indexArray), m = this.glyphOffsetArray.length, d = h.vertexLength, p = 0, g = t; p < g.length; p += 1) {
                        var A = g[p], b = A.tl, B = A.tr, v = A.bl, S = A.br, V = A.tex, C = h.vertexLength, k = A.glyphOffset[1];
                        addVertex(x, s.x, s.y, b.x, k + b.y, V.x, V.y, r), addVertex(x, s.x, s.y, B.x, k + B.y, V.x + V.w, V.y, r), addVertex(x, s.x, s.y, v.x, k + v.y, V.x, V.y + V.h, r), addVertex(x, s.x, s.y, S.x, k + S.y, V.x + V.w, V.y + V.h, r), addDynamicAttributes(f, s, 0), u.emplaceBack(C, C + 1, C + 2), u.emplaceBack(C + 1, C + 2, C + 3), h.vertexLength += 4, h.primitiveLength += 2, c.glyphOffsetArray.emplaceBack(A.glyphOffset[0]);
                    }
                    e.placedSymbolArray.emplaceBack(s.x, s.y, m, this.glyphOffsetArray.length - m, d, l, y, s.segment, r ? r[0] : 0, r ? r[1] : 0, o[0], o[1], n, !1), e.programConfigurations.populatePaintArrays(e.layoutVertexArray.length, a);
                }, SymbolBucket.prototype._addCollisionDebugVertex = function (e, t, r, o, i) {
                    return t.emplaceBack(0, 0), e.emplaceBack(r.x, r.y, o.x, o.y, Math.round(i.x), Math.round(i.y));
                }, SymbolBucket.prototype.addCollisionDebugVertices = function (e, t, r, o, i, a, n, s) {
                    var l = i.segments.prepareSegment(4, i.layoutVertexArray, i.indexArray), y = l.vertexLength, c = i.layoutVertexArray, u = i.collisionVertexArray;
                    if (this._addCollisionDebugVertex(c, u, a, n.anchor, new Point(e, t)), this._addCollisionDebugVertex(c, u, a, n.anchor, new Point(r, t)), this._addCollisionDebugVertex(c, u, a, n.anchor, new Point(r, o)), this._addCollisionDebugVertex(c, u, a, n.anchor, new Point(e, o)), l.vertexLength += 4, s) {
                        var x = i.indexArray;
                        x.emplaceBack(y, y + 1, y + 2), x.emplaceBack(y, y + 2, y + 3), l.primitiveLength += 2;
                    } else {
                        var f = i.indexArray;
                        f.emplaceBack(y, y + 1), f.emplaceBack(y + 1, y + 2), f.emplaceBack(y + 2, y + 3), f.emplaceBack(y + 3, y), l.primitiveLength += 4;
                    }
                }, SymbolBucket.prototype.generateCollisionDebugBuffers = function () {
                    for (var e = this, t = 0, r = e.symbolInstances; t < r.length; t += 1) {
                        var o = r[t];
                        o.textCollisionFeature = {
                            boxStartIndex: o.textBoxStartIndex,
                            boxEndIndex: o.textBoxEndIndex
                        }, o.iconCollisionFeature = {
                            boxStartIndex: o.iconBoxStartIndex,
                            boxEndIndex: o.iconBoxEndIndex
                        };
                        for (var i = 0; i < 2; i++) {
                            var a = o[0 === i ? 'textCollisionFeature' : 'iconCollisionFeature'];
                            if (a) {
                                for (var n = a.boxStartIndex; n < a.boxEndIndex; n++) {
                                    var s = e.collisionBoxArray.get(n), l = s.x1, y = s.y1, c = s.x2, u = s.y2, x = s.radius > 0;
                                    e.addCollisionDebugVertices(l, y, c, u, x ? e.collisionCircle : e.collisionBox, s.anchorPoint, o, x);
                                }
                            }
                        }
                    }
                }, SymbolBucket.prototype.deserializeCollisionBoxes = function (e, t, r, o, i) {
                    for (var a = {}, n = t; n < r; n++) {
                        var s = e.get(n);
                        if (0 === s.radius) {
                            a.textBox = {
                                x1: s.x1,
                                y1: s.y1,
                                x2: s.x2,
                                y2: s.y2,
                                anchorPointX: s.anchorPointX,
                                anchorPointY: s.anchorPointY
                            };
                            break;
                        }
                        a.textCircles || (a.textCircles = []);
                        a.textCircles.push(s.anchorPointX, s.anchorPointY, s.radius, s.signedDistanceFromAnchor, 1);
                    }
                    for (var l = o; l < i; l++) {
                        var y = e.get(l);
                        if (0 === y.radius) {
                            a.iconBox = {
                                x1: y.x1,
                                y1: y.y1,
                                x2: y.x2,
                                y2: y.y2,
                                anchorPointX: y.anchorPointX,
                                anchorPointY: y.anchorPointY
                            };
                            break;
                        }
                    }
                    return a;
                }, SymbolBucket.prototype.hasTextData = function () {
                    return this.text.segments.get().length > 0;
                }, SymbolBucket.prototype.hasIconData = function () {
                    return this.icon.segments.get().length > 0;
                }, SymbolBucket.prototype.hasCollisionBoxData = function () {
                    return this.collisionBox.segments.get().length > 0;
                }, SymbolBucket.prototype.hasCollisionCircleData = function () {
                    return this.collisionCircle.segments.get().length > 0;
                }, SymbolBucket.prototype.sortFeatures = function (e) {
                    var t = this;
                    if (this.sortFeaturesByY && this.sortedAngle !== e && (this.sortedAngle = e, !(this.text.segments.get().length > 1 || this.icon.segments.get().length > 1))) {
                        for (var r = [], o = 0; o < this.symbolInstances.length; o++) {
                            r.push(o);
                        }
                        var i = Math.sin(e), a = Math.cos(e);
                        r.sort(function (e, r) {
                            var o = t.symbolInstances[e], n = t.symbolInstances[r];
                            return (i * o.anchor.x + a * o.anchor.y | 0) - (i * n.anchor.x + a * n.anchor.y | 0) || n.featureIndex - o.featureIndex;
                        }), this.text.indexArray.clear(), this.icon.indexArray.clear();
                        for (var n = 0, s = r; n < s.length; n += 1) {
                            for (var l = s[n], y = t.symbolInstances[l], c = 0, u = y.placedTextSymbolIndices; c < u.length; c += 1) {
                                for (var x = u[c], f = t.text.placedSymbolArray.get(x), h = f.vertexStartIndex + 4 * f.numGlyphs, m = f.vertexStartIndex; m < h; m += 4) {
                                    t.text.indexArray.emplaceBack(m, m + 1, m + 2), t.text.indexArray.emplaceBack(m + 1, m + 2, m + 3);
                                }
                            }
                            var d = t.icon.placedSymbolArray.get(l);
                            if (d.numGlyphs) {
                                var p = d.vertexStartIndex;
                                t.icon.indexArray.emplaceBack(p, p + 1, p + 2), t.icon.indexArray.emplaceBack(p + 1, p + 2, p + 3);
                            }
                        }
                        this.text.indexBuffer && this.text.indexBuffer.updateData(this.text.indexArray), this.icon.indexBuffer && this.icon.indexBuffer.updateData(this.icon.indexArray);
                    }
                }, register('SymbolBucket', SymbolBucket, {
                    omit: [
                        'layers',
                        'collisionBoxArray',
                        'features',
                        'compareText'
                    ],
                    shallow: ['symbolInstances']
                }), SymbolBucket.MAX_GLYPHS = 65535, SymbolBucket.addDynamicAttributes = addDynamicAttributes, module.exports = SymbolBucket;
            },
            {
                '../../symbol/anchor': 213,
                '../../symbol/mergelines': 221,
                '../../symbol/symbol_size': 228,
                '../../symbol/transform_text': 229,
                '../../util/script_detection': 269,
                '../../util/verticalize_punctuation': 277,
                '../../util/web_worker_transfer': 278,
                '../array_types': 39,
                '../index_array_type': 55,
                '../load_geometry': 56,
                '../program_configuration': 58,
                '../segment': 60,
                './symbol_attributes': 50,
                '@mapbox/point-geometry': 4,
                '@mapbox/vector-tile': 8
            }
        ],
        52: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/image'), RGBAImage = ref.RGBAImage, util = _dereq_('../util/util'), ref$1 = _dereq_('../util/web_worker_transfer'), register = ref$1.register, Level = function (e, t, i) {
                        if (e <= 0) {
                            throw new RangeError('Level must have positive dimension');
                        }
                        this.dim = e, this.border = t, this.stride = this.dim + 2 * this.border, this.data = i || new Int32Array((this.dim + 2 * this.border) * (this.dim + 2 * this.border));
                    };
                Level.prototype.set = function (e, t, i) {
                    this.data[this._idx(e, t)] = i + 65536;
                }, Level.prototype.get = function (e, t) {
                    return this.data[this._idx(e, t)] - 65536;
                }, Level.prototype._idx = function (e, t) {
                    if (e < -this.border || e >= this.dim + this.border || t < -this.border || t >= this.dim + this.border) {
                        throw new RangeError('out of range source coordinates for DEM data');
                    }
                    return (t + this.border) * this.stride + (e + this.border);
                }, register('Level', Level);
                var DEMData = function (e, t, i) {
                    this.uid = e, this.scale = t || 1, this.level = i || new Level(256, 512), this.loaded = !!i;
                };
                DEMData.prototype.loadFromImage = function (e) {
                    var t = this;
                    if (e.height !== e.width) {
                        throw new RangeError('DEM tiles must be square');
                    }
                    for (var i = this.level = new Level(e.width, e.width / 2), r = e.data, d = 0; d < i.dim; d++) {
                        for (var s = 0; s < i.dim; s++) {
                            var a = d * i.dim + s, o = 4 * a;
                            i.set(s, d, t.scale * ((256 * r[o] * 256 + 256 * r[o + 1] + r[o + 2]) / 10 - 10000));
                        }
                    }
                    for (var m = 0; m < i.dim; m++) {
                        i.set(-1, m, i.get(0, m)), i.set(i.dim, m, i.get(i.dim - 1, m)), i.set(m, -1, i.get(m, 0)), i.set(m, i.dim, i.get(m, i.dim - 1));
                    }
                    i.set(-1, -1, i.get(0, 0)), i.set(i.dim, -1, i.get(i.dim - 1, 0)), i.set(-1, i.dim, i.get(0, i.dim - 1)), i.set(i.dim, i.dim, i.get(i.dim - 1, i.dim - 1)), this.loaded = !0;
                }, DEMData.prototype.getPixels = function () {
                    return new RGBAImage({
                        width: this.level.dim + 2 * this.level.border,
                        height: this.level.dim + 2 * this.level.border
                    }, new Uint8Array(this.level.data.buffer));
                }, DEMData.prototype.backfillBorder = function (e, t, i) {
                    var r = this.level, d = e.level;
                    if (r.dim !== d.dim) {
                        throw new Error('level mismatch (dem dimension)');
                    }
                    var s = t * r.dim, a = t * r.dim + r.dim, o = i * r.dim, m = i * r.dim + r.dim;
                    switch (t) {
                    case -1:
                        s = a - 1;
                        break;
                    case 1:
                        a = s + 1;
                    }
                    switch (i) {
                    case -1:
                        o = m - 1;
                        break;
                    case 1:
                        m = o + 1;
                    }
                    for (var l = util.clamp(s, -r.border, r.dim + r.border), h = util.clamp(a, -r.border, r.dim + r.border), n = util.clamp(o, -r.border, r.dim + r.border), v = util.clamp(m, -r.border, r.dim + r.border), u = -t * r.dim, f = -i * r.dim, b = n; b < v; b++) {
                        for (var g = l; g < h; g++) {
                            r.set(g, b, d.get(g + u, b + f));
                        }
                    }
                }, register('DEMData', DEMData), module.exports = {
                    DEMData: DEMData,
                    Level: Level
                };
            },
            {
                '../util/image': 263,
                '../util/util': 275,
                '../util/web_worker_transfer': 278
            }
        ],
        53: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = 8192;
            },
            {}
        ],
        54: [
            function (_dereq_, module, exports) {
                'use strict';
                function topDownFeatureComparator(e, r) {
                    return r - e;
                }
                var Point = _dereq_('@mapbox/point-geometry'), loadGeometry = _dereq_('./load_geometry'), EXTENT = _dereq_('./extent'), featureFilter = _dereq_('../style-spec/feature_filter'), Grid = _dereq_('grid-index'), DictionaryCoder = _dereq_('../util/dictionary_coder'), vt = _dereq_('@mapbox/vector-tile'), Protobuf = _dereq_('pbf'), GeoJSONFeature = _dereq_('../util/vectortile_to_geojson'), arraysIntersect = _dereq_('../util/util').arraysIntersect, ref = _dereq_('../source/tile_id'), OverscaledTileID = ref.OverscaledTileID, ref$1 = _dereq_('../util/web_worker_transfer'), register = ref$1.register, ref$2 = _dereq_('./array_types'), FeatureIndexArray = ref$2.FeatureIndexArray, FeatureIndex = function (e, r, t, a) {
                        this.tileID = e, this.overscaling = r, this.x = e.canonical.x, this.y = e.canonical.y, this.z = e.canonical.z, this.grid = t || new Grid(EXTENT, 16, 0), this.featureIndexArray = a || new FeatureIndexArray();
                    };
                FeatureIndex.prototype.insert = function (e, r, t, a, i) {
                    var o = this, n = this.featureIndexArray.length;
                    this.featureIndexArray.emplaceBack(t, a, i);
                    for (var s = 0; s < r.length; s++) {
                        for (var u = r[s], l = [
                                    1 / 0,
                                    1 / 0,
                                    -1 / 0,
                                    -1 / 0
                                ], y = 0; y < u.length; y++) {
                            var d = u[y];
                            l[0] = Math.min(l[0], d.x), l[1] = Math.min(l[1], d.y), l[2] = Math.max(l[2], d.x), l[3] = Math.max(l[3], d.y);
                        }
                        o.grid.insert(n, l[0], l[1], l[2], l[3]);
                    }
                }, FeatureIndex.prototype.query = function (e, r) {
                    this.vtLayers || (this.vtLayers = new vt.VectorTile(new Protobuf(this.rawTileData)).layers, this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']));
                    for (var t = {}, a = e.params || {}, i = EXTENT / e.tileSize / e.scale, o = featureFilter(a.filter), n = e.queryGeometry, s = e.additionalRadius * i, u = 1 / 0, l = 1 / 0, y = -1 / 0, d = -1 / 0, c = 0; c < n.length; c++) {
                        for (var f = n[c], h = 0; h < f.length; h++) {
                            var x = f[h];
                            u = Math.min(u, x.x), l = Math.min(l, x.y), y = Math.max(y, x.x), d = Math.max(d, x.y);
                        }
                    }
                    var v = this.grid.query(u - s, l - s, y + s, d + s);
                    v.sort(topDownFeatureComparator), this.filterMatching(t, v, this.featureIndexArray, n, o, a.layers, r, e.bearing, i);
                    var I = e.collisionIndex ? e.collisionIndex.queryRenderedSymbols(n, this.tileID, EXTENT / e.tileSize, e.collisionBoxArray, e.sourceID, e.bucketInstanceIds) : [];
                    return I.sort(), this.filterMatching(t, I, e.collisionBoxArray, n, o, a.layers, r, e.bearing, i), t;
                }, FeatureIndex.prototype.filterMatching = function (e, r, t, a, i, o, n, s, u) {
                    for (var l, y = this, d = 0; d < r.length; d++) {
                        var c = r[d];
                        if (c !== l) {
                            l = c;
                            var f = t.get(c), h = y.bucketLayerIDs[f.bucketIndex];
                            if (!o || arraysIntersect(o, h)) {
                                var x = y.sourceLayerCoder.decode(f.sourceLayerIndex), v = y.vtLayers[x], I = v.feature(f.featureIndex);
                                if (i({ zoom: y.tileID.overscaledZ }, I)) {
                                    for (var g = null, m = 0; m < h.length; m++) {
                                        var p = h[m];
                                        if (!(o && o.indexOf(p) < 0)) {
                                            var q = n[p];
                                            if (q && ('symbol' === q.type || (g || (g = loadGeometry(I)), q.queryIntersectsFeature(a, I, g, y.z, s, u)))) {
                                                var F = new GeoJSONFeature(I, y.z, y.x, y.y);
                                                F.layer = q.serialize();
                                                var b = e[p];
                                                void 0 === b && (b = e[p] = []), b.push({
                                                    featureIndex: c,
                                                    feature: F
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }, FeatureIndex.prototype.hasLayer = function (e) {
                    for (var r = this, t = 0, a = r.bucketLayerIDs; t < a.length; t += 1) {
                        for (var i = a[t], o = 0, n = i; o < n.length; o += 1) {
                            var s = n[o];
                            if (e === s) {
                                return !0;
                            }
                        }
                    }
                    return !1;
                }, register('FeatureIndex', FeatureIndex, {
                    omit: [
                        'rawTileData',
                        'sourceLayerCoder'
                    ]
                }), module.exports = FeatureIndex;
            },
            {
                '../source/tile_id': 114,
                '../style-spec/feature_filter': 148,
                '../util/dictionary_coder': 257,
                '../util/util': 275,
                '../util/vectortile_to_geojson': 276,
                '../util/web_worker_transfer': 278,
                './array_types': 39,
                './extent': 53,
                './load_geometry': 56,
                '@mapbox/point-geometry': 4,
                '@mapbox/vector-tile': 8,
                'grid-index': 24,
                'pbf': 30
            }
        ],
        55: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = {
                    LineIndexArray: _dereq_('./array_types').LineIndexArray,
                    TriangleIndexArray: _dereq_('./array_types').TriangleIndexArray
                };
            },
            { './array_types': 39 }
        ],
        56: [
            function (_dereq_, module, exports) {
                'use strict';
                function createBounds(e) {
                    return {
                        min: -1 * Math.pow(2, e - 1),
                        max: Math.pow(2, e - 1) - 1
                    };
                }
                var util = _dereq_('../util/util'), EXTENT = _dereq_('./extent'), bounds = createBounds(16);
                module.exports = function (e) {
                    for (var t = EXTENT / e.extent, r = e.loadGeometry(), n = 0; n < r.length; n++) {
                        for (var u = r[n], o = 0; o < u.length; o++) {
                            var a = u[o];
                            a.x = Math.round(a.x * t), a.y = Math.round(a.y * t), (a.x < bounds.min || a.x > bounds.max || a.y < bounds.min || a.y > bounds.max) && util.warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');
                        }
                    }
                    return r;
                };
            },
            {
                '../util/util': 275,
                './extent': 53
            }
        ],
        57: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/struct_array'), createLayout = ref.createLayout;
                module.exports = createLayout([{
                        name: 'a_pos',
                        type: 'Int16',
                        components: 2
                    }]);
            },
            { '../util/struct_array': 271 }
        ],
        58: [
            function (_dereq_, module, exports) {
                'use strict';
                function packColor(r) {
                    return [
                        packUint8ToFloat(255 * r.r, 255 * r.g),
                        packUint8ToFloat(255 * r.b, 255 * r.a)
                    ];
                }
                function paintAttributeName(r, t) {
                    return {
                        'text-opacity': 'opacity',
                        'icon-opacity': 'opacity',
                        'text-color': 'fill_color',
                        'icon-color': 'fill_color',
                        'text-halo-color': 'halo_color',
                        'icon-halo-color': 'halo_color',
                        'text-halo-blur': 'halo_blur',
                        'icon-halo-blur': 'halo_blur',
                        'text-halo-width': 'halo_width',
                        'icon-halo-width': 'halo_width',
                        'line-gap-width': 'gapwidth'
                    }[r] || r.replace(t + '-', '').replace(/-/g, '_');
                }
                var packUint8ToFloat = _dereq_('../shaders/encode_attribute').packUint8ToFloat, Color = _dereq_('../style-spec/util/color'), ref = _dereq_('../util/web_worker_transfer'), register = ref.register, ref$1 = _dereq_('../style/properties'), PossiblyEvaluatedPropertyValue = ref$1.PossiblyEvaluatedPropertyValue, ref$2 = _dereq_('./array_types'), StructArrayLayout1f4 = ref$2.StructArrayLayout1f4, StructArrayLayout2f8 = ref$2.StructArrayLayout2f8, StructArrayLayout4f16 = ref$2.StructArrayLayout4f16, ConstantBinder = function (r, t, o) {
                        this.value = r, this.name = t, this.type = o, this.statistics = { max: -1 / 0 };
                    };
                ConstantBinder.prototype.defines = function () {
                    return ['#define HAS_UNIFORM_u_' + this.name];
                }, ConstantBinder.prototype.populatePaintArray = function () {
                }, ConstantBinder.prototype.upload = function () {
                }, ConstantBinder.prototype.destroy = function () {
                }, ConstantBinder.prototype.setUniforms = function (r, t, o, e) {
                    var i = e.constantOr(this.value), n = r.gl;
                    'color' === this.type ? n.uniform4f(t.uniforms['u_' + this.name], i.r, i.g, i.b, i.a) : n.uniform1f(t.uniforms['u_' + this.name], i);
                };
                var SourceExpressionBinder = function (r, t, o) {
                    this.expression = r, this.name = t, this.type = o, this.statistics = { max: -1 / 0 };
                    var e = 'color' === o ? StructArrayLayout2f8 : StructArrayLayout1f4;
                    this.paintVertexAttributes = [{
                            name: 'a_' + t,
                            type: 'Float32',
                            components: 'color' === o ? 2 : 1,
                            offset: 0
                        }], this.paintVertexArray = new e();
                };
                SourceExpressionBinder.prototype.defines = function () {
                    return [];
                }, SourceExpressionBinder.prototype.populatePaintArray = function (r, t) {
                    var o = this.paintVertexArray, e = o.length;
                    o.reserve(r);
                    var i = this.expression.evaluate({ zoom: 0 }, t);
                    if ('color' === this.type) {
                        for (var n = packColor(i), a = e; a < r; a++) {
                            o.emplaceBack(n[0], n[1]);
                        }
                    } else {
                        for (var s = e; s < r; s++) {
                            o.emplaceBack(i);
                        }
                        this.statistics.max = Math.max(this.statistics.max, i);
                    }
                }, SourceExpressionBinder.prototype.upload = function (r) {
                    this.paintVertexArray && (this.paintVertexBuffer = r.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes));
                }, SourceExpressionBinder.prototype.destroy = function () {
                    this.paintVertexBuffer && this.paintVertexBuffer.destroy();
                }, SourceExpressionBinder.prototype.setUniforms = function (r, t) {
                    r.gl.uniform1f(t.uniforms['a_' + this.name + '_t'], 0);
                };
                var CompositeExpressionBinder = function (r, t, o, e, i) {
                    this.expression = r, this.name = t, this.type = o, this.useIntegerZoom = e, this.zoom = i, this.statistics = { max: -1 / 0 };
                    var n = 'color' === o ? StructArrayLayout4f16 : StructArrayLayout2f8;
                    this.paintVertexAttributes = [{
                            name: 'a_' + t,
                            type: 'Float32',
                            components: 'color' === o ? 4 : 2,
                            offset: 0
                        }], this.paintVertexArray = new n();
                };
                CompositeExpressionBinder.prototype.defines = function () {
                    return [];
                }, CompositeExpressionBinder.prototype.populatePaintArray = function (r, t) {
                    var o = this.paintVertexArray, e = o.length;
                    o.reserve(r);
                    var i = this.expression.evaluate({ zoom: this.zoom }, t), n = this.expression.evaluate({ zoom: this.zoom + 1 }, t);
                    if ('color' === this.type) {
                        for (var a = packColor(i), s = packColor(n), p = e; p < r; p++) {
                            o.emplaceBack(a[0], a[1], s[0], s[1]);
                        }
                    } else {
                        for (var u = e; u < r; u++) {
                            o.emplaceBack(i, n);
                        }
                        this.statistics.max = Math.max(this.statistics.max, i, n);
                    }
                }, CompositeExpressionBinder.prototype.upload = function (r) {
                    this.paintVertexArray && (this.paintVertexBuffer = r.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes));
                }, CompositeExpressionBinder.prototype.destroy = function () {
                    this.paintVertexBuffer && this.paintVertexBuffer.destroy();
                }, CompositeExpressionBinder.prototype.interpolationFactor = function (r) {
                    return this.useIntegerZoom ? this.expression.interpolationFactor(Math.floor(r), this.zoom, this.zoom + 1) : this.expression.interpolationFactor(r, this.zoom, this.zoom + 1);
                }, CompositeExpressionBinder.prototype.setUniforms = function (r, t, o) {
                    r.gl.uniform1f(t.uniforms['a_' + this.name + '_t'], this.interpolationFactor(o.zoom));
                };
                var ProgramConfiguration = function () {
                    this.binders = {}, this.cacheKey = '', this._buffers = [];
                };
                ProgramConfiguration.createDynamic = function (r, t, o) {
                    var e = new ProgramConfiguration(), i = [];
                    for (var n in r.paint._values) {
                        if (o(n)) {
                            var a = r.paint.get(n);
                            if (a instanceof PossiblyEvaluatedPropertyValue && a.property.specification['property-function']) {
                                var s = paintAttributeName(n, r.type), p = a.property.specification.type, u = a.property.useIntegerZoom;
                                'constant' === a.value.kind ? (e.binders[n] = new ConstantBinder(a.value, s, p), i.push('/u_' + s)) : 'source' === a.value.kind ? (e.binders[n] = new SourceExpressionBinder(a.value, s, p), i.push('/a_' + s)) : (e.binders[n] = new CompositeExpressionBinder(a.value, s, p, u, t), i.push('/z_' + s));
                            }
                        }
                    }
                    return e.cacheKey = i.sort().join(''), e;
                }, ProgramConfiguration.prototype.populatePaintArrays = function (r, t) {
                    var o = this;
                    for (var e in o.binders) {
                        o.binders[e].populatePaintArray(r, t);
                    }
                }, ProgramConfiguration.prototype.defines = function () {
                    var r = this, t = [];
                    for (var o in r.binders) {
                        t.push.apply(t, r.binders[o].defines());
                    }
                    return t;
                }, ProgramConfiguration.prototype.setUniforms = function (r, t, o, e) {
                    var i = this;
                    for (var n in i.binders) {
                        i.binders[n].setUniforms(r, t, e, o.get(n));
                    }
                }, ProgramConfiguration.prototype.getPaintVertexBuffers = function () {
                    return this._buffers;
                }, ProgramConfiguration.prototype.upload = function (r) {
                    var t = this;
                    for (var o in t.binders) {
                        t.binders[o].upload(r);
                    }
                    var e = [];
                    for (var i in t.binders) {
                        var n = t.binders[i];
                        (n instanceof SourceExpressionBinder || n instanceof CompositeExpressionBinder) && n.paintVertexBuffer && e.push(n.paintVertexBuffer);
                    }
                    this._buffers = e;
                }, ProgramConfiguration.prototype.destroy = function () {
                    var r = this;
                    for (var t in r.binders) {
                        r.binders[t].destroy();
                    }
                };
                var ProgramConfigurationSet = function (r, t, o, e) {
                    var i = this;
                    void 0 === e && (e = function () {
                        return !0;
                    }), this.programConfigurations = {};
                    for (var n = 0, a = t; n < a.length; n += 1) {
                        var s = a[n];
                        i.programConfigurations[s.id] = ProgramConfiguration.createDynamic(s, o, e), i.programConfigurations[s.id].layoutAttributes = r;
                    }
                };
                ProgramConfigurationSet.prototype.populatePaintArrays = function (r, t) {
                    var o = this;
                    for (var e in o.programConfigurations) {
                        o.programConfigurations[e].populatePaintArrays(r, t);
                    }
                }, ProgramConfigurationSet.prototype.get = function (r) {
                    return this.programConfigurations[r];
                }, ProgramConfigurationSet.prototype.upload = function (r) {
                    var t = this;
                    for (var o in t.programConfigurations) {
                        t.programConfigurations[o].upload(r);
                    }
                }, ProgramConfigurationSet.prototype.destroy = function () {
                    var r = this;
                    for (var t in r.programConfigurations) {
                        r.programConfigurations[t].destroy();
                    }
                }, register('ConstantBinder', ConstantBinder), register('SourceExpressionBinder', SourceExpressionBinder), register('CompositeExpressionBinder', CompositeExpressionBinder), register('ProgramConfiguration', ProgramConfiguration, { omit: ['_buffers'] }), register('ProgramConfigurationSet', ProgramConfigurationSet), module.exports = {
                    ProgramConfiguration: ProgramConfiguration,
                    ProgramConfigurationSet: ProgramConfigurationSet
                };
            },
            {
                '../shaders/encode_attribute': 96,
                '../style-spec/util/color': 153,
                '../style/properties': 188,
                '../util/web_worker_transfer': 278,
                './array_types': 39
            }
        ],
        59: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/struct_array'), createLayout = ref.createLayout;
                module.exports = createLayout([
                    {
                        name: 'a_pos',
                        type: 'Int16',
                        components: 2
                    },
                    {
                        name: 'a_texture_pos',
                        type: 'Int16',
                        components: 2
                    }
                ]);
            },
            { '../util/struct_array': 271 }
        ],
        60: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/util'), warnOnce = ref.warnOnce, ref$1 = _dereq_('../util/web_worker_transfer'), register = ref$1.register, MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1, SegmentVector = function (e) {
                        void 0 === e && (e = []), this.segments = e;
                    };
                SegmentVector.prototype.prepareSegment = function (e, t, r) {
                    var n = this.segments[this.segments.length - 1];
                    return e > MAX_VERTEX_ARRAY_LENGTH && warnOnce('Max vertices per segment is ' + MAX_VERTEX_ARRAY_LENGTH + ': bucket requested ' + e), (!n || n.vertexLength + e > module.exports.MAX_VERTEX_ARRAY_LENGTH) && (n = {
                        vertexOffset: t.length,
                        primitiveOffset: r.length,
                        vertexLength: 0,
                        primitiveLength: 0
                    }, this.segments.push(n)), n;
                }, SegmentVector.prototype.get = function () {
                    return this.segments;
                }, SegmentVector.prototype.destroy = function () {
                    for (var e = this, t = 0, r = e.segments; t < r.length; t += 1) {
                        var n = r[t];
                        for (var s in n.vaos) {
                            n.vaos[s].destroy();
                        }
                    }
                }, register('SegmentVector', SegmentVector), module.exports = {
                    SegmentVector: SegmentVector,
                    MAX_VERTEX_ARRAY_LENGTH: MAX_VERTEX_ARRAY_LENGTH
                };
            },
            {
                '../util/util': 275,
                '../util/web_worker_transfer': 278
            }
        ],
        61: [
            function (_dereq_, module, exports) {
                'use strict';
                var Coordinate = function (o, t, n) {
                    this.column = o, this.row = t, this.zoom = n;
                };
                Coordinate.prototype.clone = function () {
                    return new Coordinate(this.column, this.row, this.zoom);
                }, Coordinate.prototype.zoomTo = function (o) {
                    return this.clone()._zoomTo(o);
                }, Coordinate.prototype.sub = function (o) {
                    return this.clone()._sub(o);
                }, Coordinate.prototype._zoomTo = function (o) {
                    var t = Math.pow(2, o - this.zoom);
                    return this.column *= t, this.row *= t, this.zoom = o, this;
                }, Coordinate.prototype._sub = function (o) {
                    return o = o.zoomTo(this.zoom), this.column -= o.column, this.row -= o.row, this;
                }, module.exports = Coordinate;
            },
            {}
        ],
        62: [
            function (_dereq_, module, exports) {
                'use strict';
                var wrap = _dereq_('../util/util').wrap, LngLat = function (t, n) {
                        if (isNaN(t) || isNaN(n)) {
                            throw new Error('Invalid LngLat object: (' + t + ', ' + n + ')');
                        }
                        if (this.lng = +t, this.lat = +n, this.lat > 90 || this.lat < -90) {
                            throw new Error('Invalid LngLat latitude value: must be between -90 and 90');
                        }
                    };
                LngLat.prototype.wrap = function () {
                    return new LngLat(wrap(this.lng, -180, 180), this.lat);
                }, LngLat.prototype.toArray = function () {
                    return [
                        this.lng,
                        this.lat
                    ];
                }, LngLat.prototype.toString = function () {
                    return 'LngLat(' + this.lng + ', ' + this.lat + ')';
                }, LngLat.prototype.toBounds = function (t) {
                    var n = 360 * t / 40075017, r = n / Math.cos(Math.PI / 180 * this.lat);
                    return new (_dereq_('./lng_lat_bounds'))(new LngLat(this.lng - r, this.lat - n), new LngLat(this.lng + r, this.lat + n));
                }, LngLat.convert = function (t) {
                    if (t instanceof LngLat) {
                        return t;
                    }
                    if (Array.isArray(t) && (2 === t.length || 3 === t.length)) {
                        return new LngLat(Number(t[0]), Number(t[1]));
                    }
                    if (!Array.isArray(t) && 'object' == typeof t && null !== t) {
                        return new LngLat(Number(t.lng), Number(t.lat));
                    }
                    throw new Error('`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]');
                }, module.exports = LngLat;
            },
            {
                '../util/util': 275,
                './lng_lat_bounds': 63
            }
        ],
        63: [
            function (_dereq_, module, exports) {
                'use strict';
                var LngLat = _dereq_('./lng_lat'), LngLatBounds = function (t, n) {
                        t && (n ? this.setSouthWest(t).setNorthEast(n) : 4 === t.length ? this.setSouthWest([
                            t[0],
                            t[1]
                        ]).setNorthEast([
                            t[2],
                            t[3]
                        ]) : this.setSouthWest(t[0]).setNorthEast(t[1]));
                    };
                LngLatBounds.prototype.setNorthEast = function (t) {
                    return this._ne = t instanceof LngLat ? new LngLat(t.lng, t.lat) : LngLat.convert(t), this;
                }, LngLatBounds.prototype.setSouthWest = function (t) {
                    return this._sw = t instanceof LngLat ? new LngLat(t.lng, t.lat) : LngLat.convert(t), this;
                }, LngLatBounds.prototype.extend = function (t) {
                    var n, e, s = this._sw, o = this._ne;
                    if (t instanceof LngLat) {
                        n = t, e = t;
                    } else {
                        if (!(t instanceof LngLatBounds)) {
                            return Array.isArray(t) ? t.every(Array.isArray) ? this.extend(LngLatBounds.convert(t)) : this.extend(LngLat.convert(t)) : this;
                        }
                        if (n = t._sw, e = t._ne, !n || !e) {
                            return this;
                        }
                    }
                    return s || o ? (s.lng = Math.min(n.lng, s.lng), s.lat = Math.min(n.lat, s.lat), o.lng = Math.max(e.lng, o.lng), o.lat = Math.max(e.lat, o.lat)) : (this._sw = new LngLat(n.lng, n.lat), this._ne = new LngLat(e.lng, e.lat)), this;
                }, LngLatBounds.prototype.getCenter = function () {
                    return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);
                }, LngLatBounds.prototype.getSouthWest = function () {
                    return this._sw;
                }, LngLatBounds.prototype.getNorthEast = function () {
                    return this._ne;
                }, LngLatBounds.prototype.getNorthWest = function () {
                    return new LngLat(this.getWest(), this.getNorth());
                }, LngLatBounds.prototype.getSouthEast = function () {
                    return new LngLat(this.getEast(), this.getSouth());
                }, LngLatBounds.prototype.getWest = function () {
                    return this._sw.lng;
                }, LngLatBounds.prototype.getSouth = function () {
                    return this._sw.lat;
                }, LngLatBounds.prototype.getEast = function () {
                    return this._ne.lng;
                }, LngLatBounds.prototype.getNorth = function () {
                    return this._ne.lat;
                }, LngLatBounds.prototype.toArray = function () {
                    return [
                        this._sw.toArray(),
                        this._ne.toArray()
                    ];
                }, LngLatBounds.prototype.toString = function () {
                    return 'LngLatBounds(' + this._sw.toString() + ', ' + this._ne.toString() + ')';
                }, LngLatBounds.prototype.isEmpty = function () {
                    return !(this._sw && this._ne);
                }, LngLatBounds.convert = function (t) {
                    return !t || t instanceof LngLatBounds ? t : new LngLatBounds(t);
                }, module.exports = LngLatBounds;
            },
            { './lng_lat': 62 }
        ],
        64: [
            function (_dereq_, module, exports) {
                'use strict';
                var LngLat = _dereq_('./lng_lat'), Point = _dereq_('@mapbox/point-geometry'), Coordinate = _dereq_('./coordinate'), util = _dereq_('../util/util'), interp = _dereq_('../style-spec/util/interpolate').number, tileCover = _dereq_('../util/tile_cover'), ref = _dereq_('../source/tile_id'), CanonicalTileID = ref.CanonicalTileID, UnwrappedTileID = ref.UnwrappedTileID, EXTENT = _dereq_('../data/extent'), glmatrix = _dereq_('@mapbox/gl-matrix'), vec4 = glmatrix.vec4, mat4 = glmatrix.mat4, mat2 = glmatrix.mat2, Transform = function (t, i, o) {
                        this.tileSize = 512, this._renderWorldCopies = void 0 === o || o, this._minZoom = t || 0, this._maxZoom = i || 22, this.latRange = [
                            -85.05113,
                            85.05113
                        ], this.width = 0, this.height = 0, this._center = new LngLat(0, 0), this.zoom = 0, this.angle = 0, this._fov = 0.6435011087932844, this._pitch = 0, this._unmodified = !0, this._posMatrixCache = {}, this._alignedPosMatrixCache = {};
                    }, prototypeAccessors = {
                        minZoom: {},
                        maxZoom: {},
                        renderWorldCopies: {},
                        worldSize: {},
                        centerPoint: {},
                        size: {},
                        bearing: {},
                        pitch: {},
                        fov: {},
                        zoom: {},
                        center: {},
                        unmodified: {},
                        x: {},
                        y: {},
                        point: {}
                    };
                Transform.prototype.clone = function () {
                    var t = new Transform(this._minZoom, this._maxZoom, this._renderWorldCopies);
                    return t.tileSize = this.tileSize, t.latRange = this.latRange, t.width = this.width, t.height = this.height, t._center = this._center, t.zoom = this.zoom, t.angle = this.angle, t._fov = this._fov, t._pitch = this._pitch, t._unmodified = this._unmodified, t._calcMatrices(), t;
                }, prototypeAccessors.minZoom.get = function () {
                    return this._minZoom;
                }, prototypeAccessors.minZoom.set = function (t) {
                    this._minZoom !== t && (this._minZoom = t, this.zoom = Math.max(this.zoom, t));
                }, prototypeAccessors.maxZoom.get = function () {
                    return this._maxZoom;
                }, prototypeAccessors.maxZoom.set = function (t) {
                    this._maxZoom !== t && (this._maxZoom = t, this.zoom = Math.min(this.zoom, t));
                }, prototypeAccessors.renderWorldCopies.get = function () {
                    return this._renderWorldCopies;
                }, prototypeAccessors.worldSize.get = function () {
                    return this.tileSize * this.scale;
                }, prototypeAccessors.centerPoint.get = function () {
                    return this.size._div(2);
                }, prototypeAccessors.size.get = function () {
                    return new Point(this.width, this.height);
                }, prototypeAccessors.bearing.get = function () {
                    return -this.angle / Math.PI * 180;
                }, prototypeAccessors.bearing.set = function (t) {
                    var i = -util.wrap(t, -180, 180) * Math.PI / 180;
                    this.angle !== i && (this._unmodified = !1, this.angle = i, this._calcMatrices(), this.rotationMatrix = mat2.create(), mat2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle));
                }, prototypeAccessors.pitch.get = function () {
                    return this._pitch / Math.PI * 180;
                }, prototypeAccessors.pitch.set = function (t) {
                    var i = util.clamp(t, 0, 60) / 180 * Math.PI;
                    this._pitch !== i && (this._unmodified = !1, this._pitch = i, this._calcMatrices());
                }, prototypeAccessors.fov.get = function () {
                    return this._fov / Math.PI * 180;
                }, prototypeAccessors.fov.set = function (t) {
                    t = Math.max(0.01, Math.min(60, t)), this._fov !== t && (this._unmodified = !1, this._fov = t / 180 * Math.PI, this._calcMatrices());
                }, prototypeAccessors.zoom.get = function () {
                    return this._zoom;
                }, prototypeAccessors.zoom.set = function (t) {
                    var i = Math.min(Math.max(t, this.minZoom), this.maxZoom);
                    this._zoom !== i && (this._unmodified = !1, this._zoom = i, this.scale = this.zoomScale(i), this.tileZoom = Math.floor(i), this.zoomFraction = i - this.tileZoom, this._constrain(), this._calcMatrices());
                }, prototypeAccessors.center.get = function () {
                    return this._center;
                }, prototypeAccessors.center.set = function (t) {
                    t.lat === this._center.lat && t.lng === this._center.lng || (this._unmodified = !1, this._center = t, this._constrain(), this._calcMatrices());
                }, Transform.prototype.coveringZoomLevel = function (t) {
                    return (t.roundZoom ? Math.round : Math.floor)(this.zoom + this.scaleZoom(this.tileSize / t.tileSize));
                }, Transform.prototype.getVisibleUnwrappedCoordinates = function (t) {
                    var i = this.pointCoordinate(new Point(0, 0), 0), o = this.pointCoordinate(new Point(this.width, 0), 0), e = Math.floor(i.column), r = Math.floor(o.column), n = [new UnwrappedTileID(0, t)];
                    if (this._renderWorldCopies) {
                        for (var s = e; s <= r; s++) {
                            0 !== s && n.push(new UnwrappedTileID(s, t));
                        }
                    }
                    return n;
                }, Transform.prototype.coveringTiles = function (t) {
                    var i = this.coveringZoomLevel(t), o = i;
                    if (void 0 !== t.minzoom && i < t.minzoom) {
                        return [];
                    }
                    void 0 !== t.maxzoom && i > t.maxzoom && (i = t.maxzoom);
                    var e = this.pointCoordinate(this.centerPoint, i), r = new Point(e.column - 0.5, e.row - 0.5), n = [
                            this.pointCoordinate(new Point(0, 0), i),
                            this.pointCoordinate(new Point(this.width, 0), i),
                            this.pointCoordinate(new Point(this.width, this.height), i),
                            this.pointCoordinate(new Point(0, this.height), i)
                        ];
                    return tileCover(i, n, t.reparseOverscaled ? o : i, this._renderWorldCopies).sort(function (t, i) {
                        return r.dist(t.canonical) - r.dist(i.canonical);
                    });
                }, Transform.prototype.resize = function (t, i) {
                    this.width = t, this.height = i, this.pixelsToGLUnits = [
                        2 / t,
                        -2 / i
                    ], this._constrain(), this._calcMatrices();
                }, prototypeAccessors.unmodified.get = function () {
                    return this._unmodified;
                }, Transform.prototype.zoomScale = function (t) {
                    return Math.pow(2, t);
                }, Transform.prototype.scaleZoom = function (t) {
                    return Math.log(t) / Math.LN2;
                }, Transform.prototype.project = function (t) {
                    return new Point(this.lngX(t.lng), this.latY(t.lat));
                }, Transform.prototype.unproject = function (t) {
                    return new LngLat(this.xLng(t.x), this.yLat(t.y));
                }, prototypeAccessors.x.get = function () {
                    return this.lngX(this.center.lng);
                }, prototypeAccessors.y.get = function () {
                    return this.latY(this.center.lat);
                }, prototypeAccessors.point.get = function () {
                    return new Point(this.x, this.y);
                }, Transform.prototype.lngX = function (t) {
                    return (180 + t) * this.worldSize / 360;
                }, Transform.prototype.latY = function (t) {
                    return (180 - 180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + t * Math.PI / 360))) * this.worldSize / 360;
                }, Transform.prototype.xLng = function (t) {
                    return 360 * t / this.worldSize - 180;
                }, Transform.prototype.yLat = function (t) {
                    var i = 180 - 360 * t / this.worldSize;
                    return 360 / Math.PI * Math.atan(Math.exp(i * Math.PI / 180)) - 90;
                }, Transform.prototype.setLocationAtPoint = function (t, i) {
                    var o = this.pointCoordinate(i)._sub(this.pointCoordinate(this.centerPoint));
                    this.center = this.coordinateLocation(this.locationCoordinate(t)._sub(o)), this._renderWorldCopies && (this.center = this.center.wrap());
                }, Transform.prototype.locationPoint = function (t) {
                    return this.coordinatePoint(this.locationCoordinate(t));
                }, Transform.prototype.pointLocation = function (t) {
                    return this.coordinateLocation(this.pointCoordinate(t));
                }, Transform.prototype.locationCoordinate = function (t) {
                    return new Coordinate(this.lngX(t.lng) / this.tileSize, this.latY(t.lat) / this.tileSize, this.zoom).zoomTo(this.tileZoom);
                }, Transform.prototype.coordinateLocation = function (t) {
                    var i = t.zoomTo(this.zoom);
                    return new LngLat(this.xLng(i.column * this.tileSize), this.yLat(i.row * this.tileSize));
                }, Transform.prototype.pointCoordinate = function (t, i) {
                    void 0 === i && (i = this.tileZoom);
                    var o = [
                            t.x,
                            t.y,
                            0,
                            1
                        ], e = [
                            t.x,
                            t.y,
                            1,
                            1
                        ];
                    vec4.transformMat4(o, o, this.pixelMatrixInverse), vec4.transformMat4(e, e, this.pixelMatrixInverse);
                    var r = o[3], n = e[3], s = o[0] / r, a = e[0] / n, h = o[1] / r, c = e[1] / n, l = o[2] / r, m = e[2] / n, p = l === m ? 0 : (0 - l) / (m - l);
                    return new Coordinate(interp(s, a, p) / this.tileSize, interp(h, c, p) / this.tileSize, this.zoom)._zoomTo(i);
                }, Transform.prototype.coordinatePoint = function (t) {
                    var i = t.zoomTo(this.zoom), o = [
                            i.column * this.tileSize,
                            i.row * this.tileSize,
                            0,
                            1
                        ];
                    return vec4.transformMat4(o, o, this.pixelMatrix), new Point(o[0] / o[3], o[1] / o[3]);
                }, Transform.prototype.calculatePosMatrix = function (t, i) {
                    void 0 === i && (i = !1);
                    var o = t.key, e = i ? this._alignedPosMatrixCache : this._posMatrixCache;
                    if (e[o]) {
                        return e[o];
                    }
                    var r = t.canonical, n = this.worldSize / this.zoomScale(r.z), s = r.x + Math.pow(2, r.z) * t.wrap, a = mat4.identity(new Float64Array(16));
                    return mat4.translate(a, a, [
                        s * n,
                        r.y * n,
                        0
                    ]), mat4.scale(a, a, [
                        n / EXTENT,
                        n / EXTENT,
                        1
                    ]), mat4.multiply(a, i ? this.alignedProjMatrix : this.projMatrix, a), e[o] = new Float32Array(a), e[o];
                }, Transform.prototype._constrain = function () {
                    if (this.center && this.width && this.height && !this._constraining) {
                        this._constraining = !0;
                        var t, i, o, e, r = -90, n = 90, s = -180, a = 180, h = this.size, c = this._unmodified;
                        if (this.latRange) {
                            var l = this.latRange;
                            r = this.latY(l[1]), n = this.latY(l[0]), t = n - r < h.y ? h.y / (n - r) : 0;
                        }
                        if (this.lngRange) {
                            var m = this.lngRange;
                            s = this.lngX(m[0]), a = this.lngX(m[1]), i = a - s < h.x ? h.x / (a - s) : 0;
                        }
                        var p = Math.max(i || 0, t || 0);
                        if (p) {
                            return this.center = this.unproject(new Point(i ? (a + s) / 2 : this.x, t ? (n + r) / 2 : this.y)), this.zoom += this.scaleZoom(p), this._unmodified = c, void (this._constraining = !1);
                        }
                        if (this.latRange) {
                            var u = this.y, f = h.y / 2;
                            u - f < r && (e = r + f), u + f > n && (e = n - f);
                        }
                        if (this.lngRange) {
                            var d = this.x, g = h.x / 2;
                            d - g < s && (o = s + g), d + g > a && (o = a - g);
                        }
                        void 0 === o && void 0 === e || (this.center = this.unproject(new Point(void 0 !== o ? o : this.x, void 0 !== e ? e : this.y))), this._unmodified = c, this._constraining = !1;
                    }
                }, Transform.prototype._calcMatrices = function () {
                    if (this.height) {
                        this.cameraToCenterDistance = 0.5 / Math.tan(this._fov / 2) * this.height;
                        var t = this._fov / 2, i = Math.PI / 2 + this._pitch, o = Math.sin(t) * this.cameraToCenterDistance / Math.sin(Math.PI - i - t), e = this.x, r = this.y, n = Math.cos(Math.PI / 2 - this._pitch) * o + this.cameraToCenterDistance, s = 1.01 * n, a = new Float64Array(16);
                        mat4.perspective(a, this._fov, this.width / this.height, 1, s), mat4.scale(a, a, [
                            1,
                            -1,
                            1
                        ]), mat4.translate(a, a, [
                            0,
                            0,
                            -this.cameraToCenterDistance
                        ]), mat4.rotateX(a, a, this._pitch), mat4.rotateZ(a, a, this.angle), mat4.translate(a, a, [
                            -e,
                            -r,
                            0
                        ]);
                        var h = this.worldSize / (2 * Math.PI * 6378137 * Math.abs(Math.cos(this.center.lat * (Math.PI / 180))));
                        mat4.scale(a, a, [
                            1,
                            1,
                            h,
                            1
                        ]), this.projMatrix = a;
                        var c = this.width % 2 / 2, l = this.height % 2 / 2, m = Math.cos(this.angle), p = Math.sin(this.angle), u = e - Math.round(e) + m * c + p * l, f = r - Math.round(r) + m * l + p * c, d = new Float64Array(a);
                        if (mat4.translate(d, d, [
                                u > 0.5 ? u - 1 : u,
                                f > 0.5 ? f - 1 : f,
                                0
                            ]), this.alignedProjMatrix = d, a = mat4.create(), mat4.scale(a, a, [
                                this.width / 2,
                                -this.height / 2,
                                1
                            ]), mat4.translate(a, a, [
                                1,
                                -1,
                                0
                            ]), this.pixelMatrix = mat4.multiply(new Float64Array(16), a, this.projMatrix), !(a = mat4.invert(new Float64Array(16), this.pixelMatrix))) {
                            throw new Error('failed to invert matrix');
                        }
                        this.pixelMatrixInverse = a, this._posMatrixCache = {}, this._alignedPosMatrixCache = {};
                    }
                }, Object.defineProperties(Transform.prototype, prototypeAccessors), module.exports = Transform;
            },
            {
                '../data/extent': 53,
                '../source/tile_id': 114,
                '../style-spec/util/interpolate': 158,
                '../util/tile_cover': 273,
                '../util/util': 275,
                './coordinate': 61,
                './lng_lat': 62,
                '@mapbox/gl-matrix': 2,
                '@mapbox/point-geometry': 4
            }
        ],
        65: [
            function (_dereq_, module, exports) {
                'use strict';
                var Color = _dereq_('../style-spec/util/color'), ZERO = 0, ONE = 1, ONE_MINUS_SRC_ALPHA = 771, ColorMode = function (o, e, l) {
                        this.blendFunction = o, this.blendColor = e, this.mask = l;
                    };
                ColorMode.Replace = [
                    ONE,
                    ZERO
                ], ColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [
                    !1,
                    !1,
                    !1,
                    !1
                ]), ColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [
                    !0,
                    !0,
                    !0,
                    !0
                ]), ColorMode.alphaBlended = new ColorMode([
                    ONE,
                    ONE_MINUS_SRC_ALPHA
                ], Color.transparent, [
                    !0,
                    !0,
                    !0,
                    !0
                ]), module.exports = ColorMode;
            },
            { '../style-spec/util/color': 153 }
        ],
        66: [
            function (_dereq_, module, exports) {
                'use strict';
                var IndexBuffer = _dereq_('./index_buffer'), VertexBuffer = _dereq_('./vertex_buffer'), Framebuffer = _dereq_('./framebuffer'), DepthMode = _dereq_('./depth_mode'), StencilMode = _dereq_('./stencil_mode'), ColorMode = _dereq_('./color_mode'), util = _dereq_('../util/util'), ref = _dereq_('./value'), ClearColor = ref.ClearColor, ClearDepth = ref.ClearDepth, ClearStencil = ref.ClearStencil, ColorMask = ref.ColorMask, DepthMask = ref.DepthMask, StencilMask = ref.StencilMask, StencilFunc = ref.StencilFunc, StencilOp = ref.StencilOp, StencilTest = ref.StencilTest, DepthRange = ref.DepthRange, DepthTest = ref.DepthTest, DepthFunc = ref.DepthFunc, Blend = ref.Blend, BlendFunc = ref.BlendFunc, BlendColor = ref.BlendColor, Program = ref.Program, LineWidth = ref.LineWidth, ActiveTextureUnit = ref.ActiveTextureUnit, Viewport = ref.Viewport, BindFramebuffer = ref.BindFramebuffer, BindRenderbuffer = ref.BindRenderbuffer, BindTexture = ref.BindTexture, BindVertexBuffer = ref.BindVertexBuffer, BindElementBuffer = ref.BindElementBuffer, BindVertexArrayOES = ref.BindVertexArrayOES, PixelStoreUnpack = ref.PixelStoreUnpack, PixelStoreUnpackPremultiplyAlpha = ref.PixelStoreUnpackPremultiplyAlpha, Context = function (e) {
                        this.gl = e, this.extVertexArrayObject = this.gl.getExtension('OES_vertex_array_object'), this.lineWidthRange = e.getParameter(e.ALIASED_LINE_WIDTH_RANGE), this.clearColor = new ClearColor(this), this.clearDepth = new ClearDepth(this), this.clearStencil = new ClearStencil(this), this.colorMask = new ColorMask(this), this.depthMask = new DepthMask(this), this.stencilMask = new StencilMask(this), this.stencilFunc = new StencilFunc(this), this.stencilOp = new StencilOp(this), this.stencilTest = new StencilTest(this), this.depthRange = new DepthRange(this), this.depthTest = new DepthTest(this), this.depthFunc = new DepthFunc(this), this.blend = new Blend(this), this.blendFunc = new BlendFunc(this), this.blendColor = new BlendColor(this), this.program = new Program(this), this.lineWidth = new LineWidth(this), this.activeTexture = new ActiveTextureUnit(this), this.viewport = new Viewport(this), this.bindFramebuffer = new BindFramebuffer(this), this.bindRenderbuffer = new BindRenderbuffer(this), this.bindTexture = new BindTexture(this), this.bindVertexBuffer = new BindVertexBuffer(this), this.bindElementBuffer = new BindElementBuffer(this), this.bindVertexArrayOES = this.extVertexArrayObject && new BindVertexArrayOES(this), this.pixelStoreUnpack = new PixelStoreUnpack(this), this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this), this.extTextureFilterAnisotropic = e.getExtension('EXT_texture_filter_anisotropic') || e.getExtension('MOZ_EXT_texture_filter_anisotropic') || e.getExtension('WEBKIT_EXT_texture_filter_anisotropic'), this.extTextureFilterAnisotropic && (this.extTextureFilterAnisotropicMax = e.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT)), this.extTextureHalfFloat = e.getExtension('OES_texture_half_float'), this.extTextureHalfFloat && e.getExtension('OES_texture_half_float_linear');
                    };
                Context.prototype.createIndexBuffer = function (e, t) {
                    return new IndexBuffer(this, e, t);
                }, Context.prototype.createVertexBuffer = function (e, t, r) {
                    return new VertexBuffer(this, e, t, r);
                }, Context.prototype.createRenderbuffer = function (e, t, r) {
                    var i = this.gl, n = i.createRenderbuffer();
                    return this.bindRenderbuffer.set(n), i.renderbufferStorage(i.RENDERBUFFER, e, t, r), this.bindRenderbuffer.set(null), n;
                }, Context.prototype.createFramebuffer = function (e, t) {
                    return new Framebuffer(this, e, t);
                }, Context.prototype.clear = function (e) {
                    var t = e.color, r = e.depth, i = this.gl, n = 0;
                    t && (n |= i.COLOR_BUFFER_BIT, this.clearColor.set(t), this.colorMask.set([
                        !0,
                        !0,
                        !0,
                        !0
                    ])), void 0 !== r && (n |= i.DEPTH_BUFFER_BIT, this.clearDepth.set(r), this.depthMask.set(!0)), i.clear(n);
                }, Context.prototype.setDepthMode = function (e) {
                    e.func !== this.gl.ALWAYS || e.mask ? (this.depthTest.set(!0), this.depthFunc.set(e.func), this.depthMask.set(e.mask), this.depthRange.set(e.range)) : this.depthTest.set(!1);
                }, Context.prototype.setStencilMode = function (e) {
                    e.func !== this.gl.ALWAYS || e.mask ? (this.stencilTest.set(!0), this.stencilMask.set(e.mask), this.stencilOp.set([
                        e.fail,
                        e.depthFail,
                        e.pass
                    ]), this.stencilFunc.set({
                        func: e.test.func,
                        ref: e.ref,
                        mask: e.test.mask
                    })) : this.stencilTest.set(!1);
                }, Context.prototype.setColorMode = function (e) {
                    util.deepEqual(e.blendFunction, ColorMode.Replace) ? this.blend.set(!1) : (this.blend.set(!0), this.blendFunc.set(e.blendFunction), this.blendColor.set(e.blendColor)), this.colorMask.set(e.mask);
                }, module.exports = Context;
            },
            {
                '../util/util': 275,
                './color_mode': 65,
                './depth_mode': 67,
                './framebuffer': 68,
                './index_buffer': 69,
                './stencil_mode': 70,
                './value': 71,
                './vertex_buffer': 72
            }
        ],
        67: [
            function (_dereq_, module, exports) {
                'use strict';
                var ALWAYS = 519, DepthMode = function (e, t, d) {
                        this.func = e, this.mask = t, this.range = d;
                    };
                DepthMode.ReadOnly = !1, DepthMode.ReadWrite = !0, DepthMode.disabled = new DepthMode(ALWAYS, DepthMode.ReadOnly, [
                    0,
                    1
                ]), module.exports = DepthMode;
            },
            {}
        ],
        68: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('./value'), ColorAttachment = ref.ColorAttachment, DepthAttachment = ref.DepthAttachment, Framebuffer = function (t, e, r) {
                        this.context = t, this.width = e, this.height = r;
                        var h = t.gl, a = this.framebuffer = h.createFramebuffer();
                        this.colorAttachment = new ColorAttachment(t, a), this.depthAttachment = new DepthAttachment(t, a);
                    };
                Framebuffer.prototype.destroy = function () {
                    var t = this.context.gl, e = this.colorAttachment.get();
                    e && t.deleteTexture(e);
                    var r = this.depthAttachment.get();
                    r && t.deleteRenderbuffer(r), t.deleteFramebuffer(this.framebuffer);
                }, module.exports = Framebuffer;
            },
            { './value': 71 }
        ],
        69: [
            function (_dereq_, module, exports) {
                'use strict';
                var IndexBuffer = function (e, t, r) {
                    this.context = e;
                    var f = e.gl;
                    this.buffer = f.createBuffer(), this.dynamicDraw = Boolean(r), this.unbindVAO(), e.bindElementBuffer.set(this.buffer), f.bufferData(f.ELEMENT_ARRAY_BUFFER, t.arrayBuffer, this.dynamicDraw ? f.DYNAMIC_DRAW : f.STATIC_DRAW), this.dynamicDraw || delete t.arrayBuffer;
                };
                IndexBuffer.prototype.unbindVAO = function () {
                    this.context.extVertexArrayObject && this.context.bindVertexArrayOES.set(null);
                }, IndexBuffer.prototype.bind = function () {
                    this.context.bindElementBuffer.set(this.buffer);
                }, IndexBuffer.prototype.updateData = function (e) {
                    var t = this.context.gl;
                    this.unbindVAO(), this.bind(), t.bufferSubData(t.ELEMENT_ARRAY_BUFFER, 0, e.arrayBuffer);
                }, IndexBuffer.prototype.destroy = function () {
                    var e = this.context.gl;
                    this.buffer && (e.deleteBuffer(this.buffer), delete this.buffer);
                }, module.exports = IndexBuffer;
            },
            {}
        ],
        70: [
            function (_dereq_, module, exports) {
                'use strict';
                var ALWAYS = 519, KEEP = 7680, StencilMode = function (t, e, i, s, d, l) {
                        this.test = t, this.ref = e, this.mask = i, this.fail = s, this.depthFail = d, this.pass = l;
                    };
                StencilMode.disabled = new StencilMode({
                    func: ALWAYS,
                    mask: 0
                }, 0, 0, KEEP, KEEP, KEEP), module.exports = StencilMode;
            },
            {}
        ],
        71: [
            function (_dereq_, module, exports) {
                'use strict';
                var Color = _dereq_('../style-spec/util/color'), util = _dereq_('../util/util'), ClearColor = function (t) {
                        this.context = t, this.current = Color.transparent;
                    };
                ClearColor.prototype.get = function () {
                    return this.current;
                }, ClearColor.prototype.set = function (t) {
                    var e = this.current;
                    t.r === e.r && t.g === e.g && t.b === e.b && t.a === e.a || (this.context.gl.clearColor(t.r, t.g, t.b, t.a), this.current = t);
                };
                var ClearDepth = function (t) {
                    this.context = t, this.current = 1;
                };
                ClearDepth.prototype.get = function () {
                    return this.current;
                }, ClearDepth.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.clearDepth(t), this.current = t);
                };
                var ClearStencil = function (t) {
                    this.context = t, this.current = 0;
                };
                ClearStencil.prototype.get = function () {
                    return this.current;
                }, ClearStencil.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.clearStencil(t), this.current = t);
                };
                var ColorMask = function (t) {
                    this.context = t, this.current = [
                        !0,
                        !0,
                        !0,
                        !0
                    ];
                };
                ColorMask.prototype.get = function () {
                    return this.current;
                }, ColorMask.prototype.set = function (t) {
                    var e = this.current;
                    t[0] === e[0] && t[1] === e[1] && t[2] === e[2] && t[3] === e[3] || (this.context.gl.colorMask(t[0], t[1], t[2], t[3]), this.current = t);
                };
                var DepthMask = function (t) {
                    this.context = t, this.current = !0;
                };
                DepthMask.prototype.get = function () {
                    return this.current;
                }, DepthMask.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.depthMask(t), this.current = t);
                };
                var StencilMask = function (t) {
                    this.context = t, this.current = 255;
                };
                StencilMask.prototype.get = function () {
                    return this.current;
                }, StencilMask.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.stencilMask(t), this.current = t);
                };
                var StencilFunc = function (t) {
                    this.context = t, this.current = {
                        func: t.gl.ALWAYS,
                        ref: 0,
                        mask: 255
                    };
                };
                StencilFunc.prototype.get = function () {
                    return this.current;
                }, StencilFunc.prototype.set = function (t) {
                    var e = this.current;
                    t.func === e.func && t.ref === e.ref && t.mask === e.mask || (this.context.gl.stencilFunc(t.func, t.ref, t.mask), this.current = t);
                };
                var StencilOp = function (t) {
                    this.context = t;
                    var e = this.context.gl;
                    this.current = [
                        e.KEEP,
                        e.KEEP,
                        e.KEEP
                    ];
                };
                StencilOp.prototype.get = function () {
                    return this.current;
                }, StencilOp.prototype.set = function (t) {
                    var e = this.current;
                    t[0] === e[0] && t[1] === e[1] && t[2] === e[2] || (this.context.gl.stencilOp(t[0], t[1], t[2]), this.current = t);
                };
                var StencilTest = function (t) {
                    this.context = t, this.current = !1;
                };
                StencilTest.prototype.get = function () {
                    return this.current;
                }, StencilTest.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        t ? e.enable(e.STENCIL_TEST) : e.disable(e.STENCIL_TEST), this.current = t;
                    }
                };
                var DepthRange = function (t) {
                    this.context = t, this.current = [
                        0,
                        1
                    ];
                };
                DepthRange.prototype.get = function () {
                    return this.current;
                }, DepthRange.prototype.set = function (t) {
                    var e = this.current;
                    t[0] === e[0] && t[1] === e[1] || (this.context.gl.depthRange(t[0], t[1]), this.current = t);
                };
                var DepthTest = function (t) {
                    this.context = t, this.current = !1;
                };
                DepthTest.prototype.get = function () {
                    return this.current;
                }, DepthTest.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        t ? e.enable(e.DEPTH_TEST) : e.disable(e.DEPTH_TEST), this.current = t;
                    }
                };
                var DepthFunc = function (t) {
                    this.context = t, this.current = t.gl.LESS;
                };
                DepthFunc.prototype.get = function () {
                    return this.current;
                }, DepthFunc.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.depthFunc(t), this.current = t);
                };
                var Blend = function (t) {
                    this.context = t, this.current = !1;
                };
                Blend.prototype.get = function () {
                    return this.current;
                }, Blend.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        t ? e.enable(e.BLEND) : e.disable(e.BLEND), this.current = t;
                    }
                };
                var BlendFunc = function (t) {
                    this.context = t;
                    var e = this.context.gl;
                    this.current = [
                        e.ONE,
                        e.ZERO
                    ];
                };
                BlendFunc.prototype.get = function () {
                    return this.current;
                }, BlendFunc.prototype.set = function (t) {
                    var e = this.current;
                    t[0] === e[0] && t[1] === e[1] || (this.context.gl.blendFunc(t[0], t[1]), this.current = t);
                };
                var BlendColor = function (t) {
                    this.context = t, this.current = Color.transparent;
                };
                BlendColor.prototype.get = function () {
                    return this.current;
                }, BlendColor.prototype.set = function (t) {
                    var e = this.current;
                    t.r === e.r && t.g === e.g && t.b === e.b && t.a === e.a || (this.context.gl.blendColor(t.r, t.g, t.b, t.a), this.current = t);
                };
                var Program = function (t) {
                    this.context = t, this.current = null;
                };
                Program.prototype.get = function () {
                    return this.current;
                }, Program.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.useProgram(t), this.current = t);
                };
                var LineWidth = function (t) {
                    this.context = t, this.current = 1;
                };
                LineWidth.prototype.get = function () {
                    return this.current;
                }, LineWidth.prototype.set = function (t) {
                    var e = this.context.lineWidthRange, r = util.clamp(t, e[0], e[1]);
                    this.current !== r && (this.context.gl.lineWidth(r), this.current = t);
                };
                var ActiveTextureUnit = function (t) {
                    this.context = t, this.current = t.gl.TEXTURE0;
                };
                ActiveTextureUnit.prototype.get = function () {
                    return this.current;
                }, ActiveTextureUnit.prototype.set = function (t) {
                    this.current !== t && (this.context.gl.activeTexture(t), this.current = t);
                };
                var Viewport = function (t) {
                    this.context = t;
                    var e = this.context.gl;
                    this.current = [
                        0,
                        0,
                        e.drawingBufferWidth,
                        e.drawingBufferHeight
                    ];
                };
                Viewport.prototype.get = function () {
                    return this.current;
                }, Viewport.prototype.set = function (t) {
                    var e = this.current;
                    t[0] === e[0] && t[1] === e[1] && t[2] === e[2] && t[3] === e[3] || (this.context.gl.viewport(t[0], t[1], t[2], t[3]), this.current = t);
                };
                var BindFramebuffer = function (t) {
                    this.context = t, this.current = null;
                };
                BindFramebuffer.prototype.get = function () {
                    return this.current;
                }, BindFramebuffer.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        e.bindFramebuffer(e.FRAMEBUFFER, t), this.current = t;
                    }
                };
                var BindRenderbuffer = function (t) {
                    this.context = t, this.current = null;
                };
                BindRenderbuffer.prototype.get = function () {
                    return this.current;
                }, BindRenderbuffer.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        e.bindRenderbuffer(e.RENDERBUFFER, t), this.current = t;
                    }
                };
                var BindTexture = function (t) {
                    this.context = t, this.current = null;
                };
                BindTexture.prototype.get = function () {
                    return this.current;
                }, BindTexture.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        e.bindTexture(e.TEXTURE_2D, t), this.current = t;
                    }
                };
                var BindVertexBuffer = function (t) {
                    this.context = t, this.current = null;
                };
                BindVertexBuffer.prototype.get = function () {
                    return this.current;
                }, BindVertexBuffer.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        e.bindBuffer(e.ARRAY_BUFFER, t), this.current = t;
                    }
                };
                var BindElementBuffer = function (t) {
                    this.context = t, this.current = null;
                };
                BindElementBuffer.prototype.get = function () {
                    return this.current;
                }, BindElementBuffer.prototype.set = function (t) {
                    var e = this.context.gl;
                    e.bindBuffer(e.ELEMENT_ARRAY_BUFFER, t), this.current = t;
                };
                var BindVertexArrayOES = function (t) {
                    this.context = t, this.current = null;
                };
                BindVertexArrayOES.prototype.get = function () {
                    return this.current;
                }, BindVertexArrayOES.prototype.set = function (t) {
                    this.current !== t && this.context.extVertexArrayObject && (this.context.extVertexArrayObject.bindVertexArrayOES(t), this.current = t);
                };
                var PixelStoreUnpack = function (t) {
                    this.context = t, this.current = 4;
                };
                PixelStoreUnpack.prototype.get = function () {
                    return this.current;
                }, PixelStoreUnpack.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        e.pixelStorei(e.UNPACK_ALIGNMENT, t), this.current = t;
                    }
                };
                var PixelStoreUnpackPremultiplyAlpha = function (t) {
                    this.context = t, this.current = !1;
                };
                PixelStoreUnpackPremultiplyAlpha.prototype.get = function () {
                    return this.current;
                }, PixelStoreUnpackPremultiplyAlpha.prototype.set = function (t) {
                    if (this.current !== t) {
                        var e = this.context.gl;
                        e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL, t), this.current = t;
                    }
                };
                var FramebufferValue = function (t, e) {
                    this.context = t, this.current = null, this.parent = e;
                };
                FramebufferValue.prototype.get = function () {
                    return this.current;
                };
                var ColorAttachment = function (t) {
                        function e(e, r) {
                            t.call(this, e, r), this.dirty = !1;
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.set = function (t) {
                            if (this.dirty || this.current !== t) {
                                var e = this.context.gl;
                                this.context.bindFramebuffer.set(this.parent), e.framebufferTexture2D(e.FRAMEBUFFER, e.COLOR_ATTACHMENT0, e.TEXTURE_2D, t, 0), this.current = t, this.dirty = !1;
                            }
                        }, e.prototype.setDirty = function () {
                            this.dirty = !0;
                        }, e;
                    }(FramebufferValue), DepthAttachment = function (t) {
                        function e() {
                            t.apply(this, arguments);
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.set = function (t) {
                            if (this.current !== t) {
                                var e = this.context.gl;
                                this.context.bindFramebuffer.set(this.parent), e.framebufferRenderbuffer(e.FRAMEBUFFER, e.DEPTH_ATTACHMENT, e.RENDERBUFFER, t), this.current = t;
                            }
                        }, e;
                    }(FramebufferValue);
                module.exports = {
                    ClearColor: ClearColor,
                    ClearDepth: ClearDepth,
                    ClearStencil: ClearStencil,
                    ColorMask: ColorMask,
                    DepthMask: DepthMask,
                    StencilMask: StencilMask,
                    StencilFunc: StencilFunc,
                    StencilOp: StencilOp,
                    StencilTest: StencilTest,
                    DepthRange: DepthRange,
                    DepthTest: DepthTest,
                    DepthFunc: DepthFunc,
                    Blend: Blend,
                    BlendFunc: BlendFunc,
                    BlendColor: BlendColor,
                    Program: Program,
                    LineWidth: LineWidth,
                    ActiveTextureUnit: ActiveTextureUnit,
                    Viewport: Viewport,
                    BindFramebuffer: BindFramebuffer,
                    BindRenderbuffer: BindRenderbuffer,
                    BindTexture: BindTexture,
                    BindVertexBuffer: BindVertexBuffer,
                    BindElementBuffer: BindElementBuffer,
                    BindVertexArrayOES: BindVertexArrayOES,
                    PixelStoreUnpack: PixelStoreUnpack,
                    PixelStoreUnpackPremultiplyAlpha: PixelStoreUnpackPremultiplyAlpha,
                    ColorAttachment: ColorAttachment,
                    DepthAttachment: DepthAttachment
                };
            },
            {
                '../style-spec/util/color': 153,
                '../util/util': 275
            }
        ],
        72: [
            function (_dereq_, module, exports) {
                'use strict';
                var AttributeType = {
                        Int8: 'BYTE',
                        Uint8: 'UNSIGNED_BYTE',
                        Int16: 'SHORT',
                        Uint16: 'UNSIGNED_SHORT',
                        Int32: 'INT',
                        Uint32: 'UNSIGNED_INT',
                        Float32: 'FLOAT'
                    }, VertexBuffer = function (t, e, r, i) {
                        this.length = e.length, this.attributes = r, this.itemSize = e.bytesPerElement, this.dynamicDraw = i, this.context = t;
                        var f = t.gl;
                        this.buffer = f.createBuffer(), t.bindVertexBuffer.set(this.buffer), f.bufferData(f.ARRAY_BUFFER, e.arrayBuffer, this.dynamicDraw ? f.DYNAMIC_DRAW : f.STATIC_DRAW), this.dynamicDraw || delete e.arrayBuffer;
                    };
                VertexBuffer.prototype.bind = function () {
                    this.context.bindVertexBuffer.set(this.buffer);
                }, VertexBuffer.prototype.updateData = function (t) {
                    var e = this.context.gl;
                    this.bind(), e.bufferSubData(e.ARRAY_BUFFER, 0, t.arrayBuffer);
                }, VertexBuffer.prototype.enableAttributes = function (t, e) {
                    for (var r = this, i = 0; i < this.attributes.length; i++) {
                        var f = r.attributes[i], n = e.attributes[f.name];
                        void 0 !== n && t.enableVertexAttribArray(n);
                    }
                }, VertexBuffer.prototype.setVertexAttribPointers = function (t, e, r) {
                    for (var i = this, f = 0; f < this.attributes.length; f++) {
                        var n = i.attributes[f], u = e.attributes[n.name];
                        void 0 !== u && t.vertexAttribPointer(u, n.components, t[AttributeType[n.type]], !1, i.itemSize, n.offset + i.itemSize * (r || 0));
                    }
                }, VertexBuffer.prototype.destroy = function () {
                    var t = this.context.gl;
                    this.buffer && (t.deleteBuffer(this.buffer), delete this.buffer);
                }, module.exports = VertexBuffer;
            },
            {}
        ],
        73: [
            function (_dereq_, module, exports) {
                'use strict';
                var supported = _dereq_('@mapbox/mapbox-gl-supported'), browser = _dereq_('./util/browser'), version = _dereq_('../package.json').version, Map = _dereq_('./ui/map'), NavigationControl = _dereq_('./ui/control/navigation_control'), GeolocateControl = _dereq_('./ui/control/geolocate_control'), AttributionControl = _dereq_('./ui/control/attribution_control'), ScaleControl = _dereq_('./ui/control/scale_control'), FullscreenControl = _dereq_('./ui/control/fullscreen_control'), Popup = _dereq_('./ui/popup'), Marker = _dereq_('./ui/marker'), Style = _dereq_('./style/style'), LngLat = _dereq_('./geo/lng_lat'), LngLatBounds = _dereq_('./geo/lng_lat_bounds'), Point = _dereq_('@mapbox/point-geometry'), Evented = _dereq_('./util/evented'), config = _dereq_('./util/config'), rtlTextPlugin = _dereq_('./source/rtl_text_plugin');
                module.exports = {
                    version: version,
                    supported: supported,
                    workerCount: Math.max(Math.floor(browser.hardwareConcurrency / 2), 1),
                    setRTLTextPlugin: rtlTextPlugin.setRTLTextPlugin,
                    Map: Map,
                    NavigationControl: NavigationControl,
                    GeolocateControl: GeolocateControl,
                    AttributionControl: AttributionControl,
                    ScaleControl: ScaleControl,
                    FullscreenControl: FullscreenControl,
                    Popup: Popup,
                    Marker: Marker,
                    Style: Style,
                    LngLat: LngLat,
                    LngLatBounds: LngLatBounds,
                    Point: Point,
                    Evented: Evented,
                    config: config,
                    get accessToken() {
                        return config.ACCESS_TOKEN;
                    },
                    set accessToken(o) {
                        config.ACCESS_TOKEN = o;
                    }
                };
            },
            {
                '../package.json': 38,
                './geo/lng_lat': 62,
                './geo/lng_lat_bounds': 63,
                './source/rtl_text_plugin': 109,
                './style/style': 190,
                './ui/control/attribution_control': 232,
                './ui/control/fullscreen_control': 233,
                './ui/control/geolocate_control': 234,
                './ui/control/navigation_control': 236,
                './ui/control/scale_control': 237,
                './ui/map': 247,
                './ui/marker': 248,
                './ui/popup': 249,
                './util/browser': 252,
                './util/config': 256,
                './util/evented': 260,
                '@mapbox/mapbox-gl-supported': 3,
                '@mapbox/point-geometry': 4
            }
        ],
        74: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawBackground(e, t, r) {
                    var a = r.paint.get('background-color'), n = r.paint.get('background-opacity');
                    if (0 !== n) {
                        var o = e.context, i = o.gl, d = e.transform, u = d.tileSize, l = r.paint.get('background-pattern'), s = l || 1 !== a.a || 1 !== n ? 'translucent' : 'opaque';
                        if (e.renderPass === s) {
                            o.setStencilMode(StencilMode.disabled), o.setDepthMode(e.depthModeForSublayer(0, 'opaque' === s ? DepthMode.ReadWrite : DepthMode.ReadOnly)), o.setColorMode(e.colorModeForRenderPass());
                            var p;
                            if (l) {
                                if (pattern.isPatternMissing(l, e)) {
                                    return;
                                }
                                p = e.useProgram('backgroundPattern'), pattern.prepare(l, e, p), e.tileExtentPatternVAO.bind(o, p, e.tileExtentBuffer, []);
                            } else {
                                p = e.useProgram('background'), i.uniform4fv(p.uniforms.u_color, [
                                    a.r,
                                    a.g,
                                    a.b,
                                    a.a
                                ]), e.tileExtentVAO.bind(o, p, e.tileExtentBuffer, []);
                            }
                            i.uniform1f(p.uniforms.u_opacity, n);
                            for (var c = d.coveringTiles({ tileSize: u }), f = 0, g = c; f < g.length; f += 1) {
                                var m = g[f];
                                l && pattern.setTile({
                                    tileID: m,
                                    tileSize: u
                                }, e, p), i.uniformMatrix4fv(p.uniforms.u_matrix, !1, e.transform.calculatePosMatrix(m.toUnwrapped())), i.drawArrays(i.TRIANGLE_STRIP, 0, e.tileExtentBuffer.length);
                            }
                        }
                    }
                }
                var pattern = _dereq_('./pattern'), StencilMode = _dereq_('../gl/stencil_mode'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = drawBackground;
            },
            {
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                './pattern': 91
            }
        ],
        75: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawCircles(e, t, r, i) {
                    if ('translucent' === e.renderPass) {
                        var o = r.paint.get('circle-opacity'), a = r.paint.get('circle-stroke-width'), n = r.paint.get('circle-stroke-opacity');
                        if (0 !== o.constantOr(1) || 0 !== a.constantOr(1) && 0 !== n.constantOr(1)) {
                            var s = e.context, c = s.gl;
                            s.setDepthMode(e.depthModeForSublayer(0, DepthMode.ReadOnly)), s.setStencilMode(StencilMode.disabled), s.setColorMode(e.colorModeForRenderPass());
                            for (var l = !0, m = 0; m < i.length; m++) {
                                var u = i[m], f = t.getTile(u), p = f.getBucket(r);
                                if (p) {
                                    var d = e.context.program.get(), _ = p.programConfigurations.get(r.id), g = e.useProgram('circle', _);
                                    if ((l || g.program !== d) && (_.setUniforms(s, g, r.paint, { zoom: e.transform.zoom }), l = !1), c.uniform1f(g.uniforms.u_camera_to_center_distance, e.transform.cameraToCenterDistance), c.uniform1i(g.uniforms.u_scale_with_map, 'map' === r.paint.get('circle-pitch-scale') ? 1 : 0), 'map' === r.paint.get('circle-pitch-alignment')) {
                                        c.uniform1i(g.uniforms.u_pitch_with_map, 1);
                                        var h = pixelsToTileUnits(f, 1, e.transform.zoom);
                                        c.uniform2f(g.uniforms.u_extrude_scale, h, h);
                                    } else {
                                        c.uniform1i(g.uniforms.u_pitch_with_map, 0), c.uniform2fv(g.uniforms.u_extrude_scale, e.transform.pixelsToGLUnits);
                                    }
                                    c.uniformMatrix4fv(g.uniforms.u_matrix, !1, e.translatePosMatrix(u.posMatrix, f, r.paint.get('circle-translate'), r.paint.get('circle-translate-anchor'))), g.draw(s, c.TRIANGLES, r.id, p.layoutVertexBuffer, p.indexBuffer, p.segments, _);
                                }
                            }
                        }
                    }
                }
                var pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), StencilMode = _dereq_('../gl/stencil_mode'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = drawCircles;
            },
            {
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../source/pixels_to_tile_units': 104
            }
        ],
        76: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawCollisionDebugGeometry(e, o, i, r, t) {
                    var l = e.context, s = l.gl, n = t ? e.useProgram('collisionCircle') : e.useProgram('collisionBox');
                    l.setDepthMode(DepthMode.disabled), l.setStencilMode(StencilMode.disabled), l.setColorMode(e.colorModeForRenderPass());
                    for (var u = 0; u < r.length; u++) {
                        var a = r[u], d = o.getTile(a), f = d.getBucket(i);
                        if (f) {
                            var m = t ? f.collisionCircle : f.collisionBox;
                            if (m) {
                                s.uniformMatrix4fv(n.uniforms.u_matrix, !1, a.posMatrix), t || l.lineWidth.set(1), s.uniform1f(n.uniforms.u_camera_to_center_distance, e.transform.cameraToCenterDistance);
                                var c = pixelsToTileUnits(d, 1, e.transform.zoom), x = Math.pow(2, e.transform.zoom - d.tileID.overscaledZ);
                                s.uniform1f(n.uniforms.u_pixels_to_tile_units, c), s.uniform2f(n.uniforms.u_extrude_scale, e.transform.pixelsToGLUnits[0] / (c * x), e.transform.pixelsToGLUnits[1] / (c * x)), n.draw(l, t ? s.TRIANGLES : s.LINES, i.id, m.layoutVertexBuffer, m.indexBuffer, m.segments, null, m.collisionVertexBuffer, null);
                            }
                        }
                    }
                }
                function drawCollisionDebug(e, o, i, r) {
                    drawCollisionDebugGeometry(e, o, i, r, !1), drawCollisionDebugGeometry(e, o, i, r, !0);
                }
                var pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), DepthMode = _dereq_('../gl/depth_mode'), StencilMode = _dereq_('../gl/stencil_mode');
                module.exports = drawCollisionDebug;
            },
            {
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../source/pixels_to_tile_units': 104
            }
        ],
        77: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawDebug(e, r, t) {
                    for (var o = 0; o < t.length; o++) {
                        drawDebugTile(e, r, t[o]);
                    }
                }
                function drawDebugTile(e, r, t) {
                    var o = e.context, a = o.gl;
                    o.lineWidth.set(1 * browser.devicePixelRatio);
                    var i = t.posMatrix, u = e.useProgram('debug');
                    o.setDepthMode(DepthMode.disabled), o.setStencilMode(StencilMode.disabled), o.setColorMode(e.colorModeForRenderPass()), a.uniformMatrix4fv(u.uniforms.u_matrix, !1, i), a.uniform4f(u.uniforms.u_color, 1, 0, 0, 1), e.debugVAO.bind(o, u, e.debugBuffer, []), a.drawArrays(a.LINE_STRIP, 0, e.debugBuffer.length);
                    for (var n = createTextVerticies(t.toString(), 50, 200, 5), s = new PosArray(), l = 0; l < n.length; l += 2) {
                        s.emplaceBack(n[l], n[l + 1]);
                    }
                    var d = o.createVertexBuffer(s, posAttributes.members);
                    new VertexArrayObject().bind(o, u, d, []), a.uniform4f(u.uniforms.u_color, 1, 1, 1, 1);
                    for (var f = r.getTile(t).tileSize, m = EXTENT / (Math.pow(2, e.transform.zoom - t.overscaledZ) * f), c = [
                                [
                                    -1,
                                    -1
                                ],
                                [
                                    -1,
                                    1
                                ],
                                [
                                    1,
                                    -1
                                ],
                                [
                                    1,
                                    1
                                ]
                            ], b = 0; b < c.length; b++) {
                        var g = c[b];
                        a.uniformMatrix4fv(u.uniforms.u_matrix, !1, mat4.translate([], i, [
                            m * g[0],
                            m * g[1],
                            0
                        ])), a.drawArrays(a.LINES, 0, d.length);
                    }
                    a.uniform4f(u.uniforms.u_color, 0, 0, 0, 1), a.uniformMatrix4fv(u.uniforms.u_matrix, !1, i), a.drawArrays(a.LINES, 0, d.length);
                }
                function createTextVerticies(e, r, t, o) {
                    o = o || 1;
                    var a, i, u, n, s, l, d, f, m = [];
                    for (a = 0, i = e.length; a < i; a++) {
                        if (s = simplexFont[e[a]]) {
                            for (f = null, u = 0, n = s[1].length; u < n; u += 2) {
                                -1 === s[1][u] && -1 === s[1][u + 1] ? f = null : (l = r + s[1][u] * o, d = t - s[1][u + 1] * o, f && m.push(f.x, f.y, l, d), f = {
                                    x: l,
                                    y: d
                                });
                            }
                            r += s[0] * o;
                        }
                    }
                    return m;
                }
                var browser = _dereq_('../util/browser'), mat4 = _dereq_('@mapbox/gl-matrix').mat4, EXTENT = _dereq_('../data/extent'), VertexArrayObject = _dereq_('./vertex_array_object'), ref = _dereq_('../data/array_types'), PosArray = ref.PosArray, posAttributes = _dereq_('../data/pos_attributes'), DepthMode = _dereq_('../gl/depth_mode'), StencilMode = _dereq_('../gl/stencil_mode');
                module.exports = drawDebug;
                var simplexFont = {
                    ' ': [
                        16,
                        []
                    ],
                    '!': [
                        10,
                        [
                            5,
                            21,
                            5,
                            7,
                            -1,
                            -1,
                            5,
                            2,
                            4,
                            1,
                            5,
                            0,
                            6,
                            1,
                            5,
                            2
                        ]
                    ],
                    '"': [
                        16,
                        [
                            4,
                            21,
                            4,
                            14,
                            -1,
                            -1,
                            12,
                            21,
                            12,
                            14
                        ]
                    ],
                    '#': [
                        21,
                        [
                            11,
                            25,
                            4,
                            -7,
                            -1,
                            -1,
                            17,
                            25,
                            10,
                            -7,
                            -1,
                            -1,
                            4,
                            12,
                            18,
                            12,
                            -1,
                            -1,
                            3,
                            6,
                            17,
                            6
                        ]
                    ],
                    $: [
                        20,
                        [
                            8,
                            25,
                            8,
                            -4,
                            -1,
                            -1,
                            12,
                            25,
                            12,
                            -4,
                            -1,
                            -1,
                            17,
                            18,
                            15,
                            20,
                            12,
                            21,
                            8,
                            21,
                            5,
                            20,
                            3,
                            18,
                            3,
                            16,
                            4,
                            14,
                            5,
                            13,
                            7,
                            12,
                            13,
                            10,
                            15,
                            9,
                            16,
                            8,
                            17,
                            6,
                            17,
                            3,
                            15,
                            1,
                            12,
                            0,
                            8,
                            0,
                            5,
                            1,
                            3,
                            3
                        ]
                    ],
                    '%': [
                        24,
                        [
                            21,
                            21,
                            3,
                            0,
                            -1,
                            -1,
                            8,
                            21,
                            10,
                            19,
                            10,
                            17,
                            9,
                            15,
                            7,
                            14,
                            5,
                            14,
                            3,
                            16,
                            3,
                            18,
                            4,
                            20,
                            6,
                            21,
                            8,
                            21,
                            10,
                            20,
                            13,
                            19,
                            16,
                            19,
                            19,
                            20,
                            21,
                            21,
                            -1,
                            -1,
                            17,
                            7,
                            15,
                            6,
                            14,
                            4,
                            14,
                            2,
                            16,
                            0,
                            18,
                            0,
                            20,
                            1,
                            21,
                            3,
                            21,
                            5,
                            19,
                            7,
                            17,
                            7
                        ]
                    ],
                    '&': [
                        26,
                        [
                            23,
                            12,
                            23,
                            13,
                            22,
                            14,
                            21,
                            14,
                            20,
                            13,
                            19,
                            11,
                            17,
                            6,
                            15,
                            3,
                            13,
                            1,
                            11,
                            0,
                            7,
                            0,
                            5,
                            1,
                            4,
                            2,
                            3,
                            4,
                            3,
                            6,
                            4,
                            8,
                            5,
                            9,
                            12,
                            13,
                            13,
                            14,
                            14,
                            16,
                            14,
                            18,
                            13,
                            20,
                            11,
                            21,
                            9,
                            20,
                            8,
                            18,
                            8,
                            16,
                            9,
                            13,
                            11,
                            10,
                            16,
                            3,
                            18,
                            1,
                            20,
                            0,
                            22,
                            0,
                            23,
                            1,
                            23,
                            2
                        ]
                    ],
                    '\'': [
                        10,
                        [
                            5,
                            19,
                            4,
                            20,
                            5,
                            21,
                            6,
                            20,
                            6,
                            18,
                            5,
                            16,
                            4,
                            15
                        ]
                    ],
                    '(': [
                        14,
                        [
                            11,
                            25,
                            9,
                            23,
                            7,
                            20,
                            5,
                            16,
                            4,
                            11,
                            4,
                            7,
                            5,
                            2,
                            7,
                            -2,
                            9,
                            -5,
                            11,
                            -7
                        ]
                    ],
                    ')': [
                        14,
                        [
                            3,
                            25,
                            5,
                            23,
                            7,
                            20,
                            9,
                            16,
                            10,
                            11,
                            10,
                            7,
                            9,
                            2,
                            7,
                            -2,
                            5,
                            -5,
                            3,
                            -7
                        ]
                    ],
                    '*': [
                        16,
                        [
                            8,
                            21,
                            8,
                            9,
                            -1,
                            -1,
                            3,
                            18,
                            13,
                            12,
                            -1,
                            -1,
                            13,
                            18,
                            3,
                            12
                        ]
                    ],
                    '+': [
                        26,
                        [
                            13,
                            18,
                            13,
                            0,
                            -1,
                            -1,
                            4,
                            9,
                            22,
                            9
                        ]
                    ],
                    ',': [
                        10,
                        [
                            6,
                            1,
                            5,
                            0,
                            4,
                            1,
                            5,
                            2,
                            6,
                            1,
                            6,
                            -1,
                            5,
                            -3,
                            4,
                            -4
                        ]
                    ],
                    '-': [
                        26,
                        [
                            4,
                            9,
                            22,
                            9
                        ]
                    ],
                    '.': [
                        10,
                        [
                            5,
                            2,
                            4,
                            1,
                            5,
                            0,
                            6,
                            1,
                            5,
                            2
                        ]
                    ],
                    '/': [
                        22,
                        [
                            20,
                            25,
                            2,
                            -7
                        ]
                    ],
                    0: [
                        20,
                        [
                            9,
                            21,
                            6,
                            20,
                            4,
                            17,
                            3,
                            12,
                            3,
                            9,
                            4,
                            4,
                            6,
                            1,
                            9,
                            0,
                            11,
                            0,
                            14,
                            1,
                            16,
                            4,
                            17,
                            9,
                            17,
                            12,
                            16,
                            17,
                            14,
                            20,
                            11,
                            21,
                            9,
                            21
                        ]
                    ],
                    1: [
                        20,
                        [
                            6,
                            17,
                            8,
                            18,
                            11,
                            21,
                            11,
                            0
                        ]
                    ],
                    2: [
                        20,
                        [
                            4,
                            16,
                            4,
                            17,
                            5,
                            19,
                            6,
                            20,
                            8,
                            21,
                            12,
                            21,
                            14,
                            20,
                            15,
                            19,
                            16,
                            17,
                            16,
                            15,
                            15,
                            13,
                            13,
                            10,
                            3,
                            0,
                            17,
                            0
                        ]
                    ],
                    3: [
                        20,
                        [
                            5,
                            21,
                            16,
                            21,
                            10,
                            13,
                            13,
                            13,
                            15,
                            12,
                            16,
                            11,
                            17,
                            8,
                            17,
                            6,
                            16,
                            3,
                            14,
                            1,
                            11,
                            0,
                            8,
                            0,
                            5,
                            1,
                            4,
                            2,
                            3,
                            4
                        ]
                    ],
                    4: [
                        20,
                        [
                            13,
                            21,
                            3,
                            7,
                            18,
                            7,
                            -1,
                            -1,
                            13,
                            21,
                            13,
                            0
                        ]
                    ],
                    5: [
                        20,
                        [
                            15,
                            21,
                            5,
                            21,
                            4,
                            12,
                            5,
                            13,
                            8,
                            14,
                            11,
                            14,
                            14,
                            13,
                            16,
                            11,
                            17,
                            8,
                            17,
                            6,
                            16,
                            3,
                            14,
                            1,
                            11,
                            0,
                            8,
                            0,
                            5,
                            1,
                            4,
                            2,
                            3,
                            4
                        ]
                    ],
                    6: [
                        20,
                        [
                            16,
                            18,
                            15,
                            20,
                            12,
                            21,
                            10,
                            21,
                            7,
                            20,
                            5,
                            17,
                            4,
                            12,
                            4,
                            7,
                            5,
                            3,
                            7,
                            1,
                            10,
                            0,
                            11,
                            0,
                            14,
                            1,
                            16,
                            3,
                            17,
                            6,
                            17,
                            7,
                            16,
                            10,
                            14,
                            12,
                            11,
                            13,
                            10,
                            13,
                            7,
                            12,
                            5,
                            10,
                            4,
                            7
                        ]
                    ],
                    7: [
                        20,
                        [
                            17,
                            21,
                            7,
                            0,
                            -1,
                            -1,
                            3,
                            21,
                            17,
                            21
                        ]
                    ],
                    8: [
                        20,
                        [
                            8,
                            21,
                            5,
                            20,
                            4,
                            18,
                            4,
                            16,
                            5,
                            14,
                            7,
                            13,
                            11,
                            12,
                            14,
                            11,
                            16,
                            9,
                            17,
                            7,
                            17,
                            4,
                            16,
                            2,
                            15,
                            1,
                            12,
                            0,
                            8,
                            0,
                            5,
                            1,
                            4,
                            2,
                            3,
                            4,
                            3,
                            7,
                            4,
                            9,
                            6,
                            11,
                            9,
                            12,
                            13,
                            13,
                            15,
                            14,
                            16,
                            16,
                            16,
                            18,
                            15,
                            20,
                            12,
                            21,
                            8,
                            21
                        ]
                    ],
                    9: [
                        20,
                        [
                            16,
                            14,
                            15,
                            11,
                            13,
                            9,
                            10,
                            8,
                            9,
                            8,
                            6,
                            9,
                            4,
                            11,
                            3,
                            14,
                            3,
                            15,
                            4,
                            18,
                            6,
                            20,
                            9,
                            21,
                            10,
                            21,
                            13,
                            20,
                            15,
                            18,
                            16,
                            14,
                            16,
                            9,
                            15,
                            4,
                            13,
                            1,
                            10,
                            0,
                            8,
                            0,
                            5,
                            1,
                            4,
                            3
                        ]
                    ],
                    ':': [
                        10,
                        [
                            5,
                            14,
                            4,
                            13,
                            5,
                            12,
                            6,
                            13,
                            5,
                            14,
                            -1,
                            -1,
                            5,
                            2,
                            4,
                            1,
                            5,
                            0,
                            6,
                            1,
                            5,
                            2
                        ]
                    ],
                    ';': [
                        10,
                        [
                            5,
                            14,
                            4,
                            13,
                            5,
                            12,
                            6,
                            13,
                            5,
                            14,
                            -1,
                            -1,
                            6,
                            1,
                            5,
                            0,
                            4,
                            1,
                            5,
                            2,
                            6,
                            1,
                            6,
                            -1,
                            5,
                            -3,
                            4,
                            -4
                        ]
                    ],
                    '<': [
                        24,
                        [
                            20,
                            18,
                            4,
                            9,
                            20,
                            0
                        ]
                    ],
                    '=': [
                        26,
                        [
                            4,
                            12,
                            22,
                            12,
                            -1,
                            -1,
                            4,
                            6,
                            22,
                            6
                        ]
                    ],
                    '>': [
                        24,
                        [
                            4,
                            18,
                            20,
                            9,
                            4,
                            0
                        ]
                    ],
                    '?': [
                        18,
                        [
                            3,
                            16,
                            3,
                            17,
                            4,
                            19,
                            5,
                            20,
                            7,
                            21,
                            11,
                            21,
                            13,
                            20,
                            14,
                            19,
                            15,
                            17,
                            15,
                            15,
                            14,
                            13,
                            13,
                            12,
                            9,
                            10,
                            9,
                            7,
                            -1,
                            -1,
                            9,
                            2,
                            8,
                            1,
                            9,
                            0,
                            10,
                            1,
                            9,
                            2
                        ]
                    ],
                    '@': [
                        27,
                        [
                            18,
                            13,
                            17,
                            15,
                            15,
                            16,
                            12,
                            16,
                            10,
                            15,
                            9,
                            14,
                            8,
                            11,
                            8,
                            8,
                            9,
                            6,
                            11,
                            5,
                            14,
                            5,
                            16,
                            6,
                            17,
                            8,
                            -1,
                            -1,
                            12,
                            16,
                            10,
                            14,
                            9,
                            11,
                            9,
                            8,
                            10,
                            6,
                            11,
                            5,
                            -1,
                            -1,
                            18,
                            16,
                            17,
                            8,
                            17,
                            6,
                            19,
                            5,
                            21,
                            5,
                            23,
                            7,
                            24,
                            10,
                            24,
                            12,
                            23,
                            15,
                            22,
                            17,
                            20,
                            19,
                            18,
                            20,
                            15,
                            21,
                            12,
                            21,
                            9,
                            20,
                            7,
                            19,
                            5,
                            17,
                            4,
                            15,
                            3,
                            12,
                            3,
                            9,
                            4,
                            6,
                            5,
                            4,
                            7,
                            2,
                            9,
                            1,
                            12,
                            0,
                            15,
                            0,
                            18,
                            1,
                            20,
                            2,
                            21,
                            3,
                            -1,
                            -1,
                            19,
                            16,
                            18,
                            8,
                            18,
                            6,
                            19,
                            5
                        ]
                    ],
                    A: [
                        18,
                        [
                            9,
                            21,
                            1,
                            0,
                            -1,
                            -1,
                            9,
                            21,
                            17,
                            0,
                            -1,
                            -1,
                            4,
                            7,
                            14,
                            7
                        ]
                    ],
                    B: [
                        21,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            13,
                            21,
                            16,
                            20,
                            17,
                            19,
                            18,
                            17,
                            18,
                            15,
                            17,
                            13,
                            16,
                            12,
                            13,
                            11,
                            -1,
                            -1,
                            4,
                            11,
                            13,
                            11,
                            16,
                            10,
                            17,
                            9,
                            18,
                            7,
                            18,
                            4,
                            17,
                            2,
                            16,
                            1,
                            13,
                            0,
                            4,
                            0
                        ]
                    ],
                    C: [
                        21,
                        [
                            18,
                            16,
                            17,
                            18,
                            15,
                            20,
                            13,
                            21,
                            9,
                            21,
                            7,
                            20,
                            5,
                            18,
                            4,
                            16,
                            3,
                            13,
                            3,
                            8,
                            4,
                            5,
                            5,
                            3,
                            7,
                            1,
                            9,
                            0,
                            13,
                            0,
                            15,
                            1,
                            17,
                            3,
                            18,
                            5
                        ]
                    ],
                    D: [
                        21,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            11,
                            21,
                            14,
                            20,
                            16,
                            18,
                            17,
                            16,
                            18,
                            13,
                            18,
                            8,
                            17,
                            5,
                            16,
                            3,
                            14,
                            1,
                            11,
                            0,
                            4,
                            0
                        ]
                    ],
                    E: [
                        19,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            17,
                            21,
                            -1,
                            -1,
                            4,
                            11,
                            12,
                            11,
                            -1,
                            -1,
                            4,
                            0,
                            17,
                            0
                        ]
                    ],
                    F: [
                        18,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            17,
                            21,
                            -1,
                            -1,
                            4,
                            11,
                            12,
                            11
                        ]
                    ],
                    G: [
                        21,
                        [
                            18,
                            16,
                            17,
                            18,
                            15,
                            20,
                            13,
                            21,
                            9,
                            21,
                            7,
                            20,
                            5,
                            18,
                            4,
                            16,
                            3,
                            13,
                            3,
                            8,
                            4,
                            5,
                            5,
                            3,
                            7,
                            1,
                            9,
                            0,
                            13,
                            0,
                            15,
                            1,
                            17,
                            3,
                            18,
                            5,
                            18,
                            8,
                            -1,
                            -1,
                            13,
                            8,
                            18,
                            8
                        ]
                    ],
                    H: [
                        22,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            18,
                            21,
                            18,
                            0,
                            -1,
                            -1,
                            4,
                            11,
                            18,
                            11
                        ]
                    ],
                    I: [
                        8,
                        [
                            4,
                            21,
                            4,
                            0
                        ]
                    ],
                    J: [
                        16,
                        [
                            12,
                            21,
                            12,
                            5,
                            11,
                            2,
                            10,
                            1,
                            8,
                            0,
                            6,
                            0,
                            4,
                            1,
                            3,
                            2,
                            2,
                            5,
                            2,
                            7
                        ]
                    ],
                    K: [
                        21,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            18,
                            21,
                            4,
                            7,
                            -1,
                            -1,
                            9,
                            12,
                            18,
                            0
                        ]
                    ],
                    L: [
                        17,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            0,
                            16,
                            0
                        ]
                    ],
                    M: [
                        24,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            12,
                            0,
                            -1,
                            -1,
                            20,
                            21,
                            12,
                            0,
                            -1,
                            -1,
                            20,
                            21,
                            20,
                            0
                        ]
                    ],
                    N: [
                        22,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            18,
                            0,
                            -1,
                            -1,
                            18,
                            21,
                            18,
                            0
                        ]
                    ],
                    O: [
                        22,
                        [
                            9,
                            21,
                            7,
                            20,
                            5,
                            18,
                            4,
                            16,
                            3,
                            13,
                            3,
                            8,
                            4,
                            5,
                            5,
                            3,
                            7,
                            1,
                            9,
                            0,
                            13,
                            0,
                            15,
                            1,
                            17,
                            3,
                            18,
                            5,
                            19,
                            8,
                            19,
                            13,
                            18,
                            16,
                            17,
                            18,
                            15,
                            20,
                            13,
                            21,
                            9,
                            21
                        ]
                    ],
                    P: [
                        21,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            13,
                            21,
                            16,
                            20,
                            17,
                            19,
                            18,
                            17,
                            18,
                            14,
                            17,
                            12,
                            16,
                            11,
                            13,
                            10,
                            4,
                            10
                        ]
                    ],
                    Q: [
                        22,
                        [
                            9,
                            21,
                            7,
                            20,
                            5,
                            18,
                            4,
                            16,
                            3,
                            13,
                            3,
                            8,
                            4,
                            5,
                            5,
                            3,
                            7,
                            1,
                            9,
                            0,
                            13,
                            0,
                            15,
                            1,
                            17,
                            3,
                            18,
                            5,
                            19,
                            8,
                            19,
                            13,
                            18,
                            16,
                            17,
                            18,
                            15,
                            20,
                            13,
                            21,
                            9,
                            21,
                            -1,
                            -1,
                            12,
                            4,
                            18,
                            -2
                        ]
                    ],
                    R: [
                        21,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            21,
                            13,
                            21,
                            16,
                            20,
                            17,
                            19,
                            18,
                            17,
                            18,
                            15,
                            17,
                            13,
                            16,
                            12,
                            13,
                            11,
                            4,
                            11,
                            -1,
                            -1,
                            11,
                            11,
                            18,
                            0
                        ]
                    ],
                    S: [
                        20,
                        [
                            17,
                            18,
                            15,
                            20,
                            12,
                            21,
                            8,
                            21,
                            5,
                            20,
                            3,
                            18,
                            3,
                            16,
                            4,
                            14,
                            5,
                            13,
                            7,
                            12,
                            13,
                            10,
                            15,
                            9,
                            16,
                            8,
                            17,
                            6,
                            17,
                            3,
                            15,
                            1,
                            12,
                            0,
                            8,
                            0,
                            5,
                            1,
                            3,
                            3
                        ]
                    ],
                    T: [
                        16,
                        [
                            8,
                            21,
                            8,
                            0,
                            -1,
                            -1,
                            1,
                            21,
                            15,
                            21
                        ]
                    ],
                    U: [
                        22,
                        [
                            4,
                            21,
                            4,
                            6,
                            5,
                            3,
                            7,
                            1,
                            10,
                            0,
                            12,
                            0,
                            15,
                            1,
                            17,
                            3,
                            18,
                            6,
                            18,
                            21
                        ]
                    ],
                    V: [
                        18,
                        [
                            1,
                            21,
                            9,
                            0,
                            -1,
                            -1,
                            17,
                            21,
                            9,
                            0
                        ]
                    ],
                    W: [
                        24,
                        [
                            2,
                            21,
                            7,
                            0,
                            -1,
                            -1,
                            12,
                            21,
                            7,
                            0,
                            -1,
                            -1,
                            12,
                            21,
                            17,
                            0,
                            -1,
                            -1,
                            22,
                            21,
                            17,
                            0
                        ]
                    ],
                    X: [
                        20,
                        [
                            3,
                            21,
                            17,
                            0,
                            -1,
                            -1,
                            17,
                            21,
                            3,
                            0
                        ]
                    ],
                    Y: [
                        18,
                        [
                            1,
                            21,
                            9,
                            11,
                            9,
                            0,
                            -1,
                            -1,
                            17,
                            21,
                            9,
                            11
                        ]
                    ],
                    Z: [
                        20,
                        [
                            17,
                            21,
                            3,
                            0,
                            -1,
                            -1,
                            3,
                            21,
                            17,
                            21,
                            -1,
                            -1,
                            3,
                            0,
                            17,
                            0
                        ]
                    ],
                    '[': [
                        14,
                        [
                            4,
                            25,
                            4,
                            -7,
                            -1,
                            -1,
                            5,
                            25,
                            5,
                            -7,
                            -1,
                            -1,
                            4,
                            25,
                            11,
                            25,
                            -1,
                            -1,
                            4,
                            -7,
                            11,
                            -7
                        ]
                    ],
                    '\\': [
                        14,
                        [
                            0,
                            21,
                            14,
                            -3
                        ]
                    ],
                    ']': [
                        14,
                        [
                            9,
                            25,
                            9,
                            -7,
                            -1,
                            -1,
                            10,
                            25,
                            10,
                            -7,
                            -1,
                            -1,
                            3,
                            25,
                            10,
                            25,
                            -1,
                            -1,
                            3,
                            -7,
                            10,
                            -7
                        ]
                    ],
                    '^': [
                        16,
                        [
                            6,
                            15,
                            8,
                            18,
                            10,
                            15,
                            -1,
                            -1,
                            3,
                            12,
                            8,
                            17,
                            13,
                            12,
                            -1,
                            -1,
                            8,
                            17,
                            8,
                            0
                        ]
                    ],
                    _: [
                        16,
                        [
                            0,
                            -2,
                            16,
                            -2
                        ]
                    ],
                    '`': [
                        10,
                        [
                            6,
                            21,
                            5,
                            20,
                            4,
                            18,
                            4,
                            16,
                            5,
                            15,
                            6,
                            16,
                            5,
                            17
                        ]
                    ],
                    a: [
                        19,
                        [
                            15,
                            14,
                            15,
                            0,
                            -1,
                            -1,
                            15,
                            11,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3
                        ]
                    ],
                    b: [
                        19,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            11,
                            6,
                            13,
                            8,
                            14,
                            11,
                            14,
                            13,
                            13,
                            15,
                            11,
                            16,
                            8,
                            16,
                            6,
                            15,
                            3,
                            13,
                            1,
                            11,
                            0,
                            8,
                            0,
                            6,
                            1,
                            4,
                            3
                        ]
                    ],
                    c: [
                        18,
                        [
                            15,
                            11,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3
                        ]
                    ],
                    d: [
                        19,
                        [
                            15,
                            21,
                            15,
                            0,
                            -1,
                            -1,
                            15,
                            11,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3
                        ]
                    ],
                    e: [
                        18,
                        [
                            3,
                            8,
                            15,
                            8,
                            15,
                            10,
                            14,
                            12,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3
                        ]
                    ],
                    f: [
                        12,
                        [
                            10,
                            21,
                            8,
                            21,
                            6,
                            20,
                            5,
                            17,
                            5,
                            0,
                            -1,
                            -1,
                            2,
                            14,
                            9,
                            14
                        ]
                    ],
                    g: [
                        19,
                        [
                            15,
                            14,
                            15,
                            -2,
                            14,
                            -5,
                            13,
                            -6,
                            11,
                            -7,
                            8,
                            -7,
                            6,
                            -6,
                            -1,
                            -1,
                            15,
                            11,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3
                        ]
                    ],
                    h: [
                        19,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            10,
                            7,
                            13,
                            9,
                            14,
                            12,
                            14,
                            14,
                            13,
                            15,
                            10,
                            15,
                            0
                        ]
                    ],
                    i: [
                        8,
                        [
                            3,
                            21,
                            4,
                            20,
                            5,
                            21,
                            4,
                            22,
                            3,
                            21,
                            -1,
                            -1,
                            4,
                            14,
                            4,
                            0
                        ]
                    ],
                    j: [
                        10,
                        [
                            5,
                            21,
                            6,
                            20,
                            7,
                            21,
                            6,
                            22,
                            5,
                            21,
                            -1,
                            -1,
                            6,
                            14,
                            6,
                            -3,
                            5,
                            -6,
                            3,
                            -7,
                            1,
                            -7
                        ]
                    ],
                    k: [
                        17,
                        [
                            4,
                            21,
                            4,
                            0,
                            -1,
                            -1,
                            14,
                            14,
                            4,
                            4,
                            -1,
                            -1,
                            8,
                            8,
                            15,
                            0
                        ]
                    ],
                    l: [
                        8,
                        [
                            4,
                            21,
                            4,
                            0
                        ]
                    ],
                    m: [
                        30,
                        [
                            4,
                            14,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            10,
                            7,
                            13,
                            9,
                            14,
                            12,
                            14,
                            14,
                            13,
                            15,
                            10,
                            15,
                            0,
                            -1,
                            -1,
                            15,
                            10,
                            18,
                            13,
                            20,
                            14,
                            23,
                            14,
                            25,
                            13,
                            26,
                            10,
                            26,
                            0
                        ]
                    ],
                    n: [
                        19,
                        [
                            4,
                            14,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            10,
                            7,
                            13,
                            9,
                            14,
                            12,
                            14,
                            14,
                            13,
                            15,
                            10,
                            15,
                            0
                        ]
                    ],
                    o: [
                        19,
                        [
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3,
                            16,
                            6,
                            16,
                            8,
                            15,
                            11,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14
                        ]
                    ],
                    p: [
                        19,
                        [
                            4,
                            14,
                            4,
                            -7,
                            -1,
                            -1,
                            4,
                            11,
                            6,
                            13,
                            8,
                            14,
                            11,
                            14,
                            13,
                            13,
                            15,
                            11,
                            16,
                            8,
                            16,
                            6,
                            15,
                            3,
                            13,
                            1,
                            11,
                            0,
                            8,
                            0,
                            6,
                            1,
                            4,
                            3
                        ]
                    ],
                    q: [
                        19,
                        [
                            15,
                            14,
                            15,
                            -7,
                            -1,
                            -1,
                            15,
                            11,
                            13,
                            13,
                            11,
                            14,
                            8,
                            14,
                            6,
                            13,
                            4,
                            11,
                            3,
                            8,
                            3,
                            6,
                            4,
                            3,
                            6,
                            1,
                            8,
                            0,
                            11,
                            0,
                            13,
                            1,
                            15,
                            3
                        ]
                    ],
                    r: [
                        13,
                        [
                            4,
                            14,
                            4,
                            0,
                            -1,
                            -1,
                            4,
                            8,
                            5,
                            11,
                            7,
                            13,
                            9,
                            14,
                            12,
                            14
                        ]
                    ],
                    s: [
                        17,
                        [
                            14,
                            11,
                            13,
                            13,
                            10,
                            14,
                            7,
                            14,
                            4,
                            13,
                            3,
                            11,
                            4,
                            9,
                            6,
                            8,
                            11,
                            7,
                            13,
                            6,
                            14,
                            4,
                            14,
                            3,
                            13,
                            1,
                            10,
                            0,
                            7,
                            0,
                            4,
                            1,
                            3,
                            3
                        ]
                    ],
                    t: [
                        12,
                        [
                            5,
                            21,
                            5,
                            4,
                            6,
                            1,
                            8,
                            0,
                            10,
                            0,
                            -1,
                            -1,
                            2,
                            14,
                            9,
                            14
                        ]
                    ],
                    u: [
                        19,
                        [
                            4,
                            14,
                            4,
                            4,
                            5,
                            1,
                            7,
                            0,
                            10,
                            0,
                            12,
                            1,
                            15,
                            4,
                            -1,
                            -1,
                            15,
                            14,
                            15,
                            0
                        ]
                    ],
                    v: [
                        16,
                        [
                            2,
                            14,
                            8,
                            0,
                            -1,
                            -1,
                            14,
                            14,
                            8,
                            0
                        ]
                    ],
                    w: [
                        22,
                        [
                            3,
                            14,
                            7,
                            0,
                            -1,
                            -1,
                            11,
                            14,
                            7,
                            0,
                            -1,
                            -1,
                            11,
                            14,
                            15,
                            0,
                            -1,
                            -1,
                            19,
                            14,
                            15,
                            0
                        ]
                    ],
                    x: [
                        17,
                        [
                            3,
                            14,
                            14,
                            0,
                            -1,
                            -1,
                            14,
                            14,
                            3,
                            0
                        ]
                    ],
                    y: [
                        16,
                        [
                            2,
                            14,
                            8,
                            0,
                            -1,
                            -1,
                            14,
                            14,
                            8,
                            0,
                            6,
                            -4,
                            4,
                            -6,
                            2,
                            -7,
                            1,
                            -7
                        ]
                    ],
                    z: [
                        17,
                        [
                            14,
                            14,
                            3,
                            0,
                            -1,
                            -1,
                            3,
                            14,
                            14,
                            14,
                            -1,
                            -1,
                            3,
                            0,
                            14,
                            0
                        ]
                    ],
                    '{': [
                        14,
                        [
                            9,
                            25,
                            7,
                            24,
                            6,
                            23,
                            5,
                            21,
                            5,
                            19,
                            6,
                            17,
                            7,
                            16,
                            8,
                            14,
                            8,
                            12,
                            6,
                            10,
                            -1,
                            -1,
                            7,
                            24,
                            6,
                            22,
                            6,
                            20,
                            7,
                            18,
                            8,
                            17,
                            9,
                            15,
                            9,
                            13,
                            8,
                            11,
                            4,
                            9,
                            8,
                            7,
                            9,
                            5,
                            9,
                            3,
                            8,
                            1,
                            7,
                            0,
                            6,
                            -2,
                            6,
                            -4,
                            7,
                            -6,
                            -1,
                            -1,
                            6,
                            8,
                            8,
                            6,
                            8,
                            4,
                            7,
                            2,
                            6,
                            1,
                            5,
                            -1,
                            5,
                            -3,
                            6,
                            -5,
                            7,
                            -6,
                            9,
                            -7
                        ]
                    ],
                    '|': [
                        8,
                        [
                            4,
                            25,
                            4,
                            -7
                        ]
                    ],
                    '}': [
                        14,
                        [
                            5,
                            25,
                            7,
                            24,
                            8,
                            23,
                            9,
                            21,
                            9,
                            19,
                            8,
                            17,
                            7,
                            16,
                            6,
                            14,
                            6,
                            12,
                            8,
                            10,
                            -1,
                            -1,
                            7,
                            24,
                            8,
                            22,
                            8,
                            20,
                            7,
                            18,
                            6,
                            17,
                            5,
                            15,
                            5,
                            13,
                            6,
                            11,
                            10,
                            9,
                            6,
                            7,
                            5,
                            5,
                            5,
                            3,
                            6,
                            1,
                            7,
                            0,
                            8,
                            -2,
                            8,
                            -4,
                            7,
                            -6,
                            -1,
                            -1,
                            8,
                            8,
                            6,
                            6,
                            6,
                            4,
                            7,
                            2,
                            8,
                            1,
                            9,
                            -1,
                            9,
                            -3,
                            8,
                            -5,
                            7,
                            -6,
                            5,
                            -7
                        ]
                    ],
                    '~': [
                        24,
                        [
                            3,
                            6,
                            3,
                            8,
                            4,
                            11,
                            6,
                            12,
                            8,
                            12,
                            10,
                            11,
                            14,
                            8,
                            16,
                            7,
                            18,
                            7,
                            20,
                            8,
                            21,
                            10,
                            -1,
                            -1,
                            3,
                            8,
                            4,
                            10,
                            6,
                            11,
                            8,
                            11,
                            10,
                            10,
                            14,
                            7,
                            16,
                            6,
                            18,
                            6,
                            20,
                            7,
                            21,
                            10,
                            21,
                            12
                        ]
                    ]
                };
            },
            {
                '../data/array_types': 39,
                '../data/extent': 53,
                '../data/pos_attributes': 57,
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../util/browser': 252,
                './vertex_array_object': 95,
                '@mapbox/gl-matrix': 2
            }
        ],
        78: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawFill(t, e, r, o) {
                    var a = r.paint.get('fill-color'), i = r.paint.get('fill-opacity');
                    if (0 !== i.constantOr(1)) {
                        var n = t.context;
                        n.setColorMode(t.colorModeForRenderPass());
                        var l = r.paint.get('fill-pattern') || 1 !== a.constantOr(Color.transparent).a || 1 !== i.constantOr(0) ? 'translucent' : 'opaque';
                        t.renderPass === l && (n.setDepthMode(t.depthModeForSublayer(1, 'opaque' === t.renderPass ? DepthMode.ReadWrite : DepthMode.ReadOnly)), drawFillTiles(t, e, r, o, drawFillTile)), 'translucent' === t.renderPass && r.paint.get('fill-antialias') && (n.lineWidth.set(2), n.setDepthMode(t.depthModeForSublayer(r.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly)), drawFillTiles(t, e, r, o, drawStrokeTile));
                    }
                }
                function drawFillTiles(t, e, r, o, a) {
                    if (!pattern.isPatternMissing(r.paint.get('fill-pattern'), t)) {
                        for (var i = !0, n = 0, l = o; n < l.length; n += 1) {
                            var s = l[n], p = e.getTile(s), d = p.getBucket(r);
                            d && (t.context.setStencilMode(t.stencilModeForClipping(s)), a(t, e, r, p, s, d, i), i = !1);
                        }
                    }
                }
                function drawFillTile(t, e, r, o, a, i, n) {
                    var l = t.context.gl, s = i.programConfigurations.get(r.id);
                    setFillProgram('fill', r.paint.get('fill-pattern'), t, s, r, o, a, n).draw(t.context, l.TRIANGLES, r.id, i.layoutVertexBuffer, i.indexBuffer, i.segments, s);
                }
                function drawStrokeTile(t, e, r, o, a, i, n) {
                    var l = t.context.gl, s = i.programConfigurations.get(r.id), p = r.getPaintProperty('fill-outline-color') ? null : r.paint.get('fill-pattern'), d = setFillProgram('fillOutline', p, t, s, r, o, a, n);
                    l.uniform2f(d.uniforms.u_world, l.drawingBufferWidth, l.drawingBufferHeight), d.draw(t.context, l.LINES, r.id, i.layoutVertexBuffer, i.indexBuffer2, i.segments2, s);
                }
                function setFillProgram(t, e, r, o, a, i, n, l) {
                    var s, p = r.context.program.get();
                    return e ? (s = r.useProgram(t + 'Pattern', o), (l || s.program !== p) && (o.setUniforms(r.context, s, a.paint, { zoom: r.transform.zoom }), pattern.prepare(e, r, s)), pattern.setTile(i, r, s)) : (s = r.useProgram(t, o), (l || s.program !== p) && o.setUniforms(r.context, s, a.paint, { zoom: r.transform.zoom })), r.context.gl.uniformMatrix4fv(s.uniforms.u_matrix, !1, r.translatePosMatrix(n.posMatrix, i, a.paint.get('fill-translate'), a.paint.get('fill-translate-anchor'))), s;
                }
                var pattern = _dereq_('./pattern'), Color = _dereq_('../style-spec/util/color'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = drawFill;
            },
            {
                '../gl/depth_mode': 67,
                '../style-spec/util/color': 153,
                './pattern': 91
            }
        ],
        79: [
            function (_dereq_, module, exports) {
                'use strict';
                function draw(e, t, r, i) {
                    if (0 !== r.paint.get('fill-extrusion-opacity')) {
                        if ('offscreen' === e.renderPass) {
                            drawToExtrusionFramebuffer(e, r);
                            for (var o = !0, a = 0, n = i; a < n.length; a += 1) {
                                var s = n[a], u = t.getTile(s), f = u.getBucket(r);
                                f && (drawExtrusion(e, t, r, u, s, f, o), o = !1);
                            }
                        } else {
                            'translucent' === e.renderPass && drawExtrusionTexture(e, r);
                        }
                    }
                }
                function drawToExtrusionFramebuffer(e, t) {
                    var r = e.context, i = r.gl, o = t.viewportFrame;
                    if (e.depthRboNeedsClear && e.setupOffscreenDepthRenderbuffer(), !o) {
                        var a = new Texture(r, {
                            width: e.width,
                            height: e.height,
                            data: null
                        }, i.RGBA);
                        a.bind(i.LINEAR, i.CLAMP_TO_EDGE), o = t.viewportFrame = r.createFramebuffer(e.width, e.height), o.colorAttachment.set(a.texture);
                    }
                    r.bindFramebuffer.set(o.framebuffer), o.depthAttachment.set(e.depthRbo), e.depthRboNeedsClear && (r.clear({ depth: 1 }), e.depthRboNeedsClear = !1), r.clear({ color: Color.transparent }), r.setStencilMode(StencilMode.disabled), r.setDepthMode(new DepthMode(i.LEQUAL, DepthMode.ReadWrite, [
                        0,
                        1
                    ])), r.setColorMode(e.colorModeForRenderPass());
                }
                function drawExtrusionTexture(e, t) {
                    var r = t.viewportFrame;
                    if (r) {
                        var i = e.context, o = i.gl, a = e.useProgram('extrusionTexture');
                        i.setStencilMode(StencilMode.disabled), i.setDepthMode(DepthMode.disabled), i.setColorMode(e.colorModeForRenderPass()), i.activeTexture.set(o.TEXTURE0), o.bindTexture(o.TEXTURE_2D, r.colorAttachment.get()), o.uniform1f(a.uniforms.u_opacity, t.paint.get('fill-extrusion-opacity')), o.uniform1i(a.uniforms.u_image, 0);
                        var n = mat4.create();
                        mat4.ortho(n, 0, e.width, e.height, 0, 0, 1), o.uniformMatrix4fv(a.uniforms.u_matrix, !1, n), o.uniform2f(a.uniforms.u_world, o.drawingBufferWidth, o.drawingBufferHeight), e.viewportVAO.bind(i, a, e.viewportBuffer, []), o.drawArrays(o.TRIANGLE_STRIP, 0, 4);
                    }
                }
                function drawExtrusion(e, t, r, i, o, a, n) {
                    var s = e.context, u = s.gl, f = r.paint.get('fill-extrusion-pattern'), l = e.context.program.get(), d = a.programConfigurations.get(r.id), m = e.useProgram(f ? 'fillExtrusionPattern' : 'fillExtrusion', d);
                    if ((n || m.program !== l) && d.setUniforms(s, m, r.paint, { zoom: e.transform.zoom }), f) {
                        if (pattern.isPatternMissing(f, e)) {
                            return;
                        }
                        pattern.prepare(f, e, m), pattern.setTile(i, e, m), u.uniform1f(m.uniforms.u_height_factor, -Math.pow(2, o.overscaledZ) / i.tileSize / 8);
                    }
                    e.context.gl.uniformMatrix4fv(m.uniforms.u_matrix, !1, e.translatePosMatrix(o.posMatrix, i, r.paint.get('fill-extrusion-translate'), r.paint.get('fill-extrusion-translate-anchor'))), setLight(m, e), m.draw(s, u.TRIANGLES, r.id, a.layoutVertexBuffer, a.indexBuffer, a.segments, d);
                }
                function setLight(e, t) {
                    var r = t.context.gl, i = t.style.light, o = i.properties.get('position'), a = [
                            o.x,
                            o.y,
                            o.z
                        ], n = mat3.create();
                    'viewport' === i.properties.get('anchor') && mat3.fromRotation(n, -t.transform.angle), vec3.transformMat3(a, a, n);
                    var s = i.properties.get('color');
                    r.uniform3fv(e.uniforms.u_lightpos, a), r.uniform1f(e.uniforms.u_lightintensity, i.properties.get('intensity')), r.uniform3f(e.uniforms.u_lightcolor, s.r, s.g, s.b);
                }
                var glMatrix = _dereq_('@mapbox/gl-matrix'), pattern = _dereq_('./pattern'), Texture = _dereq_('./texture'), Color = _dereq_('../style-spec/util/color'), DepthMode = _dereq_('../gl/depth_mode'), mat3 = glMatrix.mat3, mat4 = glMatrix.mat4, vec3 = glMatrix.vec3, StencilMode = _dereq_('../gl/stencil_mode');
                module.exports = draw;
            },
            {
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../style-spec/util/color': 153,
                './pattern': 91,
                './texture': 93,
                '@mapbox/gl-matrix': 2
            }
        ],
        80: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawHeatmap(e, t, r, o) {
                    if (0 !== r.paint.get('heatmap-opacity')) {
                        if ('offscreen' === e.renderPass) {
                            var a = e.context, i = a.gl;
                            a.setDepthMode(e.depthModeForSublayer(0, DepthMode.ReadOnly)), a.setStencilMode(StencilMode.disabled), bindFramebuffer(a, e, r), a.clear({ color: Color.transparent }), a.setColorMode(new ColorMode([
                                i.ONE,
                                i.ONE
                            ], Color.transparent, [
                                !0,
                                !0,
                                !0,
                                !0
                            ]));
                            for (var n = !0, u = 0; u < o.length; u++) {
                                var T = o[u];
                                if (!t.hasRenderableParent(T)) {
                                    var f = t.getTile(T), m = f.getBucket(r);
                                    if (m) {
                                        var l = e.context.program.get(), s = m.programConfigurations.get(r.id), d = e.useProgram('heatmap', s), E = e.transform, x = E.zoom;
                                        (n || d.program !== l) && (s.setUniforms(e.context, d, r.paint, { zoom: x }), n = !1), i.uniform1f(d.uniforms.u_extrude_scale, pixelsToTileUnits(f, 1, x)), i.uniform1f(d.uniforms.u_intensity, r.paint.get('heatmap-intensity')), i.uniformMatrix4fv(d.uniforms.u_matrix, !1, T.posMatrix), d.draw(a, i.TRIANGLES, r.id, m.layoutVertexBuffer, m.indexBuffer, m.segments, s);
                                    }
                                }
                            }
                            a.viewport.set([
                                0,
                                0,
                                e.width,
                                e.height
                            ]);
                        } else {
                            'translucent' === e.renderPass && (e.context.setColorMode(e.colorModeForRenderPass()), renderTextureToMap(e, r));
                        }
                    }
                }
                function bindFramebuffer(e, t, r) {
                    var o = e.gl;
                    e.activeTexture.set(o.TEXTURE1), e.viewport.set([
                        0,
                        0,
                        t.width / 4,
                        t.height / 4
                    ]);
                    var a = r.heatmapFbo;
                    if (a) {
                        o.bindTexture(o.TEXTURE_2D, a.colorAttachment.get()), e.bindFramebuffer.set(a.framebuffer);
                    } else {
                        var i = o.createTexture();
                        o.bindTexture(o.TEXTURE_2D, i), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, o.CLAMP_TO_EDGE), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, o.CLAMP_TO_EDGE), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR), a = r.heatmapFbo = e.createFramebuffer(t.width / 4, t.height / 4), bindTextureToFramebuffer(e, t, i, a);
                    }
                }
                function bindTextureToFramebuffer(e, t, r, o) {
                    var a = e.gl;
                    a.texImage2D(a.TEXTURE_2D, 0, a.RGBA, t.width / 4, t.height / 4, 0, a.RGBA, e.extTextureHalfFloat ? e.extTextureHalfFloat.HALF_FLOAT_OES : a.UNSIGNED_BYTE, null), o.colorAttachment.set(r), e.extTextureHalfFloat && a.checkFramebufferStatus(a.FRAMEBUFFER) !== a.FRAMEBUFFER_COMPLETE && (e.extTextureHalfFloat = null, o.colorAttachment.setDirty(), bindTextureToFramebuffer(e, t, r, o));
                }
                function renderTextureToMap(e, t) {
                    var r = e.context, o = r.gl, a = t.heatmapFbo;
                    if (a) {
                        r.activeTexture.set(o.TEXTURE0), o.bindTexture(o.TEXTURE_2D, a.colorAttachment.get()), r.activeTexture.set(o.TEXTURE1);
                        var i = t.colorRampTexture;
                        i || (i = t.colorRampTexture = new Texture(r, t.colorRamp, o.RGBA)), i.bind(o.LINEAR, o.CLAMP_TO_EDGE), r.setDepthMode(DepthMode.disabled);
                        var n = e.useProgram('heatmapTexture'), u = t.paint.get('heatmap-opacity');
                        o.uniform1f(n.uniforms.u_opacity, u), o.uniform1i(n.uniforms.u_image, 0), o.uniform1i(n.uniforms.u_color_ramp, 1);
                        var T = mat4.create();
                        mat4.ortho(T, 0, e.width, e.height, 0, 0, 1), o.uniformMatrix4fv(n.uniforms.u_matrix, !1, T), o.uniform2f(n.uniforms.u_world, o.drawingBufferWidth, o.drawingBufferHeight), e.viewportVAO.bind(e.context, n, e.viewportBuffer, []), o.drawArrays(o.TRIANGLE_STRIP, 0, 4);
                    }
                }
                var mat4 = _dereq_('@mapbox/gl-matrix').mat4, Texture = _dereq_('./texture'), pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), Color = _dereq_('../style-spec/util/color'), DepthMode = _dereq_('../gl/depth_mode'), StencilMode = _dereq_('../gl/stencil_mode'), ColorMode = _dereq_('../gl/color_mode');
                module.exports = drawHeatmap;
            },
            {
                '../gl/color_mode': 65,
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../source/pixels_to_tile_units': 104,
                '../style-spec/util/color': 153,
                './texture': 93,
                '@mapbox/gl-matrix': 2
            }
        ],
        81: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawHillshade(e, r, t, a) {
                    if ('offscreen' === e.renderPass || 'translucent' === e.renderPass) {
                        var i = e.context;
                        i.setDepthMode(e.depthModeForSublayer(0, DepthMode.ReadOnly)), i.setStencilMode(StencilMode.disabled), i.setColorMode(e.colorModeForRenderPass());
                        for (var n = 0, o = a; n < o.length; n += 1) {
                            var s = o[n], d = r.getTile(s);
                            d.needsHillshadePrepare && 'offscreen' === e.renderPass ? prepareHillshade(e, d) : 'translucent' === e.renderPass && renderHillshade(e, d, t);
                        }
                        i.viewport.set([
                            0,
                            0,
                            e.width,
                            e.height
                        ]);
                    }
                }
                function setLight(e, r, t) {
                    var a = t.paint.get('hillshade-illumination-direction') * (Math.PI / 180);
                    'viewport' === t.paint.get('hillshade-illumination-anchor') && (a -= r.transform.angle), r.context.gl.uniform2f(e.uniforms.u_light, t.paint.get('hillshade-exaggeration'), a);
                }
                function getTileLatRange(e, r) {
                    var t = r.toCoordinate(), a = new Coordinate(t.column, t.row + 1, t.zoom);
                    return [
                        e.transform.coordinateLocation(t).lat,
                        e.transform.coordinateLocation(a).lat
                    ];
                }
                function renderHillshade(e, r, t) {
                    var a = e.context, i = a.gl, n = r.fbo;
                    if (n) {
                        var o = e.useProgram('hillshade'), s = e.transform.calculatePosMatrix(r.tileID.toUnwrapped());
                        setLight(o, e, t);
                        var d = getTileLatRange(e, r.tileID);
                        a.activeTexture.set(i.TEXTURE0), i.bindTexture(i.TEXTURE_2D, n.colorAttachment.get()), i.uniformMatrix4fv(o.uniforms.u_matrix, !1, s), i.uniform2fv(o.uniforms.u_latrange, d), i.uniform1i(o.uniforms.u_image, 0);
                        var l = t.paint.get('hillshade-shadow-color');
                        i.uniform4f(o.uniforms.u_shadow, l.r, l.g, l.b, l.a);
                        var u = t.paint.get('hillshade-highlight-color');
                        i.uniform4f(o.uniforms.u_highlight, u.r, u.g, u.b, u.a);
                        var f = t.paint.get('hillshade-accent-color');
                        if (i.uniform4f(o.uniforms.u_accent, f.r, f.g, f.b, f.a), r.maskedBoundsBuffer && r.maskedIndexBuffer && r.segments) {
                            o.draw(a, i.TRIANGLES, t.id, r.maskedBoundsBuffer, r.maskedIndexBuffer, r.segments);
                        } else {
                            var m = e.rasterBoundsBuffer;
                            e.rasterBoundsVAO.bind(a, o, m, []), i.drawArrays(i.TRIANGLE_STRIP, 0, m.length);
                        }
                    }
                }
                function prepareHillshade(e, r) {
                    var t = e.context, a = t.gl;
                    if (r.dem && r.dem.level) {
                        var i = r.dem.level.dim, n = r.dem.getPixels();
                        if (t.activeTexture.set(a.TEXTURE1), t.pixelStoreUnpackPremultiplyAlpha.set(!1), r.demTexture = r.demTexture || e.getTileTexture(r.tileSize), r.demTexture) {
                            var o = r.demTexture;
                            o.update(n, !1), o.bind(a.NEAREST, a.CLAMP_TO_EDGE);
                        } else {
                            r.demTexture = new Texture(t, n, a.RGBA, !1), r.demTexture.bind(a.NEAREST, a.CLAMP_TO_EDGE);
                        }
                        t.activeTexture.set(a.TEXTURE0);
                        var s = r.fbo;
                        if (!s) {
                            var d = new Texture(t, {
                                width: i,
                                height: i,
                                data: null
                            }, a.RGBA);
                            d.bind(a.LINEAR, a.CLAMP_TO_EDGE), s = r.fbo = t.createFramebuffer(i, i), s.colorAttachment.set(d.texture);
                        }
                        t.bindFramebuffer.set(s.framebuffer), t.viewport.set([
                            0,
                            0,
                            i,
                            i
                        ]);
                        var l = mat4.create();
                        mat4.ortho(l, 0, EXTENT, -EXTENT, 0, 0, 1), mat4.translate(l, l, [
                            0,
                            -EXTENT,
                            0
                        ]);
                        var u = e.useProgram('hillshadePrepare');
                        a.uniformMatrix4fv(u.uniforms.u_matrix, !1, l), a.uniform1f(u.uniforms.u_zoom, r.tileID.overscaledZ), a.uniform2fv(u.uniforms.u_dimension, [
                            2 * i,
                            2 * i
                        ]), a.uniform1i(u.uniforms.u_image, 1);
                        var f = e.rasterBoundsBuffer;
                        e.rasterBoundsVAO.bind(t, u, f, []), a.drawArrays(a.TRIANGLE_STRIP, 0, f.length), r.needsHillshadePrepare = !1;
                    }
                }
                var Coordinate = _dereq_('../geo/coordinate'), Texture = _dereq_('./texture'), EXTENT = _dereq_('../data/extent'), mat4 = _dereq_('@mapbox/gl-matrix').mat4, StencilMode = _dereq_('../gl/stencil_mode'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = drawHillshade;
            },
            {
                '../data/extent': 53,
                '../geo/coordinate': 61,
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                './texture': 93,
                '@mapbox/gl-matrix': 2
            }
        ],
        82: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawLineTile(e, i, t, r, n, a, o, s, u) {
                    var f, l, m, p, _ = i.context, g = _.gl, d = n.paint.get('line-dasharray'), c = n.paint.get('line-pattern');
                    if (s || u) {
                        var x = 1 / pixelsToTileUnits(t, 1, i.transform.tileZoom);
                        if (d) {
                            f = i.lineAtlas.getDash(d.from, 'round' === n.layout.get('line-cap')), l = i.lineAtlas.getDash(d.to, 'round' === n.layout.get('line-cap'));
                            var h = f.width * d.fromScale, v = l.width * d.toScale;
                            g.uniform2f(e.uniforms.u_patternscale_a, x / h, -f.height / 2), g.uniform2f(e.uniforms.u_patternscale_b, x / v, -l.height / 2), g.uniform1f(e.uniforms.u_sdfgamma, i.lineAtlas.width / (256 * Math.min(h, v) * browser.devicePixelRatio) / 2);
                        } else if (c) {
                            if (m = i.imageManager.getPattern(c.from), p = i.imageManager.getPattern(c.to), !m || !p) {
                                return;
                            }
                            g.uniform2f(e.uniforms.u_pattern_size_a, m.displaySize[0] * c.fromScale / x, p.displaySize[1]), g.uniform2f(e.uniforms.u_pattern_size_b, p.displaySize[0] * c.toScale / x, p.displaySize[1]);
                            var T = i.imageManager.getPixelSize(), y = T.width, M = T.height;
                            g.uniform2fv(e.uniforms.u_texsize, [
                                y,
                                M
                            ]);
                        }
                        g.uniform2f(e.uniforms.u_gl_units_to_pixels, 1 / i.transform.pixelsToGLUnits[0], 1 / i.transform.pixelsToGLUnits[1]);
                    }
                    s && (d ? (g.uniform1i(e.uniforms.u_image, 0), _.activeTexture.set(g.TEXTURE0), i.lineAtlas.bind(_), g.uniform1f(e.uniforms.u_tex_y_a, f.y), g.uniform1f(e.uniforms.u_tex_y_b, l.y), g.uniform1f(e.uniforms.u_mix, d.t)) : c && (g.uniform1i(e.uniforms.u_image, 0), _.activeTexture.set(g.TEXTURE0), i.imageManager.bind(_), g.uniform2fv(e.uniforms.u_pattern_tl_a, m.tl), g.uniform2fv(e.uniforms.u_pattern_br_a, m.br), g.uniform2fv(e.uniforms.u_pattern_tl_b, p.tl), g.uniform2fv(e.uniforms.u_pattern_br_b, p.br), g.uniform1f(e.uniforms.u_fade, c.t))), _.setStencilMode(i.stencilModeForClipping(a));
                    var b = i.translatePosMatrix(a.posMatrix, t, n.paint.get('line-translate'), n.paint.get('line-translate-anchor'));
                    g.uniformMatrix4fv(e.uniforms.u_matrix, !1, b), g.uniform1f(e.uniforms.u_ratio, 1 / pixelsToTileUnits(t, 1, i.transform.zoom)), e.draw(_, g.TRIANGLES, n.id, r.layoutVertexBuffer, r.indexBuffer, r.segments, o);
                }
                var browser = _dereq_('../util/browser'), pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = function (e, i, t, r) {
                    if ('translucent' === e.renderPass) {
                        if (0 !== t.paint.get('line-opacity').constantOr(1)) {
                            var n = e.context;
                            n.setDepthMode(e.depthModeForSublayer(0, DepthMode.ReadOnly)), n.setColorMode(e.colorModeForRenderPass());
                            for (var a, o = t.paint.get('line-dasharray') ? 'lineSDF' : t.paint.get('line-pattern') ? 'linePattern' : 'line', s = !0, u = 0, f = r; u < f.length; u += 1) {
                                var l = f[u], m = i.getTile(l), p = m.getBucket(t);
                                if (p) {
                                    var _ = p.programConfigurations.get(t.id), g = e.context.program.get(), d = e.useProgram(o, _), c = s || d.program !== g, x = a !== m.tileID.overscaledZ;
                                    c && _.setUniforms(e.context, d, t.paint, { zoom: e.transform.zoom }), drawLineTile(d, e, m, p, t, l, _, c, x), a = m.tileID.overscaledZ, s = !1;
                                }
                            }
                        }
                    }
                };
            },
            {
                '../gl/depth_mode': 67,
                '../source/pixels_to_tile_units': 104,
                '../util/browser': 252
            }
        ],
        83: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawRaster(e, r, t, a) {
                    if ('translucent' === e.renderPass && 0 !== t.paint.get('raster-opacity')) {
                        var i = e.context, o = i.gl, n = r.getSource(), s = e.useProgram('raster');
                        i.setStencilMode(StencilMode.disabled), i.setColorMode(e.colorModeForRenderPass()), o.uniform1f(s.uniforms.u_brightness_low, t.paint.get('raster-brightness-min')), o.uniform1f(s.uniforms.u_brightness_high, t.paint.get('raster-brightness-max')), o.uniform1f(s.uniforms.u_saturation_factor, saturationFactor(t.paint.get('raster-saturation'))), o.uniform1f(s.uniforms.u_contrast_factor, contrastFactor(t.paint.get('raster-contrast'))), o.uniform3fv(s.uniforms.u_spin_weights, spinWeights(t.paint.get('raster-hue-rotate'))), o.uniform1f(s.uniforms.u_buffer_scale, 1), o.uniform1i(s.uniforms.u_image0, 0), o.uniform1i(s.uniforms.u_image1, 1);
                        for (var u = a.length && a[0].overscaledZ, d = 0, f = a; d < f.length; d += 1) {
                            var c = f[d];
                            i.setDepthMode(e.depthModeForSublayer(c.overscaledZ - u, 1 === t.paint.get('raster-opacity') ? DepthMode.ReadWrite : DepthMode.ReadOnly, o.LESS));
                            var m = r.getTile(c), l = e.transform.calculatePosMatrix(c.toUnwrapped(), !0);
                            m.registerFadeDuration(t.paint.get('raster-fade-duration')), o.uniformMatrix4fv(s.uniforms.u_matrix, !1, l);
                            var g = r.findLoadedParent(c, 0, {}), p = getFadeValues(m, g, r, t, e.transform), _ = void 0, h = void 0;
                            if (i.activeTexture.set(o.TEXTURE0), m.texture.bind(o.LINEAR, o.CLAMP_TO_EDGE, o.LINEAR_MIPMAP_NEAREST), i.activeTexture.set(o.TEXTURE1), g ? (g.texture.bind(o.LINEAR, o.CLAMP_TO_EDGE, o.LINEAR_MIPMAP_NEAREST), _ = Math.pow(2, g.tileID.overscaledZ - m.tileID.overscaledZ), h = [
                                    m.tileID.canonical.x * _ % 1,
                                    m.tileID.canonical.y * _ % 1
                                ]) : m.texture.bind(o.LINEAR, o.CLAMP_TO_EDGE, o.LINEAR_MIPMAP_NEAREST), o.uniform2fv(s.uniforms.u_tl_parent, h || [
                                    0,
                                    0
                                ]), o.uniform1f(s.uniforms.u_scale_parent, _ || 1), o.uniform1f(s.uniforms.u_fade_t, p.mix), o.uniform1f(s.uniforms.u_opacity, p.opacity * t.paint.get('raster-opacity')), n instanceof ImageSource) {
                                var E = n.boundsBuffer;
                                n.boundsVAO.bind(i, s, E, []), o.drawArrays(o.TRIANGLE_STRIP, 0, E.length);
                            } else if (m.maskedBoundsBuffer && m.maskedIndexBuffer && m.segments) {
                                s.draw(i, o.TRIANGLES, t.id, m.maskedBoundsBuffer, m.maskedIndexBuffer, m.segments);
                            } else {
                                var M = e.rasterBoundsBuffer, v = e.rasterBoundsVAO;
                                v.bind(i, s, M, []), o.drawArrays(o.TRIANGLE_STRIP, 0, M.length);
                            }
                        }
                    }
                }
                function spinWeights(e) {
                    e *= Math.PI / 180;
                    var r = Math.sin(e), t = Math.cos(e);
                    return [
                        (2 * t + 1) / 3,
                        (-Math.sqrt(3) * r - t + 1) / 3,
                        (Math.sqrt(3) * r - t + 1) / 3
                    ];
                }
                function contrastFactor(e) {
                    return e > 0 ? 1 / (1 - e) : 1 + e;
                }
                function saturationFactor(e) {
                    return e > 0 ? 1 - 1 / (1.001 - e) : -e;
                }
                function getFadeValues(e, r, t, a, i) {
                    var o = a.paint.get('raster-fade-duration');
                    if (o > 0) {
                        var n = browser.now(), s = (n - e.timeAdded) / o, u = r ? (n - r.timeAdded) / o : -1, d = t.getSource(), f = i.coveringZoomLevel({
                                tileSize: d.tileSize,
                                roundZoom: d.roundZoom
                            }), c = !r || Math.abs(r.tileID.overscaledZ - f) > Math.abs(e.tileID.overscaledZ - f), m = c && e.refreshedUponExpiration ? 1 : util.clamp(c ? s : 1 - u, 0, 1);
                        return e.refreshedUponExpiration && s >= 1 && (e.refreshedUponExpiration = !1), r ? {
                            opacity: 1,
                            mix: 1 - m
                        } : {
                            opacity: m,
                            mix: 0
                        };
                    }
                    return {
                        opacity: 1,
                        mix: 0
                    };
                }
                var util = _dereq_('../util/util'), ImageSource = _dereq_('../source/image_source'), browser = _dereq_('../util/browser'), StencilMode = _dereq_('../gl/stencil_mode'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = drawRaster;
            },
            {
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../source/image_source': 102,
                '../util/browser': 252,
                '../util/util': 275
            }
        ],
        84: [
            function (_dereq_, module, exports) {
                'use strict';
                function drawSymbols(t, e, o, i) {
                    if ('translucent' === t.renderPass) {
                        var r = t.context;
                        r.setStencilMode(StencilMode.disabled), r.setColorMode(t.colorModeForRenderPass()), 0 !== o.paint.get('icon-opacity').constantOr(1) && drawLayerSymbols(t, e, o, i, !1, o.paint.get('icon-translate'), o.paint.get('icon-translate-anchor'), o.layout.get('icon-rotation-alignment'), o.layout.get('icon-pitch-alignment'), o.layout.get('icon-keep-upright')), 0 !== o.paint.get('text-opacity').constantOr(1) && drawLayerSymbols(t, e, o, i, !0, o.paint.get('text-translate'), o.paint.get('text-translate-anchor'), o.layout.get('text-rotation-alignment'), o.layout.get('text-pitch-alignment'), o.layout.get('text-keep-upright')), e.map.showCollisionBoxes && drawCollisionDebug(t, e, o, i);
                    }
                }
                function drawLayerSymbols(t, e, o, i, r, n, a, s, u, l) {
                    var m = t.context, f = m.gl, c = t.transform, y = 'map' === s, p = 'map' === u, _ = y && 'line' === o.layout.get('symbol-placement'), d = y && !p && !_, g = p;
                    m.setDepthMode(g ? t.depthModeForSublayer(0, DepthMode.ReadOnly) : DepthMode.disabled);
                    for (var x, b = 0, h = i; b < h.length; b += 1) {
                        var S = h[b], M = e.getTile(S), z = M.getBucket(o);
                        if (z) {
                            var T = r ? z.text : z.icon;
                            if (T && T.segments.get().length) {
                                var v = T.programConfigurations.get(o.id), w = r || z.sdfIcons, D = r ? z.textSizeData : z.iconSizeData;
                                if (x || (x = t.useProgram(w ? 'symbolSDF' : 'symbolIcon', v), v.setUniforms(t.context, x, o.paint, { zoom: t.transform.zoom }), setSymbolDrawState(x, t, o, r, d, p, D)), m.activeTexture.set(f.TEXTURE0), f.uniform1i(x.uniforms.u_texture, 0), r) {
                                    M.glyphAtlasTexture.bind(f.LINEAR, f.CLAMP_TO_EDGE), f.uniform2fv(x.uniforms.u_texsize, M.glyphAtlasTexture.size);
                                } else {
                                    var L = 1 !== o.layout.get('icon-size').constantOr(0) || z.iconsNeedLinear, P = p || 0 !== c.pitch;
                                    M.iconAtlasTexture.bind(w || t.options.rotating || t.options.zooming || L || P ? f.LINEAR : f.NEAREST, f.CLAMP_TO_EDGE), f.uniform2fv(x.uniforms.u_texsize, M.iconAtlasTexture.size);
                                }
                                f.uniformMatrix4fv(x.uniforms.u_matrix, !1, t.translatePosMatrix(S.posMatrix, M, n, a));
                                var E = pixelsToTileUnits(M, 1, t.transform.zoom), C = symbolProjection.getLabelPlaneMatrix(S.posMatrix, p, y, t.transform, E), A = symbolProjection.getGlCoordMatrix(S.posMatrix, p, y, t.transform, E);
                                f.uniformMatrix4fv(x.uniforms.u_gl_coord_matrix, !1, t.translatePosMatrix(A, M, n, a, !0)), _ ? (f.uniformMatrix4fv(x.uniforms.u_label_plane_matrix, !1, identityMat4), symbolProjection.updateLineLabels(z, S.posMatrix, t, r, C, A, p, l)) : f.uniformMatrix4fv(x.uniforms.u_label_plane_matrix, !1, C), f.uniform1f(x.uniforms.u_fade_change, t.options.fadeDuration ? t.symbolFadeChange : 1), drawTileSymbols(x, v, t, o, M, T, r, w, p);
                            }
                        }
                    }
                }
                function setSymbolDrawState(t, e, o, i, r, n, a) {
                    var s = e.context.gl, u = e.transform;
                    s.uniform1i(t.uniforms.u_pitch_with_map, n ? 1 : 0), s.uniform1f(t.uniforms.u_is_text, i ? 1 : 0), s.uniform1f(t.uniforms.u_pitch, u.pitch / 360 * 2 * Math.PI);
                    var l = 'constant' === a.functionType || 'source' === a.functionType, m = 'constant' === a.functionType || 'camera' === a.functionType;
                    s.uniform1i(t.uniforms.u_is_size_zoom_constant, l ? 1 : 0), s.uniform1i(t.uniforms.u_is_size_feature_constant, m ? 1 : 0), s.uniform1f(t.uniforms.u_camera_to_center_distance, u.cameraToCenterDistance);
                    var f = symbolSize.evaluateSizeForZoom(a, u.zoom, symbolLayoutProperties.properties[i ? 'text-size' : 'icon-size']);
                    void 0 !== f.uSizeT && s.uniform1f(t.uniforms.u_size_t, f.uSizeT), void 0 !== f.uSize && s.uniform1f(t.uniforms.u_size, f.uSize), s.uniform1f(t.uniforms.u_aspect_ratio, u.width / u.height), s.uniform1i(t.uniforms.u_rotate_symbol, r ? 1 : 0);
                }
                function drawTileSymbols(t, e, o, i, r, n, a, s, u) {
                    var l = o.context, m = l.gl, f = o.transform;
                    if (s) {
                        var c = 0 !== i.paint.get(a ? 'text-halo-width' : 'icon-halo-width').constantOr(1), y = u ? Math.cos(f._pitch) * f.cameraToCenterDistance : 1;
                        m.uniform1f(t.uniforms.u_gamma_scale, y), c && (m.uniform1f(t.uniforms.u_is_halo, 1), drawSymbolElements(n, i, l, t)), m.uniform1f(t.uniforms.u_is_halo, 0);
                    }
                    drawSymbolElements(n, i, l, t);
                }
                function drawSymbolElements(t, e, o, i) {
                    i.draw(o, o.gl.TRIANGLES, e.id, t.layoutVertexBuffer, t.indexBuffer, t.segments, t.programConfigurations.get(e.id), t.dynamicLayoutVertexBuffer, t.opacityVertexBuffer);
                }
                var drawCollisionDebug = _dereq_('./draw_collision_debug'), pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), symbolProjection = _dereq_('../symbol/projection'), symbolSize = _dereq_('../symbol/symbol_size'), mat4 = _dereq_('@mapbox/gl-matrix').mat4, identityMat4 = mat4.identity(new Float32Array(16)), symbolLayoutProperties = _dereq_('../style/style_layer/symbol_style_layer_properties').layout, StencilMode = _dereq_('../gl/stencil_mode'), DepthMode = _dereq_('../gl/depth_mode');
                module.exports = drawSymbols;
            },
            {
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../source/pixels_to_tile_units': 104,
                '../style/style_layer/symbol_style_layer_properties': 209,
                '../symbol/projection': 224,
                '../symbol/symbol_size': 228,
                './draw_collision_debug': 76,
                '@mapbox/gl-matrix': 2
            }
        ],
        85: [
            function (_dereq_, module, exports) {
                'use strict';
                function makeGlyphAtlas(a) {
                    var e = new AlphaImage({
                            width: 0,
                            height: 0
                        }), i = {}, t = new ShelfPack(0, 0, { autoResize: !0 });
                    for (var h in a) {
                        var r = a[h], p = i[h] = {};
                        for (var m in r) {
                            var d = r[+m];
                            if (d && 0 !== d.bitmap.width && 0 !== d.bitmap.height) {
                                var g = t.packOne(d.bitmap.width + 2 * padding, d.bitmap.height + 2 * padding);
                                e.resize({
                                    width: t.w,
                                    height: t.h
                                }), AlphaImage.copy(d.bitmap, e, {
                                    x: 0,
                                    y: 0
                                }, {
                                    x: g.x + padding,
                                    y: g.y + padding
                                }, d.bitmap), p[m] = {
                                    rect: g,
                                    metrics: d.metrics
                                };
                            }
                        }
                    }
                    return t.shrink(), e.resize({
                        width: t.w,
                        height: t.h
                    }), {
                        image: e,
                        positions: i
                    };
                }
                var ShelfPack = _dereq_('@mapbox/shelf-pack'), ref = _dereq_('../util/image'), AlphaImage = ref.AlphaImage, padding = 1;
                module.exports = { makeGlyphAtlas: makeGlyphAtlas };
            },
            {
                '../util/image': 263,
                '@mapbox/shelf-pack': 5
            }
        ],
        86: [
            function (_dereq_, module, exports) {
                'use strict';
                var loadGlyphRange = _dereq_('../style/load_glyph_range'), TinySDF = _dereq_('@mapbox/tiny-sdf'), isChar = _dereq_('../util/is_char_in_unicode_block'), ref = _dereq_('../util/util'), asyncAll = ref.asyncAll, ref$1 = _dereq_('../util/image'), AlphaImage = ref$1.AlphaImage, GlyphManager = function (e, r) {
                        this.requestTransform = e, this.localIdeographFontFamily = r, this.entries = {};
                    };
                GlyphManager.prototype.setURL = function (e) {
                    this.url = e;
                }, GlyphManager.prototype.getGlyphs = function (e, r) {
                    var i = this, t = [];
                    for (var a in e) {
                        for (var l = 0, n = e[a]; l < n.length; l += 1) {
                            var s = n[l];
                            t.push({
                                stack: a,
                                id: s
                            });
                        }
                    }
                    asyncAll(t, function (e, r) {
                        var t = e.stack, a = e.id, l = i.entries[t];
                        l || (l = i.entries[t] = {
                            glyphs: {},
                            requests: {}
                        });
                        var n = l.glyphs[a];
                        if (void 0 !== n) {
                            return void r(null, {
                                stack: t,
                                id: a,
                                glyph: n
                            });
                        }
                        if (n = i._tinySDF(l, t, a)) {
                            return void r(null, {
                                stack: t,
                                id: a,
                                glyph: n
                            });
                        }
                        var s = Math.floor(a / 256);
                        if (256 * s > 65535) {
                            return void r(new Error('glyphs > 65535 not supported'));
                        }
                        var o = l.requests[s];
                        o || (o = l.requests[s] = [], loadGlyphRange(t, s, i.url, i.requestTransform, function (e, r) {
                            if (r) {
                                for (var i in r) {
                                    l.glyphs[+i] = r[+i];
                                }
                            }
                            for (var t = 0, a = o; t < a.length; t += 1) {
                                (0, a[t])(e, r);
                            }
                            delete l.requests[s];
                        })), o.push(function (e, i) {
                            e ? r(e) : i && r(null, {
                                stack: t,
                                id: a,
                                glyph: i[a] || null
                            });
                        });
                    }, function (e, i) {
                        if (e) {
                            r(e);
                        } else if (i) {
                            for (var t = {}, a = 0, l = i; a < l.length; a += 1) {
                                var n = l[a], s = n.stack, o = n.id, h = n.glyph;
                                (t[s] || (t[s] = {}))[o] = h && {
                                    id: h.id,
                                    bitmap: h.bitmap.clone(),
                                    metrics: h.metrics
                                };
                            }
                            r(null, t);
                        }
                    });
                }, GlyphManager.prototype._tinySDF = function (e, r, i) {
                    var t = this.localIdeographFontFamily;
                    if (t && (isChar['CJK Unified Ideographs'](i) || isChar['Hangul Syllables'](i))) {
                        var a = e.tinySDF;
                        if (!a) {
                            var l = '400';
                            /bold/i.test(r) ? l = '900' : /medium/i.test(r) ? l = '500' : /light/i.test(r) && (l = '200'), a = e.tinySDF = new TinySDF(24, 3, 8, 0.25, t, l);
                        }
                        return {
                            id: i,
                            bitmap: new AlphaImage({
                                width: 30,
                                height: 30
                            }, a.draw(String.fromCharCode(i))),
                            metrics: {
                                width: 24,
                                height: 24,
                                left: 0,
                                top: -8,
                                advance: 24
                            }
                        };
                    }
                }, module.exports = GlyphManager;
            },
            {
                '../style/load_glyph_range': 184,
                '../util/image': 263,
                '../util/is_char_in_unicode_block': 265,
                '../util/util': 275,
                '@mapbox/tiny-sdf': 6
            }
        ],
        87: [
            function (_dereq_, module, exports) {
                'use strict';
                function imagePosition(a, i) {
                    var e = i.pixelRatio, t = {
                            x: a.x + padding,
                            y: a.y + padding,
                            w: a.w - 2 * padding,
                            h: a.h - 2 * padding
                        };
                    return {
                        pixelRatio: e,
                        textureRect: t,
                        tl: [
                            t.x,
                            t.y
                        ],
                        br: [
                            t.x + t.w,
                            t.y + t.h
                        ],
                        displaySize: [
                            t.w / e,
                            t.h / e
                        ]
                    };
                }
                function makeImageAtlas(a) {
                    var i = new RGBAImage({
                            width: 0,
                            height: 0
                        }), e = {}, t = new ShelfPack(0, 0, { autoResize: !0 });
                    for (var d in a) {
                        var g = a[d], n = t.packOne(g.data.width + 2 * padding, g.data.height + 2 * padding);
                        i.resize({
                            width: t.w,
                            height: t.h
                        }), RGBAImage.copy(g.data, i, {
                            x: 0,
                            y: 0
                        }, {
                            x: n.x + padding,
                            y: n.y + padding
                        }, g.data), e[d] = imagePosition(n, g);
                    }
                    return t.shrink(), i.resize({
                        width: t.w,
                        height: t.h
                    }), {
                        image: i,
                        positions: e
                    };
                }
                var ShelfPack = _dereq_('@mapbox/shelf-pack'), ref = _dereq_('../util/image'), RGBAImage = ref.RGBAImage, padding = 1;
                module.exports = {
                    imagePosition: imagePosition,
                    makeImageAtlas: makeImageAtlas
                };
            },
            {
                '../util/image': 263,
                '@mapbox/shelf-pack': 5
            }
        ],
        88: [
            function (_dereq_, module, exports) {
                'use strict';
                var ShelfPack = _dereq_('@mapbox/shelf-pack'), ref = _dereq_('../util/image'), RGBAImage = ref.RGBAImage, ref$1 = _dereq_('./image_atlas'), imagePosition = ref$1.imagePosition, Texture = _dereq_('./texture'), padding = 1, ImageManager = function () {
                        this.images = {}, this.loaded = !1, this.requestors = [], this.shelfPack = new ShelfPack(64, 64, { autoResize: !0 }), this.patterns = {}, this.atlasImage = new RGBAImage({
                            width: 64,
                            height: 64
                        }), this.dirty = !0;
                    };
                ImageManager.prototype.isLoaded = function () {
                    return this.loaded;
                }, ImageManager.prototype.setLoaded = function (e) {
                    var t = this;
                    if (this.loaded !== e && (this.loaded = e, e)) {
                        for (var a = 0, i = t.requestors; a < i.length; a += 1) {
                            var r = i[a], s = r.ids, h = r.callback;
                            t._notify(s, h);
                        }
                        this.requestors = [];
                    }
                }, ImageManager.prototype.getImage = function (e) {
                    return this.images[e];
                }, ImageManager.prototype.addImage = function (e, t) {
                    this.images[e] = t;
                }, ImageManager.prototype.removeImage = function (e) {
                    delete this.images[e];
                    var t = this.patterns[e];
                    t && (this.shelfPack.unref(t.bin), delete this.patterns[e]);
                }, ImageManager.prototype.getImages = function (e, t) {
                    var a = this, i = !0;
                    if (!this.isLoaded()) {
                        for (var r = 0, s = e; r < s.length; r += 1) {
                            var h = s[r];
                            a.images[h] || (i = !1);
                        }
                    }
                    this.isLoaded() || i ? this._notify(e, t) : this.requestors.push({
                        ids: e,
                        callback: t
                    });
                }, ImageManager.prototype._notify = function (e, t) {
                    for (var a = this, i = {}, r = 0, s = e; r < s.length; r += 1) {
                        var h = s[r], g = a.images[h];
                        g && (i[h] = {
                            data: g.data.clone(),
                            pixelRatio: g.pixelRatio,
                            sdf: g.sdf
                        });
                    }
                    t(null, i);
                }, ImageManager.prototype.getPixelSize = function () {
                    return {
                        width: this.shelfPack.w,
                        height: this.shelfPack.h
                    };
                }, ImageManager.prototype.getPattern = function (e) {
                    var t = this.patterns[e];
                    if (t) {
                        return t.position;
                    }
                    var a = this.getImage(e);
                    if (!a) {
                        return null;
                    }
                    var i = a.data.width + 2 * padding, r = a.data.height + 2 * padding, s = this.shelfPack.packOne(i, r);
                    if (!s) {
                        return null;
                    }
                    this.atlasImage.resize(this.getPixelSize());
                    var h = a.data, g = this.atlasImage, n = s.x + padding, o = s.y + padding, d = h.width, l = h.height;
                    RGBAImage.copy(h, g, {
                        x: 0,
                        y: 0
                    }, {
                        x: n,
                        y: o
                    }, {
                        width: d,
                        height: l
                    }), RGBAImage.copy(h, g, {
                        x: 0,
                        y: l - 1
                    }, {
                        x: n,
                        y: o - 1
                    }, {
                        width: d,
                        height: 1
                    }), RGBAImage.copy(h, g, {
                        x: 0,
                        y: 0
                    }, {
                        x: n,
                        y: o + l
                    }, {
                        width: d,
                        height: 1
                    }), RGBAImage.copy(h, g, {
                        x: d - 1,
                        y: 0
                    }, {
                        x: n - 1,
                        y: o
                    }, {
                        width: 1,
                        height: l
                    }), RGBAImage.copy(h, g, {
                        x: 0,
                        y: 0
                    }, {
                        x: n + d,
                        y: o
                    }, {
                        width: 1,
                        height: l
                    }), this.dirty = !0;
                    var p = imagePosition(s, a);
                    return this.patterns[e] = {
                        bin: s,
                        position: p
                    }, p;
                }, ImageManager.prototype.bind = function (e) {
                    var t = e.gl;
                    this.atlasTexture ? this.dirty && (this.atlasTexture.update(this.atlasImage), this.dirty = !1) : this.atlasTexture = new Texture(e, this.atlasImage, t.RGBA), this.atlasTexture.bind(t.LINEAR, t.CLAMP_TO_EDGE);
                }, module.exports = ImageManager;
            },
            {
                '../util/image': 263,
                './image_atlas': 87,
                './texture': 93,
                '@mapbox/shelf-pack': 5
            }
        ],
        89: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), LineAtlas = function (t, i) {
                        this.width = t, this.height = i, this.nextRow = 0, this.bytes = 4, this.data = new Uint8Array(this.width * this.height * this.bytes), this.positions = {};
                    };
                LineAtlas.prototype.getDash = function (t, i) {
                    var e = t.join(',') + String(i);
                    return this.positions[e] || (this.positions[e] = this.addDash(t, i)), this.positions[e];
                }, LineAtlas.prototype.addDash = function (t, i) {
                    var e = this, h = i ? 7 : 0, s = 2 * h + 1;
                    if (this.nextRow + s > this.height) {
                        return util.warnOnce('LineAtlas out of space'), null;
                    }
                    for (var a = 0, r = 0; r < t.length; r++) {
                        a += t[r];
                    }
                    for (var n = this.width / a, E = n / 2, T = t.length % 2 == 1, o = -h; o <= h; o++) {
                        for (var R = e.nextRow + h + o, d = e.width * R, u = T ? -t[t.length - 1] : 0, l = t[0], x = 1, _ = 0; _ < this.width; _++) {
                            for (; l < _ / n;) {
                                u = l, l += t[x], T && x === t.length - 1 && (l += t[0]), x++;
                            }
                            var g = Math.abs(_ - u * n), A = Math.abs(_ - l * n), w = Math.min(g, A), D = x % 2 == 1, U = void 0;
                            if (i) {
                                var f = h ? o / h * (E + 1) : 0;
                                if (D) {
                                    var p = E - Math.abs(f);
                                    U = Math.sqrt(w * w + p * p);
                                } else {
                                    U = E - Math.sqrt(w * w + f * f);
                                }
                            } else {
                                U = (D ? 1 : -1) * w;
                            }
                            e.data[3 + 4 * (d + _)] = Math.max(0, Math.min(255, U + 128));
                        }
                    }
                    var v = {
                        y: (this.nextRow + h + 0.5) / this.height,
                        height: 2 * h / this.height,
                        width: a
                    };
                    return this.nextRow += s, this.dirty = !0, v;
                }, LineAtlas.prototype.bind = function (t) {
                    var i = t.gl;
                    this.texture ? (i.bindTexture(i.TEXTURE_2D, this.texture), this.dirty && (this.dirty = !1, i.texSubImage2D(i.TEXTURE_2D, 0, 0, 0, this.width, this.height, i.RGBA, i.UNSIGNED_BYTE, this.data))) : (this.texture = i.createTexture(), i.bindTexture(i.TEXTURE_2D, this.texture), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_WRAP_S, i.REPEAT), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_WRAP_T, i.REPEAT), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_MIN_FILTER, i.LINEAR), i.texParameteri(i.TEXTURE_2D, i.TEXTURE_MAG_FILTER, i.LINEAR), i.texImage2D(i.TEXTURE_2D, 0, i.RGBA, this.width, this.height, 0, i.RGBA, i.UNSIGNED_BYTE, this.data));
                }, module.exports = LineAtlas;
            },
            { '../util/util': 275 }
        ],
        90: [
            function (_dereq_, module, exports) {
                'use strict';
                var browser = _dereq_('../util/browser'), mat4 = _dereq_('@mapbox/gl-matrix').mat4, SourceCache = _dereq_('../source/source_cache'), EXTENT = _dereq_('../data/extent'), pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), util = _dereq_('../util/util'), VertexArrayObject = _dereq_('./vertex_array_object'), ref = _dereq_('../data/array_types'), RasterBoundsArray = ref.RasterBoundsArray, PosArray = ref.PosArray, rasterBoundsAttributes = _dereq_('../data/raster_bounds_attributes'), posAttributes = _dereq_('../data/pos_attributes'), ref$1 = _dereq_('../data/program_configuration'), ProgramConfiguration = ref$1.ProgramConfiguration, CrossTileSymbolIndex = _dereq_('../symbol/cross_tile_symbol_index'), shaders = _dereq_('../shaders'), Program = _dereq_('./program'), Context = _dereq_('../gl/context'), DepthMode = _dereq_('../gl/depth_mode'), StencilMode = _dereq_('../gl/stencil_mode'), ColorMode = _dereq_('../gl/color_mode'), Texture = _dereq_('./texture'), updateTileMasks = _dereq_('./tile_mask'), Color = _dereq_('../style-spec/util/color'), draw = {
                        symbol: _dereq_('./draw_symbol'),
                        circle: _dereq_('./draw_circle'),
                        heatmap: _dereq_('./draw_heatmap'),
                        line: _dereq_('./draw_line'),
                        fill: _dereq_('./draw_fill'),
                        'fill-extrusion': _dereq_('./draw_fill_extrusion'),
                        hillshade: _dereq_('./draw_hillshade'),
                        raster: _dereq_('./draw_raster'),
                        background: _dereq_('./draw_background'),
                        debug: _dereq_('./draw_debug')
                    }, Painter = function (e, r) {
                        this.context = new Context(e), this.transform = r, this._tileTextures = {}, this.setup(), this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1, this.depthEpsilon = 1 / Math.pow(2, 16), this.depthRboNeedsClear = !0, this.emptyProgramConfiguration = new ProgramConfiguration(), this.crossTileSymbolIndex = new CrossTileSymbolIndex();
                    };
                Painter.prototype.resize = function (e, r) {
                    var t = this, i = this.context.gl;
                    if (this.width = e * browser.devicePixelRatio, this.height = r * browser.devicePixelRatio, this.context.viewport.set([
                            0,
                            0,
                            this.width,
                            this.height
                        ]), this.style) {
                        for (var s = 0, a = t.style._order; s < a.length; s += 1) {
                            var o = a[s];
                            t.style._layers[o].resize();
                        }
                    }
                    this.depthRbo && (i.deleteRenderbuffer(this.depthRbo), this.depthRbo = null);
                }, Painter.prototype.setup = function () {
                    var e = this.context, r = new PosArray();
                    r.emplaceBack(0, 0), r.emplaceBack(EXTENT, 0), r.emplaceBack(0, EXTENT), r.emplaceBack(EXTENT, EXTENT), this.tileExtentBuffer = e.createVertexBuffer(r, posAttributes.members), this.tileExtentVAO = new VertexArrayObject(), this.tileExtentPatternVAO = new VertexArrayObject();
                    var t = new PosArray();
                    t.emplaceBack(0, 0), t.emplaceBack(EXTENT, 0), t.emplaceBack(EXTENT, EXTENT), t.emplaceBack(0, EXTENT), t.emplaceBack(0, 0), this.debugBuffer = e.createVertexBuffer(t, posAttributes.members), this.debugVAO = new VertexArrayObject();
                    var i = new RasterBoundsArray();
                    i.emplaceBack(0, 0, 0, 0), i.emplaceBack(EXTENT, 0, EXTENT, 0), i.emplaceBack(0, EXTENT, 0, EXTENT), i.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT), this.rasterBoundsBuffer = e.createVertexBuffer(i, rasterBoundsAttributes.members), this.rasterBoundsVAO = new VertexArrayObject();
                    var s = new PosArray();
                    s.emplaceBack(0, 0), s.emplaceBack(1, 0), s.emplaceBack(0, 1), s.emplaceBack(1, 1), this.viewportBuffer = e.createVertexBuffer(s, posAttributes.members), this.viewportVAO = new VertexArrayObject();
                }, Painter.prototype.clearStencil = function () {
                    var e = this.context, r = e.gl;
                    e.setColorMode(ColorMode.disabled), e.setDepthMode(DepthMode.disabled), e.setStencilMode(new StencilMode({
                        func: r.ALWAYS,
                        mask: 0
                    }, 0, 255, r.ZERO, r.ZERO, r.ZERO));
                    var t = mat4.create();
                    mat4.ortho(t, 0, this.width, this.height, 0, 0, 1), mat4.scale(t, t, [
                        r.drawingBufferWidth,
                        r.drawingBufferHeight,
                        0
                    ]);
                    var i = this.useProgram('clippingMask');
                    r.uniformMatrix4fv(i.uniforms.u_matrix, !1, t), this.viewportVAO.bind(e, i, this.viewportBuffer, []), r.drawArrays(r.TRIANGLE_STRIP, 0, 4);
                }, Painter.prototype._renderTileClippingMasks = function (e) {
                    var r = this, t = this.context, i = t.gl;
                    t.setColorMode(ColorMode.disabled), t.setDepthMode(DepthMode.disabled);
                    var s = 1;
                    this._tileClippingMaskIDs = {};
                    for (var a = 0, o = e; a < o.length; a += 1) {
                        var n = o[a], l = r._tileClippingMaskIDs[n.key] = s++;
                        t.setStencilMode(new StencilMode({
                            func: i.ALWAYS,
                            mask: 0
                        }, l, 255, i.KEEP, i.KEEP, i.REPLACE));
                        var c = r.useProgram('clippingMask');
                        i.uniformMatrix4fv(c.uniforms.u_matrix, !1, n.posMatrix), r.tileExtentVAO.bind(r.context, c, r.tileExtentBuffer, []), i.drawArrays(i.TRIANGLE_STRIP, 0, r.tileExtentBuffer.length);
                    }
                }, Painter.prototype.stencilModeForClipping = function (e) {
                    var r = this.context.gl;
                    return new StencilMode({
                        func: r.EQUAL,
                        mask: 255
                    }, this._tileClippingMaskIDs[e.key], 0, r.KEEP, r.KEEP, r.REPLACE);
                }, Painter.prototype.colorModeForRenderPass = function () {
                    var e = this.context.gl;
                    if (this._showOverdrawInspector) {
                        return new ColorMode([
                            e.CONSTANT_COLOR,
                            e.ONE
                        ], new Color(1 / 8, 1 / 8, 1 / 8, 0), [
                            !0,
                            !0,
                            !0,
                            !0
                        ]);
                    }
                    return 'opaque' === this.renderPass ? ColorMode.unblended : ColorMode.alphaBlended;
                }, Painter.prototype.depthModeForSublayer = function (e, r, t) {
                    var i = 1 - ((1 + this.currentLayer) * this.numSublayers + e) * this.depthEpsilon, s = i - 1 + this.depthRange;
                    return new DepthMode(t || this.context.gl.LEQUAL, r, [
                        s,
                        i
                    ]);
                }, Painter.prototype.render = function (e, r) {
                    var t = this;
                    this.style = e, this.options = r, this.lineAtlas = e.lineAtlas, this.imageManager = e.imageManager, this.glyphManager = e.glyphManager, this.symbolFadeChange = e.placement.symbolFadeChange(browser.now());
                    for (var i in e.sourceCaches) {
                        var s = t.style.sourceCaches[i];
                        s.used && s.prepare(t.context);
                    }
                    var a = this.style._order, o = util.filterObject(this.style.sourceCaches, function (e) {
                            return 'raster' === e.getSource().type || 'raster-dem' === e.getSource().type;
                        });
                    for (var n in o) {
                        !function (e) {
                            var r = o[e], i = r.getVisibleCoordinates(), s = i.map(function (e) {
                                    return r.getTile(e);
                                });
                            updateTileMasks(s, t.context);
                        }(n);
                    }
                    this.renderPass = 'offscreen';
                    var l, c = [];
                    this.depthRboNeedsClear = !0;
                    for (var h = 0; h < a.length; h++) {
                        var u = t.style._layers[a[h]];
                        u.hasOffscreenPass() && !u.isHidden(t.transform.zoom) && (u.source !== (l && l.id) && (l = t.style.sourceCaches[u.source], c = [], l && (c = l.getVisibleCoordinates(), c.reverse())), c.length && t.renderLayer(t, l, u, c));
                    }
                    this.context.bindFramebuffer.set(null), this.context.clear({
                        color: r.showOverdrawInspector ? Color.black : Color.transparent,
                        depth: 1
                    }), this._showOverdrawInspector = r.showOverdrawInspector, this.depthRange = (e._order.length + 2) * this.numSublayers * this.depthEpsilon, this.renderPass = 'opaque';
                    var d, p = [];
                    for (this.currentLayer = a.length - 1, this.currentLayer; this.currentLayer >= 0; this.currentLayer--) {
                        var f = t.style._layers[a[t.currentLayer]];
                        f.source !== (d && d.id) && (d = t.style.sourceCaches[f.source], p = [], d && (t.clearStencil(), p = d.getVisibleCoordinates(), d.getSource().isTileClipped && t._renderTileClippingMasks(p))), t.renderLayer(t, d, f, p);
                    }
                    this.renderPass = 'translucent';
                    var m, g = [];
                    for (this.currentLayer = 0, this.currentLayer; this.currentLayer < a.length; this.currentLayer++) {
                        var y = t.style._layers[a[t.currentLayer]];
                        y.source !== (m && m.id) && (m = t.style.sourceCaches[y.source], g = [], m && (t.clearStencil(), g = m.getVisibleCoordinates(), m.getSource().isTileClipped && t._renderTileClippingMasks(g)), g.reverse()), t.renderLayer(t, m, y, g);
                    }
                    if (this.options.showTileBoundaries) {
                        var b = this.style.sourceCaches[Object.keys(this.style.sourceCaches)[0]];
                        b && draw.debug(this, b, b.getVisibleCoordinates());
                    }
                }, Painter.prototype.setupOffscreenDepthRenderbuffer = function () {
                    var e = this.context;
                    this.depthRbo || (this.depthRbo = e.createRenderbuffer(e.gl.DEPTH_COMPONENT16, this.width, this.height));
                }, Painter.prototype.renderLayer = function (e, r, t, i) {
                    t.isHidden(this.transform.zoom) || ('background' === t.type || i.length) && (this.id = t.id, draw[t.type](e, r, t, i));
                }, Painter.prototype.translatePosMatrix = function (e, r, t, i, s) {
                    if (!t[0] && !t[1]) {
                        return e;
                    }
                    var a = s ? 'map' === i ? this.transform.angle : 0 : 'viewport' === i ? -this.transform.angle : 0;
                    if (a) {
                        var o = Math.sin(a), n = Math.cos(a);
                        t = [
                            t[0] * n - t[1] * o,
                            t[0] * o + t[1] * n
                        ];
                    }
                    var l = [
                            s ? t[0] : pixelsToTileUnits(r, t[0], this.transform.zoom),
                            s ? t[1] : pixelsToTileUnits(r, t[1], this.transform.zoom),
                            0
                        ], c = new Float32Array(16);
                    return mat4.translate(c, e, l), c;
                }, Painter.prototype.saveTileTexture = function (e) {
                    var r = this._tileTextures[e.size[0]];
                    r ? r.push(e) : this._tileTextures[e.size[0]] = [e];
                }, Painter.prototype.getTileTexture = function (e) {
                    var r = this._tileTextures[e];
                    return r && r.length > 0 ? r.pop() : null;
                }, Painter.prototype._createProgramCached = function (e, r) {
                    this.cache = this.cache || {};
                    var t = '' + e + (r.cacheKey || '') + (this._showOverdrawInspector ? '/overdraw' : '');
                    return this.cache[t] || (this.cache[t] = new Program(this.context, shaders[e], r, this._showOverdrawInspector)), this.cache[t];
                }, Painter.prototype.useProgram = function (e, r) {
                    var t = this._createProgramCached(e, r || this.emptyProgramConfiguration);
                    return this.context.program.set(t.program), t;
                }, module.exports = Painter;
            },
            {
                '../data/array_types': 39,
                '../data/extent': 53,
                '../data/pos_attributes': 57,
                '../data/program_configuration': 58,
                '../data/raster_bounds_attributes': 59,
                '../gl/color_mode': 65,
                '../gl/context': 66,
                '../gl/depth_mode': 67,
                '../gl/stencil_mode': 70,
                '../shaders': 97,
                '../source/pixels_to_tile_units': 104,
                '../source/source_cache': 111,
                '../style-spec/util/color': 153,
                '../symbol/cross_tile_symbol_index': 218,
                '../util/browser': 252,
                '../util/util': 275,
                './draw_background': 74,
                './draw_circle': 75,
                './draw_debug': 77,
                './draw_fill': 78,
                './draw_fill_extrusion': 79,
                './draw_heatmap': 80,
                './draw_hillshade': 81,
                './draw_line': 82,
                './draw_raster': 83,
                './draw_symbol': 84,
                './program': 92,
                './texture': 93,
                './tile_mask': 94,
                './vertex_array_object': 95,
                '@mapbox/gl-matrix': 2
            }
        ],
        91: [
            function (_dereq_, module, exports) {
                'use strict';
                var pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units');
                exports.isPatternMissing = function (e, i) {
                    if (!e) {
                        return !1;
                    }
                    var r = i.imageManager.getPattern(e.from), t = i.imageManager.getPattern(e.to);
                    return !r || !t;
                }, exports.prepare = function (e, i, r) {
                    var t = i.context, n = t.gl, o = i.imageManager.getPattern(e.from), a = i.imageManager.getPattern(e.to);
                    n.uniform1i(r.uniforms.u_image, 0), n.uniform2fv(r.uniforms.u_pattern_tl_a, o.tl), n.uniform2fv(r.uniforms.u_pattern_br_a, o.br), n.uniform2fv(r.uniforms.u_pattern_tl_b, a.tl), n.uniform2fv(r.uniforms.u_pattern_br_b, a.br);
                    var u = i.imageManager.getPixelSize(), f = u.width, m = u.height;
                    n.uniform2fv(r.uniforms.u_texsize, [
                        f,
                        m
                    ]), n.uniform1f(r.uniforms.u_mix, e.t), n.uniform2fv(r.uniforms.u_pattern_size_a, o.displaySize), n.uniform2fv(r.uniforms.u_pattern_size_b, a.displaySize), n.uniform1f(r.uniforms.u_scale_a, e.fromScale), n.uniform1f(r.uniforms.u_scale_b, e.toScale), t.activeTexture.set(n.TEXTURE0), i.imageManager.bind(i.context);
                }, exports.setTile = function (e, i, r) {
                    var t = i.context.gl;
                    t.uniform1f(r.uniforms.u_tile_units_to_pixels, 1 / pixelsToTileUnits(e, 1, i.transform.tileZoom));
                    var n = Math.pow(2, e.tileID.overscaledZ), o = e.tileSize * Math.pow(2, i.transform.tileZoom) / n, a = o * (e.tileID.canonical.x + e.tileID.wrap * n), u = o * e.tileID.canonical.y;
                    t.uniform2f(r.uniforms.u_pixel_coord_upper, a >> 16, u >> 16), t.uniform2f(r.uniforms.u_pixel_coord_lower, 65535 & a, 65535 & u);
                };
            },
            { '../source/pixels_to_tile_units': 104 }
        ],
        92: [
            function (_dereq_, module, exports) {
                'use strict';
                var browser = _dereq_('../util/browser'), shaders = _dereq_('../shaders'), ref = _dereq_('../data/program_configuration'), ProgramConfiguration = ref.ProgramConfiguration, VertexArrayObject = _dereq_('./vertex_array_object'), Context = _dereq_('../gl/context'), Program = function (r, e, t, a) {
                        var o = this, i = r.gl;
                        this.program = i.createProgram();
                        var n = t.defines().concat('#define DEVICE_PIXEL_RATIO ' + browser.devicePixelRatio.toFixed(1));
                        a && n.push('#define OVERDRAW_INSPECTOR;');
                        var s = n.concat(shaders.prelude.fragmentSource, e.fragmentSource).join('\n'), m = n.concat(shaders.prelude.vertexSource, e.vertexSource).join('\n'), g = i.createShader(i.FRAGMENT_SHADER);
                        i.shaderSource(g, s), i.compileShader(g), i.attachShader(this.program, g);
                        var c = i.createShader(i.VERTEX_SHADER);
                        i.shaderSource(c, m), i.compileShader(c), i.attachShader(this.program, c);
                        for (var u = t.layoutAttributes || [], h = 0; h < u.length; h++) {
                            i.bindAttribLocation(o.program, h, u[h].name);
                        }
                        i.linkProgram(this.program), this.numAttributes = i.getProgramParameter(this.program, i.ACTIVE_ATTRIBUTES), this.attributes = {}, this.uniforms = {};
                        for (var f = 0; f < this.numAttributes; f++) {
                            var d = i.getActiveAttrib(o.program, f);
                            d && (o.attributes[d.name] = i.getAttribLocation(o.program, d.name));
                        }
                        for (var v = i.getProgramParameter(this.program, i.ACTIVE_UNIFORMS), p = 0; p < v; p++) {
                            var S = i.getActiveUniform(o.program, p);
                            S && (o.uniforms[S.name] = i.getUniformLocation(o.program, S.name));
                        }
                    };
                Program.prototype.draw = function (r, e, t, a, o, i, n, s, m) {
                    for (var g, c = this, u = r.gl, h = (g = {}, g[u.LINES] = 2, g[u.TRIANGLES] = 3, g)[e], f = 0, d = i.get(); f < d.length; f += 1) {
                        var v = d[f], p = v.vaos || (v.vaos = {});
                        (p[t] || (p[t] = new VertexArrayObject())).bind(r, c, a, n ? n.getPaintVertexBuffers() : [], o, v.vertexOffset, s, m), u.drawElements(e, v.primitiveLength * h, u.UNSIGNED_SHORT, v.primitiveOffset * h * 2);
                    }
                }, module.exports = Program;
            },
            {
                '../data/program_configuration': 58,
                '../gl/context': 66,
                '../shaders': 97,
                '../util/browser': 252,
                './vertex_array_object': 95
            }
        ],
        93: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/window'), HTMLImageElement = ref.HTMLImageElement, HTMLCanvasElement = ref.HTMLCanvasElement, HTMLVideoElement = ref.HTMLVideoElement, ImageData = ref.ImageData, Texture = function (e, t, i, r) {
                        this.context = e;
                        var a = t.width, T = t.height;
                        this.size = [
                            a,
                            T
                        ], this.format = i, this.texture = e.gl.createTexture(), this.update(t, r);
                    };
                Texture.prototype.update = function (e, t) {
                    var i = e.width, r = e.height;
                    this.size = [
                        i,
                        r
                    ];
                    var a = this, T = a.context, n = T.gl;
                    n.bindTexture(n.TEXTURE_2D, this.texture), T.pixelStoreUnpack.set(1), this.format === n.RGBA && !1 !== t && T.pixelStoreUnpackPremultiplyAlpha.set(!0), e instanceof HTMLImageElement || e instanceof HTMLCanvasElement || e instanceof HTMLVideoElement || e instanceof ImageData ? n.texImage2D(n.TEXTURE_2D, 0, this.format, this.format, n.UNSIGNED_BYTE, e) : n.texImage2D(n.TEXTURE_2D, 0, this.format, i, r, 0, this.format, n.UNSIGNED_BYTE, e.data);
                }, Texture.prototype.bind = function (e, t, i) {
                    var r = this, a = r.context, T = a.gl;
                    T.bindTexture(T.TEXTURE_2D, this.texture), e !== this.filter && (T.texParameteri(T.TEXTURE_2D, T.TEXTURE_MAG_FILTER, e), T.texParameteri(T.TEXTURE_2D, T.TEXTURE_MIN_FILTER, i || e), this.filter = e), t !== this.wrap && (T.texParameteri(T.TEXTURE_2D, T.TEXTURE_WRAP_S, t), T.texParameteri(T.TEXTURE_2D, T.TEXTURE_WRAP_T, t), this.wrap = t);
                }, Texture.prototype.destroy = function () {
                    this.context.gl.deleteTexture(this.texture), this.texture = null;
                }, module.exports = Texture;
            },
            { '../util/window': 254 }
        ],
        94: [
            function (_dereq_, module, exports) {
                'use strict';
                function computeTileMasks(e, i, l, a, r) {
                    for (var n = 0; n < l.length; n++) {
                        var s = l[n];
                        if (a.isLessThan(s.tileID)) {
                            break;
                        }
                        if (i.key === s.tileID.key) {
                            return;
                        }
                        if (s.tileID.isChildOf(i)) {
                            for (var t = i.children(1 / 0), c = 0; c < t.length; c++) {
                                computeTileMasks(e, t[c], l.slice(n), a, r);
                            }
                            return;
                        }
                    }
                    var o = i.overscaledZ - e.overscaledZ, D = new CanonicalTileID(o, i.canonical.x - (e.canonical.x << o), i.canonical.y - (e.canonical.y << o));
                    r[D.key] = r[D.key] || D;
                }
                var ref = _dereq_('../source/tile_id'), OverscaledTileID = ref.OverscaledTileID, CanonicalTileID = ref.CanonicalTileID;
                module.exports = function (e, i) {
                    for (var l = e.sort(function (e, i) {
                                return e.tileID.isLessThan(i.tileID) ? -1 : i.tileID.isLessThan(e.tileID) ? 1 : 0;
                            }), a = 0; a < l.length; a++) {
                        var r = {}, n = l[a], s = l.slice(a + 1);
                        computeTileMasks(n.tileID.wrapped(), n.tileID, s, new OverscaledTileID(0, n.tileID.wrap + 1, 0, 0, 0), r), n.setMask(r, i);
                    }
                };
            },
            { '../source/tile_id': 114 }
        ],
        95: [
            function (_dereq_, module, exports) {
                'use strict';
                var VertexArrayObject = function () {
                    this.boundProgram = null, this.boundLayoutVertexBuffer = null, this.boundPaintVertexBuffers = [], this.boundIndexBuffer = null, this.boundVertexOffset = null, this.boundDynamicVertexBuffer = null, this.vao = null;
                };
                VertexArrayObject.prototype.bind = function (t, e, r, i, n, s, u, o) {
                    var b = this;
                    this.context = t;
                    for (var a = this.boundPaintVertexBuffers.length !== i.length, f = 0; !a && f < i.length; f++) {
                        b.boundPaintVertexBuffers[f] !== i[f] && (a = !0);
                    }
                    var x = !this.vao || this.boundProgram !== e || this.boundLayoutVertexBuffer !== r || a || this.boundIndexBuffer !== n || this.boundVertexOffset !== s || this.boundDynamicVertexBuffer !== u || this.boundDynamicVertexBuffer2 !== o;
                    !t.extVertexArrayObject || x ? this.freshBind(e, r, i, n, s, u, o) : (t.bindVertexArrayOES.set(this.vao), u && u.bind(), n && n.dynamicDraw && n.bind(), o && o.bind());
                }, VertexArrayObject.prototype.freshBind = function (t, e, r, i, n, s, u) {
                    var o, b = t.numAttributes, a = this.context, f = a.gl;
                    if (a.extVertexArrayObject) {
                        this.vao && this.destroy(), this.vao = a.extVertexArrayObject.createVertexArrayOES(), a.bindVertexArrayOES.set(this.vao), o = 0, this.boundProgram = t, this.boundLayoutVertexBuffer = e, this.boundPaintVertexBuffers = r, this.boundIndexBuffer = i, this.boundVertexOffset = n, this.boundDynamicVertexBuffer = s, this.boundDynamicVertexBuffer2 = u;
                    } else {
                        o = a.currentNumAttributes || 0;
                        for (var x = b; x < o; x++) {
                            f.disableVertexAttribArray(x);
                        }
                    }
                    e.enableAttributes(f, t);
                    for (var d = 0, h = r; d < h.length; d += 1) {
                        h[d].enableAttributes(f, t);
                    }
                    s && s.enableAttributes(f, t), u && u.enableAttributes(f, t), e.bind(), e.setVertexAttribPointers(f, t, n);
                    for (var V = 0, l = r; V < l.length; V += 1) {
                        var y = l[V];
                        y.bind(), y.setVertexAttribPointers(f, t, n);
                    }
                    s && (s.bind(), s.setVertexAttribPointers(f, t, n)), i && i.bind(), u && (u.bind(), u.setVertexAttribPointers(f, t, n)), a.currentNumAttributes = b;
                }, VertexArrayObject.prototype.destroy = function () {
                    this.vao && (this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao), this.vao = null);
                }, module.exports = VertexArrayObject;
            },
            {}
        ],
        96: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util');
                exports.packUint8ToFloat = function (t, l) {
                    return t = util.clamp(Math.floor(t), 0, 255), l = util.clamp(Math.floor(l), 0, 255), 256 * t + l;
                };
            },
            { '../util/util': 275 }
        ],
        97: [
            function (_dereq_, module, exports) {
                'use strict';
                var shaders = {
                        prelude: {
                            fragmentSource: '#ifdef GL_ES\nprecision mediump float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n',
                            vertexSource: '#ifdef GL_ES\nprecision highp float;\n#else\n\n#if !defined(lowp)\n#define lowp\n#endif\n\n#if !defined(mediump)\n#define mediump\n#endif\n\n#if !defined(highp)\n#define highp\n#endif\n\n#endif\n\n// Unpack a pair of values that have been packed into a single float.\n// The packed values are assumed to be 8-bit unsigned integers, and are\n// packed like so:\n// packedValue = floor(input[0]) * 256 + input[1],\nvec2 unpack_float(const float packedValue) {\n    int packedIntValue = int(packedValue);\n    int v0 = packedIntValue / 256;\n    return vec2(v0, packedIntValue - v0 * 256);\n}\n\nvec2 unpack_opacity(const float packedOpacity) {\n    int intOpacity = int(packedOpacity) / 2;\n    return vec2(float(intOpacity) / 127.0, mod(packedOpacity, 2.0));\n}\n\n// To minimize the number of attributes needed, we encode a 4-component\n// color into a pair of floats (i.e. a vec2) as follows:\n// [ floor(color.r * 255) * 256 + color.g * 255,\n//   floor(color.b * 255) * 256 + color.g * 255 ]\nvec4 decode_color(const vec2 encodedColor) {\n    return vec4(\n        unpack_float(encodedColor[0]) / 255.0,\n        unpack_float(encodedColor[1]) / 255.0\n    );\n}\n\n// Unpack a pair of paint values and interpolate between them.\nfloat unpack_mix_vec2(const vec2 packedValue, const float t) {\n    return mix(packedValue[0], packedValue[1], t);\n}\n\n// Unpack a pair of paint values and interpolate between them.\nvec4 unpack_mix_vec4(const vec4 packedColors, const float t) {\n    vec4 minColor = decode_color(vec2(packedColors[0], packedColors[1]));\n    vec4 maxColor = decode_color(vec2(packedColors[2], packedColors[3]));\n    return mix(minColor, maxColor, t);\n}\n\n// The offset depends on how many pixels are between the world origin and the edge of the tile:\n// vec2 offset = mod(pixel_coord, size)\n//\n// At high zoom levels there are a ton of pixels between the world origin and the edge of the tile.\n// The glsl spec only guarantees 16 bits of precision for highp floats. We need more than that.\n//\n// The pixel_coord is passed in as two 16 bit values:\n// pixel_coord_upper = floor(pixel_coord / 2^16)\n// pixel_coord_lower = mod(pixel_coord, 2^16)\n//\n// The offset is calculated in a series of steps that should preserve this precision:\nvec2 get_pattern_pos(const vec2 pixel_coord_upper, const vec2 pixel_coord_lower,\n    const vec2 pattern_size, const float tile_units_to_pixels, const vec2 pos) {\n\n    vec2 offset = mod(mod(mod(pixel_coord_upper, pattern_size) * 256.0, pattern_size) * 256.0 + pixel_coord_lower, pattern_size);\n    return (tile_units_to_pixels * pos + offset) / pattern_size;\n}\n'
                        },
                        background: {
                            fragmentSource: 'uniform vec4 u_color;\nuniform float u_opacity;\n\nvoid main() {\n    gl_FragColor = u_color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n'
                        },
                        backgroundPattern: {
                            fragmentSource: 'uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\nuniform float u_opacity;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n'
                        },
                        circle: {
                            fragmentSource: '#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    vec2 extrude = v_data.xy;\n    float extrude_length = length(extrude);\n\n    lowp float antialiasblur = v_data.z;\n    float antialiased_blur = -max(blur, antialiasblur);\n\n    float opacity_t = smoothstep(0.0, antialiased_blur, extrude_length - 1.0);\n\n    float color_t = stroke_width < 0.01 ? 0.0 : smoothstep(\n        antialiased_blur,\n        0.0,\n        extrude_length - radius / (radius + stroke_width)\n    );\n\n    gl_FragColor = opacity_t * mix(color * opacity, stroke_color * stroke_opacity, color_t);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform bool u_scale_with_map;\nuniform bool u_pitch_with_map;\nuniform vec2 u_extrude_scale;\nuniform highp float u_camera_to_center_distance;\n\nattribute vec2 a_pos;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define mediump float radius\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define highp vec4 stroke_color\n#pragma mapbox: define mediump float stroke_width\n#pragma mapbox: define lowp float stroke_opacity\n\nvarying vec3 v_data;\n\nvoid main(void) {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize mediump float radius\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize highp vec4 stroke_color\n    #pragma mapbox: initialize mediump float stroke_width\n    #pragma mapbox: initialize lowp float stroke_opacity\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec2 circle_center = floor(a_pos * 0.5);\n    if (u_pitch_with_map) {\n        vec2 corner_position = circle_center;\n        if (u_scale_with_map) {\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale;\n        } else {\n            // Pitching the circle with the map effectively scales it with the map\n            // To counteract the effect for pitch-scale: viewport, we rescale the\n            // whole circle based on the pitch scaling effect at its central point\n            vec4 projected_center = u_matrix * vec4(circle_center, 0, 1);\n            corner_position += extrude * (radius + stroke_width) * u_extrude_scale * (projected_center.w / u_camera_to_center_distance);\n        }\n\n        gl_Position = u_matrix * vec4(corner_position, 0, 1);\n    } else {\n        gl_Position = u_matrix * vec4(circle_center, 0, 1);\n\n        if (u_scale_with_map) {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * u_camera_to_center_distance;\n        } else {\n            gl_Position.xy += extrude * (radius + stroke_width) * u_extrude_scale * gl_Position.w;\n        }\n    }\n\n    // This is a minimum blur distance that serves as a faux-antialiasing for\n    // the circle. since blur is a ratio of the circle\'s size and the intent is\n    // to keep the blur at roughly 1px, the two are inversely related.\n    lowp float antialiasblur = 1.0 / DEVICE_PIXEL_RATIO / (radius + stroke_width);\n\n    v_data = vec3(extrude.x, extrude.y, antialiasblur);\n}\n'
                        },
                        clippingMask: {
                            fragmentSource: 'void main() {\n    gl_FragColor = vec4(1.0);\n}\n',
                            vertexSource: 'attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n'
                        },
                        heatmap: {
                            fragmentSource: '#pragma mapbox: define highp float weight\n\nuniform highp float u_intensity;\nvarying vec2 v_extrude;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main() {\n    #pragma mapbox: initialize highp float weight\n\n    // Kernel density estimation with a Gaussian kernel of size 5x5\n    float d = -0.5 * 3.0 * 3.0 * dot(v_extrude, v_extrude);\n    float val = weight * u_intensity * GAUSS_COEF * exp(d);\n\n    gl_FragColor = vec4(val, 1.0, 1.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: '#pragma mapbox: define highp float weight\n#pragma mapbox: define mediump float radius\n\nuniform mat4 u_matrix;\nuniform float u_extrude_scale;\nuniform float u_opacity;\nuniform float u_intensity;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_extrude;\n\n// Effective "0" in the kernel density texture to adjust the kernel size to;\n// this empirically chosen number minimizes artifacts on overlapping kernels\n// for typical heatmap cases (assuming clustered source)\nconst highp float ZERO = 1.0 / 255.0 / 16.0;\n\n// Gaussian kernel coefficient: 1 / sqrt(2 * PI)\n#define GAUSS_COEF 0.3989422804014327\n\nvoid main(void) {\n    #pragma mapbox: initialize highp float weight\n    #pragma mapbox: initialize mediump float radius\n\n    // unencode the extrusion vector that we snuck into the a_pos vector\n    vec2 unscaled_extrude = vec2(mod(a_pos, 2.0) * 2.0 - 1.0);\n\n    // This \'extrude\' comes in ranging from [-1, -1], to [1, 1].  We\'ll use\n    // it to produce the vertices of a square mesh framing the point feature\n    // we\'re adding to the kernel density texture.  We\'ll also pass it as\n    // a varying, so that the fragment shader can determine the distance of\n    // each fragment from the point feature.\n    // Before we do so, we need to scale it up sufficiently so that the\n    // kernel falls effectively to zero at the edge of the mesh.\n    // That is, we want to know S such that\n    // weight * u_intensity * GAUSS_COEF * exp(-0.5 * 3.0^2 * S^2) == ZERO\n    // Which solves to:\n    // S = sqrt(-2.0 * log(ZERO / (weight * u_intensity * GAUSS_COEF))) / 3.0\n    float S = sqrt(-2.0 * log(ZERO / weight / u_intensity / GAUSS_COEF)) / 3.0;\n\n    // Pass the varying in units of radius\n    v_extrude = S * unscaled_extrude;\n\n    // Scale by radius and the zoom-based scale factor to produce actual\n    // mesh position\n    vec2 extrude = v_extrude * radius * u_extrude_scale;\n\n    // multiply a_pos by 0.5, since we had it * 2 in order to sneak\n    // in extrusion data\n    vec4 pos = vec4(floor(a_pos * 0.5) + extrude, 0, 1);\n\n    gl_Position = u_matrix * pos;\n}\n'
                        },
                        heatmapTexture: {
                            fragmentSource: 'uniform sampler2D u_image;\nuniform sampler2D u_color_ramp;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    float t = texture2D(u_image, v_pos).r;\n    vec4 color = texture2D(u_color_ramp, vec2(t, 0.5));\n    gl_FragColor = color * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n'
                        },
                        collisionBox: {
                            fragmentSource: '\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        gl_FragColor *= .1;\n    }\n}',
                            vertexSource: 'attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n    gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n}\n'
                        },
                        collisionCircle: {
                            fragmentSource: '\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    float alpha = 0.5;\n\n    // Red = collision, hide label\n    vec4 color = vec4(1.0, 0.0, 0.0, 1.0) * alpha;\n\n    // Blue = no collision, label is showing\n    if (v_placed > 0.5) {\n        color = vec4(0.0, 0.0, 1.0, 0.5) * alpha;\n    }\n\n    if (v_notUsed > 0.5) {\n        // This box not used, fade it out\n        color *= .2;\n    }\n\n    float extrude_scale_length = length(v_extrude_scale);\n    float extrude_length = length(v_extrude) * extrude_scale_length;\n    float stroke_width = 15.0 * extrude_scale_length;\n    float radius = v_radius * extrude_scale_length;\n\n    float distance_to_edge = abs(extrude_length - radius);\n    float opacity_t = smoothstep(-stroke_width, 0.0, -distance_to_edge);\n\n    gl_FragColor = opacity_t * color;\n}\n',
                            vertexSource: 'attribute vec2 a_pos;\nattribute vec2 a_anchor_pos;\nattribute vec2 a_extrude;\nattribute vec2 a_placed;\n\nuniform mat4 u_matrix;\nuniform vec2 u_extrude_scale;\nuniform float u_camera_to_center_distance;\n\nvarying float v_placed;\nvarying float v_notUsed;\nvarying float v_radius;\n\nvarying vec2 v_extrude;\nvarying vec2 v_extrude_scale;\n\nvoid main() {\n    vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    highp float collision_perspective_ratio = 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance);\n\n    gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0);\n\n    highp float padding_factor = 1.2; // Pad the vertices slightly to make room for anti-alias blur\n    gl_Position.xy += a_extrude * u_extrude_scale * padding_factor * gl_Position.w * collision_perspective_ratio;\n\n    v_placed = a_placed.x;\n    v_notUsed = a_placed.y;\n    v_radius = abs(a_extrude.y); // We don\'t pitch the circles, so both units of the extrusion vector are equal in magnitude to the radius\n\n    v_extrude = a_extrude * padding_factor;\n    v_extrude_scale = u_extrude_scale * u_camera_to_center_distance * collision_perspective_ratio;\n}\n'
                        },
                        debug: {
                            fragmentSource: 'uniform highp vec4 u_color;\n\nvoid main() {\n    gl_FragColor = u_color;\n}\n',
                            vertexSource: 'attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n'
                        },
                        fill: {
                            fragmentSource: '#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_FragColor = color * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n}\n'
                        },
                        fillOutline: {
                            fragmentSource: '#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_pos;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n    gl_FragColor = outline_color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'attribute vec2 a_pos;\n\nuniform mat4 u_matrix;\nuniform vec2 u_world;\n\nvarying vec2 v_pos;\n\n#pragma mapbox: define highp vec4 outline_color\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 outline_color\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n'
                        },
                        fillOutlinePattern: {
                            fragmentSource: 'uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    // find distance to outline for alpha interpolation\n\n    float dist = length(v_pos - gl_FragCoord.xy);\n    float alpha = 1.0 - smoothstep(0.0, 1.0, dist);\n\n\n    gl_FragColor = mix(color1, color2, u_mix) * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_world;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec2 v_pos;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n\n    v_pos = (gl_Position.xy / gl_Position.w + 1.0) / 2.0 * u_world;\n}\n'
                        },
                        fillPattern: {
                            fragmentSource: 'uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    gl_FragColor = mix(color1, color2, u_mix) * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\n\nattribute vec2 a_pos;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\n\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, a_pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, a_pos);\n}\n'
                        },
                        fillExtrusion: {
                            fragmentSource: 'varying vec4 v_color;\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    gl_FragColor = v_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec4 v_color;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\n#pragma mapbox: define highp vec4 color\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n    #pragma mapbox: initialize highp vec4 color\n\n    vec3 normal = a_normal_ed.xyz;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n\n    gl_Position = u_matrix * vec4(a_pos, t > 0.0 ? height : base, 1);\n\n    // Relative luminance (how dark/bright is the surface color?)\n    float colorvalue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;\n\n    v_color = vec4(0.0, 0.0, 0.0, 1.0);\n\n    // Add slight ambient lighting so no extrusions are totally black\n    vec4 ambientlight = vec4(0.03, 0.03, 0.03, 1.0);\n    color += ambientlight;\n\n    // Calculate cos(theta), where theta is the angle between surface normal and diffuse light ray\n    float directional = clamp(dot(normal / 16384.0, u_lightpos), 0.0, 1.0);\n\n    // Adjust directional so that\n    // the range of values for highlight/shading is narrower\n    // with lower light intensity\n    // and with lighter/brighter surface colors\n    directional = mix((1.0 - u_lightintensity), max((1.0 - colorvalue + u_lightintensity), 1.0), directional);\n\n    // Add gradient along z axis of side surfaces\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    // Assign final color based on surface + ambient light color, diffuse light directional, and light color\n    // with lower bounds adjusted to hue of light\n    // so that shading is tinted with the complementary (opposite) color to the light color\n    v_color.r += clamp(color.r * directional * u_lightcolor.r, mix(0.0, 0.3, 1.0 - u_lightcolor.r), 1.0);\n    v_color.g += clamp(color.g * directional * u_lightcolor.g, mix(0.0, 0.3, 1.0 - u_lightcolor.g), 1.0);\n    v_color.b += clamp(color.b * directional * u_lightcolor.b, mix(0.0, 0.3, 1.0 - u_lightcolor.b), 1.0);\n}\n'
                        },
                        fillExtrusionPattern: {
                            fragmentSource: 'uniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_mix;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec2 imagecoord = mod(v_pos_a, 1.0);\n    vec2 pos = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, imagecoord);\n    vec4 color1 = texture2D(u_image, pos);\n\n    vec2 imagecoord_b = mod(v_pos_b, 1.0);\n    vec2 pos2 = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, imagecoord_b);\n    vec4 color2 = texture2D(u_image, pos2);\n\n    vec4 mixedColor = mix(color1, color2, u_mix);\n\n    gl_FragColor = mixedColor * v_lighting;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pixel_coord_upper;\nuniform vec2 u_pixel_coord_lower;\nuniform float u_scale_a;\nuniform float u_scale_b;\nuniform float u_tile_units_to_pixels;\nuniform float u_height_factor;\n\nuniform vec3 u_lightcolor;\nuniform lowp vec3 u_lightpos;\nuniform lowp float u_lightintensity;\n\nattribute vec2 a_pos;\nattribute vec4 a_normal_ed;\n\nvarying vec2 v_pos_a;\nvarying vec2 v_pos_b;\nvarying vec4 v_lighting;\nvarying float v_directional;\n\n#pragma mapbox: define lowp float base\n#pragma mapbox: define lowp float height\n\nvoid main() {\n    #pragma mapbox: initialize lowp float base\n    #pragma mapbox: initialize lowp float height\n\n    vec3 normal = a_normal_ed.xyz;\n    float edgedistance = a_normal_ed.w;\n\n    base = max(0.0, base);\n    height = max(0.0, height);\n\n    float t = mod(normal.x, 2.0);\n    float z = t > 0.0 ? height : base;\n\n    gl_Position = u_matrix * vec4(a_pos, z, 1);\n\n    vec2 pos = normal.x == 1.0 && normal.y == 0.0 && normal.z == 16384.0\n        ? a_pos // extrusion top\n        : vec2(edgedistance, z * u_height_factor); // extrusion side\n\n    v_pos_a = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_a * u_pattern_size_a, u_tile_units_to_pixels, pos);\n    v_pos_b = get_pattern_pos(u_pixel_coord_upper, u_pixel_coord_lower, u_scale_b * u_pattern_size_b, u_tile_units_to_pixels, pos);\n\n    v_lighting = vec4(0.0, 0.0, 0.0, 1.0);\n    float directional = clamp(dot(normal / 16383.0, u_lightpos), 0.0, 1.0);\n    directional = mix((1.0 - u_lightintensity), max((0.5 + u_lightintensity), 1.0), directional);\n\n    if (normal.y != 0.0) {\n        directional *= clamp((t + base) * pow(height / 150.0, 0.5), mix(0.7, 0.98, 1.0 - u_lightintensity), 1.0);\n    }\n\n    v_lighting.rgb += clamp(directional * u_lightcolor, mix(vec3(0.0), vec3(0.3), 1.0 - u_lightcolor), vec3(1.0));\n}\n'
                        },
                        extrusionTexture: {
                            fragmentSource: 'uniform sampler2D u_image;\nuniform float u_opacity;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_FragColor = texture2D(u_image, v_pos) * u_opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(0.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_world;\nattribute vec2 a_pos;\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos * u_world, 0, 1);\n\n    v_pos.x = a_pos.x;\n    v_pos.y = 1.0 - a_pos.y;\n}\n'
                        },
                        hillshadePrepare: {
                            fragmentSource: '#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D u_image;\nvarying vec2 v_pos;\nuniform vec2 u_dimension;\nuniform float u_zoom;\n\nfloat getElevation(vec2 coord, float bias) {\n    // Convert encoded elevation value to meters\n    vec4 data = texture2D(u_image, coord) * 255.0;\n    return (data.r + data.g * 256.0 + data.b * 256.0 * 256.0) / 4.0;\n}\n\nvoid main() {\n    vec2 epsilon = 1.0 / u_dimension;\n\n    // queried pixels:\n    // +-----------+\n    // |   |   |   |\n    // | a | b | c |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | d | e | f |\n    // |   |   |   |\n    // +-----------+\n    // |   |   |   |\n    // | g | h | i |\n    // |   |   |   |\n    // +-----------+\n\n    float a = getElevation(v_pos + vec2(-epsilon.x, -epsilon.y), 0.0);\n    float b = getElevation(v_pos + vec2(0, -epsilon.y), 0.0);\n    float c = getElevation(v_pos + vec2(epsilon.x, -epsilon.y), 0.0);\n    float d = getElevation(v_pos + vec2(-epsilon.x, 0), 0.0);\n    float e = getElevation(v_pos, 0.0);\n    float f = getElevation(v_pos + vec2(epsilon.x, 0), 0.0);\n    float g = getElevation(v_pos + vec2(-epsilon.x, epsilon.y), 0.0);\n    float h = getElevation(v_pos + vec2(0, epsilon.y), 0.0);\n    float i = getElevation(v_pos + vec2(epsilon.x, epsilon.y), 0.0);\n\n    // here we divide the x and y slopes by 8 * pixel size\n    // where pixel size (aka meters/pixel) is:\n    // circumference of the world / (pixels per tile * number of tiles)\n    // which is equivalent to: 8 * 40075016.6855785 / (512 * pow(2, u_zoom))\n    // which can be reduced to: pow(2, 19.25619978527 - u_zoom)\n    // we want to vertically exaggerate the hillshading though, because otherwise\n    // it is barely noticeable at low zooms. to do this, we multiply this by some\n    // scale factor pow(2, (u_zoom - 14) * a) where a is an arbitrary value and 14 is the\n    // maxzoom of the tile source. here we use a=0.3 which works out to the\n    // expression below. see nickidlugash\'s awesome breakdown for more info\n    // https://github.com/mapbox/mapbox-gl-js/pull/5286#discussion_r148419556\n    float exaggeration = u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;\n\n    vec2 deriv = vec2(\n        (c + f + f + i) - (a + d + d + g),\n        (g + h + h + i) - (a + b + b + c)\n    ) /  pow(2.0, (u_zoom - 14.0) * exaggeration + 19.2562 - u_zoom);\n\n    gl_FragColor = clamp(vec4(\n        deriv.x / 2.0 + 0.5,\n        deriv.y / 2.0 + 0.5,\n        1.0,\n        1.0), 0.0, 1.0);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = (a_texture_pos / 8192.0) / 2.0 + 0.25;\n}\n'
                        },
                        hillshade: {
                            fragmentSource: 'uniform sampler2D u_image;\nvarying vec2 v_pos;\n\nuniform vec2 u_latrange;\nuniform vec2 u_light;\nuniform vec4 u_shadow;\nuniform vec4 u_highlight;\nuniform vec4 u_accent;\n\n#define PI 3.141592653589793\n\nvoid main() {\n    vec4 pixel = texture2D(u_image, v_pos);\n\n    vec2 deriv = ((pixel.rg * 2.0) - 1.0);\n\n    // We divide the slope by a scale factor based on the cosin of the pixel\'s approximate latitude\n    // to account for mercator projection distortion. see #4807 for details\n    float scaleFactor = cos(radians((u_latrange[0] - u_latrange[1]) * (1.0 - v_pos.y) + u_latrange[1]));\n    // We also multiply the slope by an arbitrary z-factor of 1.25\n    float slope = atan(1.25 * length(deriv) / scaleFactor);\n    float aspect = deriv.x != 0.0 ? atan(deriv.y, -deriv.x) : PI / 2.0 * (deriv.y > 0.0 ? 1.0 : -1.0);\n\n    float intensity = u_light.x;\n    // We add PI to make this property match the global light object, which adds PI/2 to the light\'s azimuthal\n    // position property to account for 0deg corresponding to north/the top of the viewport in the style spec\n    // and the original shader was written to accept (-illuminationDirection - 90) as the azimuthal.\n    float azimuth = u_light.y + PI;\n\n    // We scale the slope exponentially based on intensity, using a calculation similar to\n    // the exponential interpolation function in the style spec:\n    // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/expression/definitions/interpolate.js#L217-L228\n    // so that higher intensity values create more opaque hillshading.\n    float base = 1.875 - intensity * 1.75;\n    float maxValue = 0.5 * PI;\n    float scaledSlope = intensity != 0.5 ? ((pow(base, slope) - 1.0) / (pow(base, maxValue) - 1.0)) * maxValue : slope;\n\n    // The accent color is calculated with the cosine of the slope while the shade color is calculated with the sine\n    // so that the accent color\'s rate of change eases in while the shade color\'s eases out.\n    float accent = cos(scaledSlope);\n    // We multiply both the accent and shade color by a clamped intensity value\n    // so that intensities >= 0.5 do not additionally affect the color values\n    // while intensity values < 0.5 make the overall color more transparent.\n    vec4 accent_color = (1.0 - accent) * u_accent * clamp(intensity * 2.0, 0.0, 1.0);\n    float shade = abs(mod((aspect + azimuth) / PI + 0.5, 2.0) - 1.0);\n    vec4 shade_color = mix(u_shadow, u_highlight, shade) * sin(scaledSlope) * clamp(intensity * 2.0, 0.0, 1.0);\n    gl_FragColor = accent_color * (1.0 - shade_color.a) + shade_color;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    v_pos = a_texture_pos / 8192.0;\n}\n'
                        },
                        line: {
                            fragmentSource: '#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_width2;\nvarying vec2 v_normal;\nvarying float v_gamma_scale;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: '\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\n// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also "special" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it\'s a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we\'re drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_width2 = vec2(outset, inset);\n}\n'
                        },
                        linePattern: {
                            fragmentSource: 'uniform vec2 u_pattern_size_a;\nuniform vec2 u_pattern_size_b;\nuniform vec2 u_pattern_tl_a;\nuniform vec2 u_pattern_br_a;\nuniform vec2 u_pattern_tl_b;\nuniform vec2 u_pattern_br_b;\nuniform vec2 u_texsize;\nuniform float u_fade;\n\nuniform sampler2D u_image;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float x_a = mod(v_linesofar / u_pattern_size_a.x, 1.0);\n    float x_b = mod(v_linesofar / u_pattern_size_b.x, 1.0);\n    float y_a = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_a.y);\n    float y_b = 0.5 + (v_normal.y * v_width2.s / u_pattern_size_b.y);\n    vec2 pos_a = mix(u_pattern_tl_a / u_texsize, u_pattern_br_a / u_texsize, vec2(x_a, y_a));\n    vec2 pos_b = mix(u_pattern_tl_b / u_texsize, u_pattern_br_b / u_texsize, vec2(x_b, y_b));\n\n    vec4 color = mix(texture2D(u_image, pos_a), texture2D(u_image, pos_b), u_fade);\n\n    gl_FragColor = color * alpha * opacity;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: '// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also "special" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying float v_linesofar;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define mediump float width\n\nvoid main() {\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize mediump float width\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it\'s a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist = outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we\'re drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_linesofar = a_linesofar;\n    v_width2 = vec2(outset, inset);\n}\n'
                        },
                        lineSDF: {
                            fragmentSource: '\nuniform sampler2D u_image;\nuniform float u_sdfgamma;\nuniform float u_mix;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    // Calculate the distance of the pixel from the line in pixels.\n    float dist = length(v_normal) * v_width2.s;\n\n    // Calculate the antialiasing fade factor. This is either when fading in\n    // the line in case of an offset line (v_width2.t) or when fading out\n    // (v_width2.s)\n    float blur2 = (blur + 1.0 / DEVICE_PIXEL_RATIO) * v_gamma_scale;\n    float alpha = clamp(min(dist - (v_width2.t - blur2), v_width2.s - dist) / blur2, 0.0, 1.0);\n\n    float sdfdist_a = texture2D(u_image, v_tex_a).a;\n    float sdfdist_b = texture2D(u_image, v_tex_b).a;\n    float sdfdist = mix(sdfdist_a, sdfdist_b, u_mix);\n    alpha *= smoothstep(0.5 - u_sdfgamma / floorwidth, 0.5 + u_sdfgamma / floorwidth, sdfdist);\n\n    gl_FragColor = color * (alpha * opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: '// floor(127 / 2) == 63.0\n// the maximum allowed miter limit is 2.0 at the moment. the extrude normal is\n// stored in a byte (-128..127). we scale regular normals up to length 63, but\n// there are also "special" normals that have a bigger length (of up to 126 in\n// this case).\n// #define scale 63.0\n#define scale 0.015873016\n\n// We scale the distance before adding it to the buffers so that we can store\n// long distances for long segments. Use this value to unscale the distance.\n#define LINE_DISTANCE_SCALE 2.0\n\n// the distance over which the line edge fades out.\n// Retina devices need a smaller distance to avoid aliasing.\n#define ANTIALIASING 1.0 / DEVICE_PIXEL_RATIO / 2.0\n\nattribute vec4 a_pos_normal;\nattribute vec4 a_data;\n\nuniform mat4 u_matrix;\nuniform mediump float u_ratio;\nuniform vec2 u_patternscale_a;\nuniform float u_tex_y_a;\nuniform vec2 u_patternscale_b;\nuniform float u_tex_y_b;\nuniform vec2 u_gl_units_to_pixels;\n\nvarying vec2 v_normal;\nvarying vec2 v_width2;\nvarying vec2 v_tex_a;\nvarying vec2 v_tex_b;\nvarying float v_gamma_scale;\n\n#pragma mapbox: define highp vec4 color\n#pragma mapbox: define lowp float blur\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define mediump float gapwidth\n#pragma mapbox: define lowp float offset\n#pragma mapbox: define mediump float width\n#pragma mapbox: define lowp float floorwidth\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 color\n    #pragma mapbox: initialize lowp float blur\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize mediump float gapwidth\n    #pragma mapbox: initialize lowp float offset\n    #pragma mapbox: initialize mediump float width\n    #pragma mapbox: initialize lowp float floorwidth\n\n    vec2 a_extrude = a_data.xy - 128.0;\n    float a_direction = mod(a_data.z, 4.0) - 1.0;\n    float a_linesofar = (floor(a_data.z / 4.0) + a_data.w * 64.0) * LINE_DISTANCE_SCALE;\n\n    vec2 pos = a_pos_normal.xy;\n\n    // x is 1 if it\'s a round cap, 0 otherwise\n    // y is 1 if the normal points up, and -1 if it points down\n    mediump vec2 normal = a_pos_normal.zw;\n    v_normal = normal;\n\n    // these transformations used to be applied in the JS and native code bases.\n    // moved them into the shader for clarity and simplicity.\n    gapwidth = gapwidth / 2.0;\n    float halfwidth = width / 2.0;\n    offset = -1.0 * offset;\n\n    float inset = gapwidth + (gapwidth > 0.0 ? ANTIALIASING : 0.0);\n    float outset = gapwidth + halfwidth * (gapwidth > 0.0 ? 2.0 : 1.0) + ANTIALIASING;\n\n    // Scale the extrusion vector down to a normal and then up by the line width\n    // of this vertex.\n    mediump vec2 dist =outset * a_extrude * scale;\n\n    // Calculate the offset when drawing a line that is to the side of the actual line.\n    // We do this by creating a vector that points towards the extrude, but rotate\n    // it when we\'re drawing round end points (a_direction = -1 or 1) since their\n    // extrude vector points in another direction.\n    mediump float u = 0.5 * a_direction;\n    mediump float t = 1.0 - abs(u);\n    mediump vec2 offset2 = offset * a_extrude * scale * normal.y * mat2(t, -u, u, t);\n\n    vec4 projected_extrude = u_matrix * vec4(dist / u_ratio, 0.0, 0.0);\n    gl_Position = u_matrix * vec4(pos + offset2 / u_ratio, 0.0, 1.0) + projected_extrude;\n\n    // calculate how much the perspective view squishes or stretches the extrude\n    float extrude_length_without_perspective = length(dist);\n    float extrude_length_with_perspective = length(projected_extrude.xy / gl_Position.w * u_gl_units_to_pixels);\n    v_gamma_scale = extrude_length_without_perspective / extrude_length_with_perspective;\n\n    v_tex_a = vec2(a_linesofar * u_patternscale_a.x / floorwidth, normal.y * u_patternscale_a.y + u_tex_y_a);\n    v_tex_b = vec2(a_linesofar * u_patternscale_b.x / floorwidth, normal.y * u_patternscale_b.y + u_tex_y_b);\n\n    v_width2 = vec2(outset, inset);\n}\n'
                        },
                        raster: {
                            fragmentSource: 'uniform float u_fade_t;\nuniform float u_opacity;\nuniform sampler2D u_image0;\nuniform sampler2D u_image1;\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nuniform float u_brightness_low;\nuniform float u_brightness_high;\n\nuniform float u_saturation_factor;\nuniform float u_contrast_factor;\nuniform vec3 u_spin_weights;\n\nvoid main() {\n\n    // read and cross-fade colors from the main and parent tiles\n    vec4 color0 = texture2D(u_image0, v_pos0);\n    vec4 color1 = texture2D(u_image1, v_pos1);\n    if (color0.a > 0.0) {\n        color0.rgb = color0.rgb / color0.a;\n    }\n    if (color1.a > 0.0) {\n        color1.rgb = color1.rgb / color1.a;\n    }\n    vec4 color = mix(color0, color1, u_fade_t);\n    color.a *= u_opacity;\n    vec3 rgb = color.rgb;\n\n    // spin\n    rgb = vec3(\n        dot(rgb, u_spin_weights.xyz),\n        dot(rgb, u_spin_weights.zxy),\n        dot(rgb, u_spin_weights.yzx));\n\n    // saturation\n    float average = (color.r + color.g + color.b) / 3.0;\n    rgb += (average - rgb) * u_saturation_factor;\n\n    // contrast\n    rgb = (rgb - 0.5) * u_contrast_factor + 0.5;\n\n    // brightness\n    vec3 u_high_vec = vec3(u_brightness_low, u_brightness_low, u_brightness_low);\n    vec3 u_low_vec = vec3(u_brightness_high, u_brightness_high, u_brightness_high);\n\n    gl_FragColor = vec4(mix(u_high_vec, u_low_vec, rgb) * color.a, color.a);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'uniform mat4 u_matrix;\nuniform vec2 u_tl_parent;\nuniform float u_scale_parent;\nuniform float u_buffer_scale;\n\nattribute vec2 a_pos;\nattribute vec2 a_texture_pos;\n\nvarying vec2 v_pos0;\nvarying vec2 v_pos1;\n\nvoid main() {\n    gl_Position = u_matrix * vec4(a_pos, 0, 1);\n    // We are using Int16 for texture position coordinates to give us enough precision for\n    // fractional coordinates. We use 8192 to scale the texture coordinates in the buffer\n    // as an arbitrarily high number to preserve adequate precision when rendering.\n    // This is also the same value as the EXTENT we are using for our tile buffer pos coordinates,\n    // so math for modifying either is consistent.\n    v_pos0 = (((a_texture_pos / 8192.0) - 0.5) / u_buffer_scale ) + 0.5;\n    v_pos1 = (v_pos0 * u_scale_parent) + u_tl_parent;\n}\n'
                        },
                        symbolIcon: {
                            fragmentSource: 'uniform sampler2D u_texture;\n\n#pragma mapbox: define lowp float opacity\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    lowp float alpha = opacity * v_fade_opacity;\n    gl_FragColor = texture2D(u_texture, v_tex) * alpha;\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\nuniform highp float u_camera_to_center_distance;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform float u_fade_change;\n\n#pragma mapbox: define lowp float opacity\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_tex;\nvarying float v_fade_opacity;\n\nvoid main() {\n    #pragma mapbox: initialize lowp float opacity\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n\n    float size;\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // See comments in symbol_sdf.vertex\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // See comments in symbol_sdf.vertex\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n\n    v_tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    v_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n}\n'
                        },
                        symbolSDF: {
                            fragmentSource: '#define SDF_PX 8.0\n#define EDGE_GAMMA 0.105/DEVICE_PIXEL_RATIO\n\nuniform bool u_is_halo;\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform sampler2D u_texture;\nuniform highp float u_gamma_scale;\nuniform bool u_is_text;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 tex = v_data0.xy;\n    float gamma_scale = v_data1.x;\n    float size = v_data1.y;\n    float fade_opacity = v_data1[2];\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    lowp vec4 color = fill_color;\n    highp float gamma = EDGE_GAMMA / (fontScale * u_gamma_scale);\n    lowp float buff = (256.0 - 64.0) / 256.0;\n    if (u_is_halo) {\n        color = halo_color;\n        gamma = (halo_blur * 1.19 / SDF_PX + EDGE_GAMMA) / (fontScale * u_gamma_scale);\n        buff = (6.0 - halo_width / fontScale) / SDF_PX;\n    }\n\n    lowp float dist = texture2D(u_texture, tex).a;\n    highp float gamma_scaled = gamma * gamma_scale;\n    highp float alpha = smoothstep(buff - gamma_scaled, buff + gamma_scaled, dist);\n\n    gl_FragColor = color * (alpha * opacity * fade_opacity);\n\n#ifdef OVERDRAW_INSPECTOR\n    gl_FragColor = vec4(1.0);\n#endif\n}\n',
                            vertexSource: 'const float PI = 3.141592653589793;\n\nattribute vec4 a_pos_offset;\nattribute vec4 a_data;\nattribute vec3 a_projected_pos;\nattribute float a_fade_opacity;\n\n// contents of a_size vary based on the type of property value\n// used for {text,icon}-size.\n// For constants, a_size is disabled.\n// For source functions, we bind only one value per vertex: the value of {text,icon}-size evaluated for the current feature.\n// For composite functions:\n// [ text-size(lowerZoomStop, feature),\n//   text-size(upperZoomStop, feature) ]\nuniform bool u_is_size_zoom_constant;\nuniform bool u_is_size_feature_constant;\nuniform highp float u_size_t; // used to interpolate between zoom stops when size is a composite function\nuniform highp float u_size; // used when size is both zoom and feature constant\n\n#pragma mapbox: define highp vec4 fill_color\n#pragma mapbox: define highp vec4 halo_color\n#pragma mapbox: define lowp float opacity\n#pragma mapbox: define lowp float halo_width\n#pragma mapbox: define lowp float halo_blur\n\nuniform mat4 u_matrix;\nuniform mat4 u_label_plane_matrix;\nuniform mat4 u_gl_coord_matrix;\n\nuniform bool u_is_text;\nuniform bool u_pitch_with_map;\nuniform highp float u_pitch;\nuniform bool u_rotate_symbol;\nuniform highp float u_aspect_ratio;\nuniform highp float u_camera_to_center_distance;\nuniform float u_fade_change;\n\nuniform vec2 u_texsize;\n\nvarying vec2 v_data0;\nvarying vec3 v_data1;\n\nvoid main() {\n    #pragma mapbox: initialize highp vec4 fill_color\n    #pragma mapbox: initialize highp vec4 halo_color\n    #pragma mapbox: initialize lowp float opacity\n    #pragma mapbox: initialize lowp float halo_width\n    #pragma mapbox: initialize lowp float halo_blur\n\n    vec2 a_pos = a_pos_offset.xy;\n    vec2 a_offset = a_pos_offset.zw;\n\n    vec2 a_tex = a_data.xy;\n    vec2 a_size = a_data.zw;\n\n    highp float segment_angle = -a_projected_pos[2];\n    float size;\n\n    if (!u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = mix(a_size[0], a_size[1], u_size_t) / 10.0;\n    } else if (u_is_size_zoom_constant && !u_is_size_feature_constant) {\n        size = a_size[0] / 10.0;\n    } else if (!u_is_size_zoom_constant && u_is_size_feature_constant) {\n        size = u_size;\n    } else {\n        size = u_size;\n    }\n\n    vec4 projectedPoint = u_matrix * vec4(a_pos, 0, 1);\n    highp float camera_to_anchor_distance = projectedPoint.w;\n    // If the label is pitched with the map, layout is done in pitched space,\n    // which makes labels in the distance smaller relative to viewport space.\n    // We counteract part of that effect by multiplying by the perspective ratio.\n    // If the label isn\'t pitched with the map, we do layout in viewport space,\n    // which makes labels in the distance larger relative to the features around\n    // them. We counteract part of that effect by dividing by the perspective ratio.\n    highp float distance_ratio = u_pitch_with_map ?\n        camera_to_anchor_distance / u_camera_to_center_distance :\n        u_camera_to_center_distance / camera_to_anchor_distance;\n    highp float perspective_ratio = 0.5 + 0.5 * distance_ratio;\n\n    size *= perspective_ratio;\n\n    float fontScale = u_is_text ? size / 24.0 : size;\n\n    highp float symbol_rotation = 0.0;\n    if (u_rotate_symbol) {\n        // Point labels with \'rotation-alignment: map\' are horizontal with respect to tile units\n        // To figure out that angle in projected space, we draw a short horizontal line in tile\n        // space, project it, and measure its angle in projected space.\n        vec4 offsetProjectedPoint = u_matrix * vec4(a_pos + vec2(1, 0), 0, 1);\n\n        vec2 a = projectedPoint.xy / projectedPoint.w;\n        vec2 b = offsetProjectedPoint.xy / offsetProjectedPoint.w;\n\n        symbol_rotation = atan((b.y - a.y) / u_aspect_ratio, b.x - a.x);\n    }\n\n    highp float angle_sin = sin(segment_angle + symbol_rotation);\n    highp float angle_cos = cos(segment_angle + symbol_rotation);\n    mat2 rotation_matrix = mat2(angle_cos, -1.0 * angle_sin, angle_sin, angle_cos);\n\n    vec4 projected_pos = u_label_plane_matrix * vec4(a_projected_pos.xy, 0.0, 1.0);\n    gl_Position = u_gl_coord_matrix * vec4(projected_pos.xy / projected_pos.w + rotation_matrix * (a_offset / 64.0 * fontScale), 0.0, 1.0);\n    float gamma_scale = gl_Position.w;\n\n    vec2 tex = a_tex / u_texsize;\n    vec2 fade_opacity = unpack_opacity(a_fade_opacity);\n    float fade_change = fade_opacity[1] > 0.5 ? u_fade_change : -u_fade_change;\n    float interpolated_fade_opacity = max(0.0, min(1.0, fade_opacity[0] + fade_change));\n\n    v_data0 = vec2(tex.x, tex.y);\n    v_data1 = vec3(gamma_scale, size, interpolated_fade_opacity);\n}\n'
                        }
                    }, re = /#pragma mapbox: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g, loop = function (e) {
                        var n = shaders[e], a = {};
                        n.fragmentSource = n.fragmentSource.replace(re, function (e, n, t, o, i) {
                            return a[i] = !0, 'define' === n ? '\n#ifndef HAS_UNIFORM_u_' + i + '\nvarying ' + t + ' ' + o + ' ' + i + ';\n#else\nuniform ' + t + ' ' + o + ' u_' + i + ';\n#endif\n' : '\n#ifdef HAS_UNIFORM_u_' + i + '\n    ' + t + ' ' + o + ' ' + i + ' = u_' + i + ';\n#endif\n';
                        }), n.vertexSource = n.vertexSource.replace(re, function (e, n, t, o, i) {
                            var r = 'float' === o ? 'vec2' : 'vec4';
                            return a[i] ? 'define' === n ? '\n#ifndef HAS_UNIFORM_u_' + i + '\nuniform lowp float a_' + i + '_t;\nattribute ' + t + ' ' + r + ' a_' + i + ';\nvarying ' + t + ' ' + o + ' ' + i + ';\n#else\nuniform ' + t + ' ' + o + ' u_' + i + ';\n#endif\n' : '\n#ifndef HAS_UNIFORM_u_' + i + '\n    ' + i + ' = unpack_mix_' + r + '(a_' + i + ', a_' + i + '_t);\n#else\n    ' + t + ' ' + o + ' ' + i + ' = u_' + i + ';\n#endif\n' : 'define' === n ? '\n#ifndef HAS_UNIFORM_u_' + i + '\nuniform lowp float a_' + i + '_t;\nattribute ' + t + ' ' + r + ' a_' + i + ';\n#else\nuniform ' + t + ' ' + o + ' u_' + i + ';\n#endif\n' : '\n#ifndef HAS_UNIFORM_u_' + i + '\n    ' + t + ' ' + o + ' ' + i + ' = unpack_mix_' + r + '(a_' + i + ', a_' + i + '_t);\n#else\n    ' + t + ' ' + o + ' ' + i + ' = u_' + i + ';\n#endif\n';
                        });
                    };
                for (var programName in shaders) {
                    loop(programName);
                }
                module.exports = shaders;
            },
            {}
        ],
        98: [
            function (_dereq_, module, exports) {
                'use strict';
                var ImageSource = _dereq_('./image_source'), window = _dereq_('../util/window'), rasterBoundsAttributes = _dereq_('../data/raster_bounds_attributes'), VertexArrayObject = _dereq_('../render/vertex_array_object'), Texture = _dereq_('../render/texture'), CanvasSource = function (t) {
                        function e(e, i, s, a) {
                            t.call(this, e, i, s, a), this.options = i, this.animate = void 0 === i.animate || i.animate;
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.load = function () {
                            if (this.canvas = this.canvas || window.document.getElementById(this.options.canvas), this.width = this.canvas.width, this.height = this.canvas.height, this._hasInvalidDimensions()) {
                                return void this.fire('error', new Error('Canvas dimensions cannot be less than or equal to zero.'));
                            }
                            this.play = function () {
                                this._playing = !0, this.map._rerender();
                            }, this.pause = function () {
                                this._playing = !1;
                            }, this._finishLoading();
                        }, e.prototype.getCanvas = function () {
                            return this.canvas;
                        }, e.prototype.onAdd = function (t) {
                            this.map = t, this.load(), this.canvas && this.animate && this.play();
                        }, e.prototype.onRemove = function () {
                            this.pause();
                        }, e.prototype.prepare = function () {
                            var t = this, e = !1;
                            if (this.canvas.width !== this.width && (this.width = this.canvas.width, e = !0), this.canvas.height !== this.height && (this.height = this.canvas.height, e = !0), !this._hasInvalidDimensions() && 0 !== Object.keys(this.tiles).length) {
                                var i = this.map.painter.context, s = i.gl;
                                this.boundsBuffer || (this.boundsBuffer = i.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members)), this.boundsVAO || (this.boundsVAO = new VertexArrayObject()), this.texture ? e ? this.texture.update(this.canvas) : this._playing && (this.texture.bind(s.LINEAR, s.CLAMP_TO_EDGE), s.texSubImage2D(s.TEXTURE_2D, 0, 0, 0, s.RGBA, s.UNSIGNED_BYTE, this.canvas)) : (this.texture = new Texture(i, this.canvas, s.RGBA), this.texture.bind(s.LINEAR, s.CLAMP_TO_EDGE));
                                for (var a in t.tiles) {
                                    var r = t.tiles[a];
                                    'loaded' !== r.state && (r.state = 'loaded', r.texture = t.texture);
                                }
                            }
                        }, e.prototype.serialize = function () {
                            return {
                                type: 'canvas',
                                canvas: this.canvas,
                                coordinates: this.coordinates
                            };
                        }, e.prototype.hasTransition = function () {
                            return this._playing;
                        }, e.prototype._hasInvalidDimensions = function () {
                            for (var t = this, e = 0, i = [
                                        t.canvas.width,
                                        t.canvas.height
                                    ]; e < i.length; e += 1) {
                                var s = i[e];
                                if (isNaN(s) || s <= 0) {
                                    return !0;
                                }
                            }
                            return !1;
                        }, e;
                    }(ImageSource);
                module.exports = CanvasSource;
            },
            {
                '../data/raster_bounds_attributes': 59,
                '../render/texture': 93,
                '../render/vertex_array_object': 95,
                '../util/window': 254,
                './image_source': 102
            }
        ],
        99: [
            function (_dereq_, module, exports) {
                'use strict';
                function resolveURL(e) {
                    var t = window.document.createElement('a');
                    return t.href = e, t.href;
                }
                var Evented = _dereq_('../util/evented'), util = _dereq_('../util/util'), window = _dereq_('../util/window'), EXTENT = _dereq_('../data/extent'), ResourceType = _dereq_('../util/ajax').ResourceType, browser = _dereq_('../util/browser'), GeoJSONSource = function (e) {
                        function t(t, i, o, r) {
                            e.call(this), this.id = t, this.type = 'geojson', this.minzoom = 0, this.maxzoom = 18, this.tileSize = 512, this.isTileClipped = !0, this.reparseOverscaled = !0, this.dispatcher = o, this.setEventedParent(r), this._data = i.data, this._options = util.extend({}, i), this._collectResourceTiming = i.collectResourceTiming, this._resourceTiming = [], void 0 !== i.maxzoom && (this.maxzoom = i.maxzoom), i.type && (this.type = i.type);
                            var s = EXTENT / this.tileSize;
                            this.workerOptions = util.extend({
                                source: this.id,
                                cluster: i.cluster || !1,
                                geojsonVtOptions: {
                                    buffer: (void 0 !== i.buffer ? i.buffer : 128) * s,
                                    tolerance: (void 0 !== i.tolerance ? i.tolerance : 0.375) * s,
                                    extent: EXTENT,
                                    maxZoom: this.maxzoom
                                },
                                superclusterOptions: {
                                    maxZoom: void 0 !== i.clusterMaxZoom ? Math.min(i.clusterMaxZoom, this.maxzoom - 1) : this.maxzoom - 1,
                                    extent: EXTENT,
                                    radius: (i.clusterRadius || 50) * s,
                                    log: !1
                                }
                            }, i.workerOptions);
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t.prototype.load = function () {
                            var e = this;
                            this.fire('dataloading', { dataType: 'source' }), this._updateWorkerData(function (t) {
                                if (t) {
                                    return void e.fire('error', { error: t });
                                }
                                var i = {
                                    dataType: 'source',
                                    sourceDataType: 'metadata'
                                };
                                e._collectResourceTiming && e._resourceTiming && e._resourceTiming.length > 0 && (i.resourceTiming = e._resourceTiming, e._resourceTiming = []), e.fire('data', i);
                            });
                        }, t.prototype.onAdd = function (e) {
                            this.map = e, this.load();
                        }, t.prototype.setData = function (e) {
                            var t = this;
                            return this._data = e, this.fire('dataloading', { dataType: 'source' }), this._updateWorkerData(function (e) {
                                if (e) {
                                    return t.fire('error', { error: e });
                                }
                                var i = {
                                    dataType: 'source',
                                    sourceDataType: 'content'
                                };
                                t._collectResourceTiming && t._resourceTiming && t._resourceTiming.length > 0 && (i.resourceTiming = t._resourceTiming, t._resourceTiming = []), t.fire('data', i);
                            }), this;
                        }, t.prototype._updateWorkerData = function (e) {
                            var t = this, i = util.extend({}, this.workerOptions), o = this._data;
                            'string' == typeof o ? (i.request = this.map._transformRequest(resolveURL(o), ResourceType.Source), i.request.collectResourceTiming = this._collectResourceTiming) : i.data = JSON.stringify(o), this.workerID = this.dispatcher.send(this.type + '.loadData', i, function (i, o) {
                                t._loaded = !0, o && o.resourceTiming && o.resourceTiming[t.id] && (t._resourceTiming = o.resourceTiming[t.id].slice(0)), e(i);
                            }, this.workerID);
                        }, t.prototype.loadTile = function (e, t) {
                            var i = this, o = void 0 === e.workerID || 'expired' === e.state ? 'loadTile' : 'reloadTile', r = {
                                    type: this.type,
                                    uid: e.uid,
                                    tileID: e.tileID,
                                    zoom: e.tileID.overscaledZ,
                                    maxZoom: this.maxzoom,
                                    tileSize: this.tileSize,
                                    source: this.id,
                                    pixelRatio: browser.devicePixelRatio,
                                    overscaling: e.tileID.overscaleFactor(),
                                    showCollisionBoxes: this.map.showCollisionBoxes
                                };
                            e.workerID = this.dispatcher.send(o, r, function (r, s) {
                                return e.unloadVectorData(), e.aborted ? t(null) : r ? t(r) : (e.loadVectorData(s, i.map.painter, 'reloadTile' === o), t(null));
                            }, this.workerID);
                        }, t.prototype.abortTile = function (e) {
                            e.aborted = !0;
                        }, t.prototype.unloadTile = function (e) {
                            e.unloadVectorData(), this.dispatcher.send('removeTile', {
                                uid: e.uid,
                                type: this.type,
                                source: this.id
                            }, null, e.workerID);
                        }, t.prototype.onRemove = function () {
                            this.dispatcher.broadcast('removeSource', {
                                type: this.type,
                                source: this.id
                            });
                        }, t.prototype.serialize = function () {
                            return util.extend({}, this._options, {
                                type: this.type,
                                data: this._data
                            });
                        }, t.prototype.hasTransition = function () {
                            return !1;
                        }, t;
                    }(Evented);
                module.exports = GeoJSONSource;
            },
            {
                '../data/extent': 53,
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/evented': 260,
                '../util/util': 275,
                '../util/window': 254
            }
        ],
        100: [
            function (_dereq_, module, exports) {
                'use strict';
                function loadGeoJSONTile(e, r) {
                    var t = e.source, o = e.tileID.canonical;
                    if (!this._geoJSONIndexes[t]) {
                        return r(null, null);
                    }
                    var u = this._geoJSONIndexes[t].getTile(o.z, o.x, o.y);
                    if (!u) {
                        return r(null, null);
                    }
                    var n = new GeoJSONWrapper(u.features), i = vtpbf(n);
                    0 === i.byteOffset && i.byteLength === i.buffer.byteLength || (i = new Uint8Array(i)), r(null, {
                        vectorTile: n,
                        rawData: i.buffer
                    });
                }
                var ajax = _dereq_('../util/ajax'), perf = _dereq_('../util/performance'), rewind = _dereq_('geojson-rewind'), GeoJSONWrapper = _dereq_('./geojson_wrapper'), vtpbf = _dereq_('vt-pbf'), supercluster = _dereq_('supercluster'), geojsonvt = _dereq_('geojson-vt'), VectorTileWorkerSource = _dereq_('./vector_tile_worker_source'), GeoJSONWorkerSource = function (e) {
                        function r(r, t, o) {
                            e.call(this, r, t, loadGeoJSONTile), o && (this.loadGeoJSON = o), this._geoJSONIndexes = {};
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r.prototype.loadData = function (e, r) {
                            var t = this;
                            this.loadGeoJSON(e, function (o, u) {
                                if (o || !u) {
                                    return r(o);
                                }
                                if ('object' != typeof u) {
                                    return r(new Error('Input data is not a valid GeoJSON object.'));
                                }
                                rewind(u, !0);
                                try {
                                    t._geoJSONIndexes[e.source] = e.cluster ? supercluster(e.superclusterOptions).load(u.features) : geojsonvt(u, e.geojsonVtOptions);
                                } catch (o) {
                                    return r(o);
                                }
                                t.loaded[e.source] = {};
                                var n = {};
                                if (e.request && e.request.collectResourceTiming) {
                                    var i = perf.getEntriesByName(e.request.url);
                                    i && (n.resourceTiming = {}, n.resourceTiming[e.source] = JSON.parse(JSON.stringify(i)));
                                }
                                r(null, n);
                            });
                        }, r.prototype.reloadTile = function (r, t) {
                            var o = this.loaded[r.source], u = r.uid;
                            return o && o[u] ? e.prototype.reloadTile.call(this, r, t) : this.loadTile(r, t);
                        }, r.prototype.loadGeoJSON = function (e, r) {
                            if (e.request) {
                                ajax.getJSON(e.request, r);
                            } else {
                                if ('string' != typeof e.data) {
                                    return r(new Error('Input data is not a valid GeoJSON object.'));
                                }
                                try {
                                    return r(null, JSON.parse(e.data));
                                } catch (e) {
                                    return r(new Error('Input data is not a valid GeoJSON object.'));
                                }
                            }
                        }, r.prototype.removeSource = function (e, r) {
                            this._geoJSONIndexes[e.source] && delete this._geoJSONIndexes[e.source], r();
                        }, r;
                    }(VectorTileWorkerSource);
                module.exports = GeoJSONWorkerSource;
            },
            {
                '../util/ajax': 251,
                '../util/performance': 268,
                './geojson_wrapper': 101,
                './vector_tile_worker_source': 116,
                'geojson-rewind': 15,
                'geojson-vt': 19,
                'supercluster': 32,
                'vt-pbf': 34
            }
        ],
        101: [
            function (_dereq_, module, exports) {
                'use strict';
                var Point = _dereq_('@mapbox/point-geometry'), toGeoJSON = _dereq_('@mapbox/vector-tile').VectorTileFeature.prototype.toGeoJSON, EXTENT = _dereq_('../data/extent'), FeatureWrapper = function (e) {
                        this._feature = e, this.extent = EXTENT, this.type = e.type, this.properties = e.tags, 'id' in e && !isNaN(e.id) && (this.id = parseInt(e.id, 10));
                    };
                FeatureWrapper.prototype.loadGeometry = function () {
                    var e = this;
                    if (1 === this._feature.type) {
                        for (var t = [], r = 0, o = e._feature.geometry; r < o.length; r += 1) {
                            var a = o[r];
                            t.push([new Point(a[0], a[1])]);
                        }
                        return t;
                    }
                    for (var i = [], p = 0, n = e._feature.geometry; p < n.length; p += 1) {
                        for (var s = n[p], u = [], h = 0, f = s; h < f.length; h += 1) {
                            var l = f[h];
                            u.push(new Point(l[0], l[1]));
                        }
                        i.push(u);
                    }
                    return i;
                }, FeatureWrapper.prototype.toGeoJSON = function (e, t, r) {
                    return toGeoJSON.call(this, e, t, r);
                };
                var GeoJSONWrapper = function (e) {
                    this.layers = { _geojsonTileLayer: this }, this.name = '_geojsonTileLayer', this.extent = EXTENT, this.length = e.length, this._features = e;
                };
                GeoJSONWrapper.prototype.feature = function (e) {
                    return new FeatureWrapper(this._features[e]);
                }, module.exports = GeoJSONWrapper;
            },
            {
                '../data/extent': 53,
                '@mapbox/point-geometry': 4,
                '@mapbox/vector-tile': 8
            }
        ],
        102: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), ref = _dereq_('./tile_id'), CanonicalTileID = ref.CanonicalTileID, LngLat = _dereq_('../geo/lng_lat'), Point = _dereq_('@mapbox/point-geometry'), Evented = _dereq_('../util/evented'), ajax = _dereq_('../util/ajax'), browser = _dereq_('../util/browser'), EXTENT = _dereq_('../data/extent'), ref$1 = _dereq_('../data/array_types'), RasterBoundsArray = ref$1.RasterBoundsArray, rasterBoundsAttributes = _dereq_('../data/raster_bounds_attributes'), VertexArrayObject = _dereq_('../render/vertex_array_object'), Texture = _dereq_('../render/texture'), ImageSource = function (t) {
                        function e(e, r, o, i) {
                            t.call(this), this.id = e, this.dispatcher = o, this.coordinates = r.coordinates, this.type = 'image', this.minzoom = 0, this.maxzoom = 22, this.tileSize = 512, this.tiles = {}, this.setEventedParent(i), this.options = r;
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.load = function () {
                            var t = this;
                            this.fire('dataloading', { dataType: 'source' }), this.url = this.options.url, ajax.getImage(this.map._transformRequest(this.url, ajax.ResourceType.Image), function (e, r) {
                                e ? t.fire('error', { error: e }) : r && (t.image = browser.getImageData(r), t._finishLoading());
                            });
                        }, e.prototype._finishLoading = function () {
                            this.map && (this.setCoordinates(this.coordinates), this.fire('data', {
                                dataType: 'source',
                                sourceDataType: 'metadata'
                            }));
                        }, e.prototype.onAdd = function (t) {
                            this.map = t, this.load();
                        }, e.prototype.setCoordinates = function (t) {
                            this.coordinates = t;
                            var e = this.map, r = t.map(function (t) {
                                    return e.transform.locationCoordinate(LngLat.convert(t)).zoomTo(0);
                                }), o = this.centerCoord = util.getCoordinatesCenter(r);
                            o.column = Math.floor(o.column), o.row = Math.floor(o.row), this.tileID = new CanonicalTileID(o.zoom, o.column, o.row), this.minzoom = this.maxzoom = o.zoom;
                            var i = r.map(function (t) {
                                var e = t.zoomTo(o.zoom);
                                return new Point(Math.round((e.column - o.column) * EXTENT), Math.round((e.row - o.row) * EXTENT));
                            });
                            return this._boundsArray = new RasterBoundsArray(), this._boundsArray.emplaceBack(i[0].x, i[0].y, 0, 0), this._boundsArray.emplaceBack(i[1].x, i[1].y, EXTENT, 0), this._boundsArray.emplaceBack(i[3].x, i[3].y, 0, EXTENT), this._boundsArray.emplaceBack(i[2].x, i[2].y, EXTENT, EXTENT), this.boundsBuffer && (this.boundsBuffer.destroy(), delete this.boundsBuffer), this.fire('data', {
                                dataType: 'source',
                                sourceDataType: 'content'
                            }), this;
                        }, e.prototype.prepare = function () {
                            var t = this;
                            if (0 !== Object.keys(this.tiles).length && this.image) {
                                var e = this.map.painter.context, r = e.gl;
                                this.boundsBuffer || (this.boundsBuffer = e.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members)), this.boundsVAO || (this.boundsVAO = new VertexArrayObject()), this.texture || (this.texture = new Texture(e, this.image, r.RGBA), this.texture.bind(r.LINEAR, r.CLAMP_TO_EDGE));
                                for (var o in t.tiles) {
                                    var i = t.tiles[o];
                                    'loaded' !== i.state && (i.state = 'loaded', i.texture = t.texture);
                                }
                            }
                        }, e.prototype.loadTile = function (t, e) {
                            this.tileID && this.tileID.equals(t.tileID.canonical) ? (this.tiles[String(t.tileID.wrap)] = t, t.buckets = {}, e(null)) : (t.state = 'errored', e(null));
                        }, e.prototype.serialize = function () {
                            return {
                                type: 'image',
                                url: this.options.url,
                                coordinates: this.coordinates
                            };
                        }, e.prototype.hasTransition = function () {
                            return !1;
                        }, e;
                    }(Evented);
                module.exports = ImageSource;
            },
            {
                '../data/array_types': 39,
                '../data/extent': 53,
                '../data/raster_bounds_attributes': 59,
                '../geo/lng_lat': 62,
                '../render/texture': 93,
                '../render/vertex_array_object': 95,
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/evented': 260,
                '../util/util': 275,
                './tile_id': 114,
                '@mapbox/point-geometry': 4
            }
        ],
        103: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), ajax = _dereq_('../util/ajax'), browser = _dereq_('../util/browser'), normalizeURL = _dereq_('../util/mapbox').normalizeSourceURL;
                module.exports = function (r, e, o) {
                    var u = function (r, e) {
                        if (r) {
                            return o(r);
                        }
                        if (e) {
                            var u = util.pick(e, [
                                'tiles',
                                'minzoom',
                                'maxzoom',
                                'attribution',
                                'mapbox_logo',
                                'bounds'
                            ]);
                            e.vector_layers && (u.vectorLayers = e.vector_layers, u.vectorLayerIds = u.vectorLayers.map(function (r) {
                                return r.id;
                            })), o(null, u);
                        }
                    };
                    r.url ? ajax.getJSON(e(normalizeURL(r.url), ajax.ResourceType.Source), u) : browser.frame(function () {
                        return u(null, r);
                    });
                };
            },
            {
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/mapbox': 267,
                '../util/util': 275
            }
        ],
        104: [
            function (_dereq_, module, exports) {
                'use strict';
                var EXTENT = _dereq_('../data/extent');
                module.exports = function (e, t, r) {
                    return t * (EXTENT / (e.tileSize * Math.pow(2, r - e.tileID.overscaledZ)));
                };
            },
            { '../data/extent': 53 }
        ],
        105: [
            function (_dereq_, module, exports) {
                'use strict';
                function sortTilesIn(e, r) {
                    var a = e.tileID, n = r.tileID;
                    return a.overscaledZ - n.overscaledZ || a.canonical.y - n.canonical.y || a.wrap - n.wrap || a.canonical.x - n.canonical.x;
                }
                function mergeRenderedFeatureLayers(e) {
                    for (var r = {}, a = {}, n = 0, t = e; n < t.length; n += 1) {
                        var u = t[n], l = u.queryResults, o = u.wrappedTileID, s = a[o] = a[o] || {};
                        for (var i in l) {
                            for (var c = l[i], d = s[i] = s[i] || {}, f = r[i] = r[i] || [], p = 0, v = c; p < v.length; p += 1) {
                                var y = v[p];
                                d[y.featureIndex] || (d[y.featureIndex] = !0, f.push(y.feature));
                            }
                        }
                    }
                    return r;
                }
                exports.rendered = function (e, r, a, n, t, u, l) {
                    var o = e.tilesIn(a);
                    o.sort(sortTilesIn);
                    for (var s = [], i = 0, c = o; i < c.length; i += 1) {
                        var d = c[i];
                        s.push({
                            wrappedTileID: d.tileID.wrapped().key,
                            queryResults: d.tile.queryRenderedFeatures(r, d.queryGeometry, d.scale, n, u, e.id, l)
                        });
                    }
                    return mergeRenderedFeatureLayers(s);
                }, exports.source = function (e, r) {
                    for (var a = e.getRenderableIds().map(function (r) {
                                return e.getTileByID(r);
                            }), n = [], t = {}, u = 0; u < a.length; u++) {
                        var l = a[u], o = l.tileID.canonical.key;
                        t[o] || (t[o] = !0, l.querySourceFeatures(n, r));
                    }
                    return n;
                };
            },
            {}
        ],
        106: [
            function (_dereq_, module, exports) {
                'use strict';
                var ajax = _dereq_('../util/ajax'), util = _dereq_('../util/util'), Evented = _dereq_('../util/evented'), normalizeURL = _dereq_('../util/mapbox').normalizeTileURL, browser = _dereq_('../util/browser'), ref = _dereq_('./tile_id'), OverscaledTileID = ref.OverscaledTileID, RasterTileSource = _dereq_('./raster_tile_source'), RasterDEMTileSource = function (e) {
                        function r(r, i, t, l) {
                            e.call(this, r, i, t, l), this.type = 'raster-dem', this.maxzoom = 22, this._options = util.extend({}, i);
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r.prototype.serialize = function () {
                            return {
                                type: 'raster-dem',
                                url: this.url,
                                tileSize: this.tileSize,
                                tiles: this.tiles,
                                bounds: this.bounds
                            };
                        }, r.prototype.loadTile = function (e, r) {
                            function i(i, l) {
                                if (delete e.request, e.aborted) {
                                    e.state = 'unloaded', r(null);
                                } else if (i) {
                                    e.state = 'errored', r(i);
                                } else if (l) {
                                    this.map._refreshExpiredTiles && e.setExpiryData(l), delete l.cacheControl, delete l.expires;
                                    var a = browser.getImageData(l), s = {
                                            uid: e.uid,
                                            coord: e.tileID,
                                            source: this.id,
                                            rawImageData: a
                                        };
                                    e.workerID && 'expired' !== e.state || (e.workerID = this.dispatcher.send('loadDEMTile', s, t.bind(this)));
                                }
                            }
                            function t(i, t) {
                                i && (e.state = 'errored', r(i)), t && (e.dem = t, e.needsHillshadePrepare = !0, e.state = 'loaded', r(null));
                            }
                            var l = normalizeURL(e.tileID.canonical.url(this.tiles, this.scheme), this.url, this.tileSize);
                            e.request = ajax.getImage(this.map._transformRequest(l, ajax.ResourceType.Tile), i.bind(this)), e.neighboringTiles = this._getNeighboringTiles(e.tileID);
                        }, r.prototype._getNeighboringTiles = function (e) {
                            var r = e.canonical, i = Math.pow(2, r.z), t = (r.x - 1 + i) % i, l = 0 === r.x ? e.wrap - 1 : e.wrap, a = (r.x + 1 + i) % i, s = r.x + 1 === i ? e.wrap + 1 : e.wrap, o = {};
                            return o[new OverscaledTileID(e.overscaledZ, l, r.z, t, r.y).key] = { backfilled: !1 }, o[new OverscaledTileID(e.overscaledZ, s, r.z, a, r.y).key] = { backfilled: !1 }, r.y > 0 && (o[new OverscaledTileID(e.overscaledZ, l, r.z, t, r.y - 1).key] = { backfilled: !1 }, o[new OverscaledTileID(e.overscaledZ, e.wrap, r.z, r.x, r.y - 1).key] = { backfilled: !1 }, o[new OverscaledTileID(e.overscaledZ, s, r.z, a, r.y - 1).key] = { backfilled: !1 }), r.y + 1 < i && (o[new OverscaledTileID(e.overscaledZ, l, r.z, t, r.y + 1).key] = { backfilled: !1 }, o[new OverscaledTileID(e.overscaledZ, e.wrap, r.z, r.x, r.y + 1).key] = { backfilled: !1 }, o[new OverscaledTileID(e.overscaledZ, s, r.z, a, r.y + 1).key] = { backfilled: !1 }), o;
                        }, r.prototype.unloadTile = function (e) {
                            e.demTexture && this.map.painter.saveTileTexture(e.demTexture), e.fbo && (e.fbo.destroy(), delete e.fbo), e.dem && delete e.dem, delete e.neighboringTiles, e.state = 'unloaded', this.dispatcher.send('removeDEMTile', {
                                uid: e.uid,
                                source: this.id
                            }, void 0, e.workerID);
                        }, r;
                    }(RasterTileSource);
                module.exports = RasterDEMTileSource;
            },
            {
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/evented': 260,
                '../util/mapbox': 267,
                '../util/util': 275,
                './raster_tile_source': 108,
                './tile_id': 114
            }
        ],
        107: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../data/dem_data'), DEMData = ref.DEMData, RasterDEMTileWorkerSource = function () {
                        this.loading = {}, this.loaded = {};
                    };
                RasterDEMTileWorkerSource.prototype.loadTile = function (e, a) {
                    var o = e.source, r = e.uid;
                    this.loading[o] || (this.loading[o] = {});
                    var t = new DEMData(r);
                    this.loading[o][r] = t, t.loadFromImage(e.rawImageData), delete this.loading[o][r], this.loaded[o] = this.loaded[o] || {}, this.loaded[o][r] = t, a(null, t);
                }, RasterDEMTileWorkerSource.prototype.removeTile = function (e) {
                    var a = this.loaded[e.source], o = e.uid;
                    a && a[o] && delete a[o];
                }, module.exports = RasterDEMTileWorkerSource;
            },
            { '../data/dem_data': 52 }
        ],
        108: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), ajax = _dereq_('../util/ajax'), Evented = _dereq_('../util/evented'), loadTileJSON = _dereq_('./load_tilejson'), normalizeURL = _dereq_('../util/mapbox').normalizeTileURL, TileBounds = _dereq_('./tile_bounds'), Texture = _dereq_('../render/texture'), RasterTileSource = function (e) {
                        function t(t, i, r, o) {
                            e.call(this), this.id = t, this.dispatcher = r, this.setEventedParent(o), this.type = 'raster', this.minzoom = 0, this.maxzoom = 22, this.roundZoom = !0, this.scheme = 'xyz', this.tileSize = 512, this._loaded = !1, this._options = util.extend({}, i), util.extend(this, util.pick(i, [
                                'url',
                                'scheme',
                                'tileSize'
                            ]));
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t.prototype.load = function () {
                            var e = this;
                            this.fire('dataloading', { dataType: 'source' }), loadTileJSON(this._options, this.map._transformRequest, function (t, i) {
                                t ? e.fire('error', t) : i && (util.extend(e, i), i.bounds && (e.tileBounds = new TileBounds(i.bounds, e.minzoom, e.maxzoom)), e.fire('data', {
                                    dataType: 'source',
                                    sourceDataType: 'metadata'
                                }), e.fire('data', {
                                    dataType: 'source',
                                    sourceDataType: 'content'
                                }));
                            });
                        }, t.prototype.onAdd = function (e) {
                            this.map = e, this.load();
                        }, t.prototype.serialize = function () {
                            return util.extend({}, this._options);
                        }, t.prototype.hasTile = function (e) {
                            return !this.tileBounds || this.tileBounds.contains(e.canonical);
                        }, t.prototype.loadTile = function (e, t) {
                            var i = this, r = normalizeURL(e.tileID.canonical.url(this.tiles, this.scheme), this.url, this.tileSize);
                            e.request = ajax.getImage(this.map._transformRequest(r, ajax.ResourceType.Tile), function (r, o) {
                                if (delete e.request, e.aborted) {
                                    e.state = 'unloaded', t(null);
                                } else if (r) {
                                    e.state = 'errored', t(r);
                                } else if (o) {
                                    i.map._refreshExpiredTiles && e.setExpiryData(o), delete o.cacheControl, delete o.expires;
                                    var a = i.map.painter.context, n = a.gl;
                                    e.texture = i.map.painter.getTileTexture(o.width), e.texture ? (e.texture.bind(n.LINEAR, n.CLAMP_TO_EDGE, n.LINEAR_MIPMAP_NEAREST), n.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, n.RGBA, n.UNSIGNED_BYTE, o)) : (e.texture = new Texture(a, o, n.RGBA), e.texture.bind(n.LINEAR, n.CLAMP_TO_EDGE, n.LINEAR_MIPMAP_NEAREST), a.extTextureFilterAnisotropic && n.texParameterf(n.TEXTURE_2D, a.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, a.extTextureFilterAnisotropicMax)), n.generateMipmap(n.TEXTURE_2D), e.state = 'loaded', t(null);
                                }
                            });
                        }, t.prototype.abortTile = function (e, t) {
                            e.request && (e.request.abort(), delete e.request), t();
                        }, t.prototype.unloadTile = function (e, t) {
                            e.texture && this.map.painter.saveTileTexture(e.texture), t();
                        }, t.prototype.hasTransition = function () {
                            return !1;
                        }, t;
                    }(Evented);
                module.exports = RasterTileSource;
            },
            {
                '../render/texture': 93,
                '../util/ajax': 251,
                '../util/evented': 260,
                '../util/mapbox': 267,
                '../util/util': 275,
                './load_tilejson': 103,
                './tile_bounds': 113
            }
        ],
        109: [
            function (_dereq_, module, exports) {
                'use strict';
                var ajax = _dereq_('../util/ajax'), Evented = _dereq_('../util/evented'), window = _dereq_('../util/window'), pluginRequested = !1, pluginBlobURL = null;
                module.exports.evented = new Evented(), module.exports.registerForPluginAvailability = function (e) {
                    return pluginBlobURL ? e({
                        pluginBlobURL: pluginBlobURL,
                        errorCallback: module.exports.errorCallback
                    }) : module.exports.evented.once('pluginAvailable', e), e;
                }, module.exports.createBlobURL = function (e) {
                    return window.URL.createObjectURL(new window.Blob([e.data], { type: 'text/javascript' }));
                }, module.exports.clearRTLTextPlugin = function () {
                    pluginRequested = !1, pluginBlobURL = null;
                }, module.exports.setRTLTextPlugin = function (e, l) {
                    if (pluginRequested) {
                        throw new Error('setRTLTextPlugin cannot be called multiple times.');
                    }
                    pluginRequested = !0, module.exports.errorCallback = l, ajax.getArrayBuffer({ url: e }, function (e, t) {
                        e ? l(e) : t && (pluginBlobURL = module.exports.createBlobURL(t), module.exports.evented.fire('pluginAvailable', {
                            pluginBlobURL: pluginBlobURL,
                            errorCallback: l
                        }));
                    });
                }, module.exports.applyArabicShaping = null, module.exports.processBidirectionalText = null;
            },
            {
                '../util/ajax': 251,
                '../util/evented': 260,
                '../util/window': 254
            }
        ],
        110: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), sourceTypes = {
                        vector: _dereq_('../source/vector_tile_source'),
                        raster: _dereq_('../source/raster_tile_source'),
                        'raster-dem': _dereq_('../source/raster_dem_tile_source'),
                        geojson: _dereq_('../source/geojson_source'),
                        video: _dereq_('../source/video_source'),
                        image: _dereq_('../source/image_source'),
                        canvas: _dereq_('../source/canvas_source')
                    };
                exports.create = function (e, r, o, s) {
                    var u = new sourceTypes[r.type](e, r, o, s);
                    if (u.id !== e) {
                        throw new Error('Expected Source id to be ' + e + ' instead of ' + u.id);
                    }
                    return util.bindAll([
                        'load',
                        'abort',
                        'unload',
                        'serialize',
                        'prepare'
                    ], u), u;
                }, exports.getType = function (e) {
                    return sourceTypes[e];
                }, exports.setType = function (e, r) {
                    sourceTypes[e] = r;
                };
            },
            {
                '../source/canvas_source': 98,
                '../source/geojson_source': 99,
                '../source/image_source': 102,
                '../source/raster_dem_tile_source': 106,
                '../source/raster_tile_source': 108,
                '../source/vector_tile_source': 115,
                '../source/video_source': 117,
                '../util/util': 275
            }
        ],
        111: [
            function (_dereq_, module, exports) {
                'use strict';
                function coordinateToTilePoint(e, t) {
                    var i = t.zoomTo(e.canonical.z);
                    return new Point((i.column - (e.canonical.x + e.wrap * Math.pow(2, e.canonical.z))) * EXTENT, (i.row - e.canonical.y) * EXTENT);
                }
                function isRasterType(e) {
                    return 'raster' === e || 'image' === e || 'video' === e;
                }
                var createSource = _dereq_('./source').create, Tile = _dereq_('./tile'), Evented = _dereq_('../util/evented'), Cache = _dereq_('../util/lru_cache'), Coordinate = _dereq_('../geo/coordinate'), util = _dereq_('../util/util'), EXTENT = _dereq_('../data/extent'), Context = _dereq_('../gl/context'), Point = _dereq_('@mapbox/point-geometry'), browser = _dereq_('../util/browser'), ref = _dereq_('./tile_id'), OverscaledTileID = ref.OverscaledTileID, SourceCache = function (e) {
                        function t(t, i, r) {
                            var o = this;
                            e.call(this), this.id = t, this.dispatcher = r, this.on('data', function (e) {
                                'source' === e.dataType && 'metadata' === e.sourceDataType && (o._sourceLoaded = !0), o._sourceLoaded && !o._paused && 'source' === e.dataType && 'content' === e.sourceDataType && (o.reload(), o.transform && o.update(o.transform));
                            }), this.on('error', function () {
                                o._sourceErrored = !0;
                            }), this._source = createSource(t, i, r, this), this._tiles = {}, this._cache = new Cache(0, this._unloadTile.bind(this)), this._timers = {}, this._cacheTimers = {}, this._maxTileCacheSize = null, this._isIdRenderable = this._isIdRenderable.bind(this), this._coveredTiles = {};
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t.prototype.onAdd = function (e) {
                            this.map = e, this._maxTileCacheSize = e ? e._maxTileCacheSize : null, this._source && this._source.onAdd && this._source.onAdd(e);
                        }, t.prototype.onRemove = function (e) {
                            this._source && this._source.onRemove && this._source.onRemove(e);
                        }, t.prototype.loaded = function () {
                            var e = this;
                            if (this._sourceErrored) {
                                return !0;
                            }
                            if (!this._sourceLoaded) {
                                return !1;
                            }
                            for (var t in e._tiles) {
                                var i = e._tiles[t];
                                if ('loaded' !== i.state && 'errored' !== i.state) {
                                    return !1;
                                }
                            }
                            return !0;
                        }, t.prototype.getSource = function () {
                            return this._source;
                        }, t.prototype.pause = function () {
                            this._paused = !0;
                        }, t.prototype.resume = function () {
                            if (this._paused) {
                                var e = this._shouldReloadOnResume;
                                this._paused = !1, this._shouldReloadOnResume = !1, e && this.reload(), this.transform && this.update(this.transform);
                            }
                        }, t.prototype._loadTile = function (e, t) {
                            return this._source.loadTile(e, t);
                        }, t.prototype._unloadTile = function (e) {
                            if (this._source.unloadTile) {
                                return this._source.unloadTile(e, function () {
                                });
                            }
                        }, t.prototype._abortTile = function (e) {
                            if (this._source.abortTile) {
                                return this._source.abortTile(e, function () {
                                });
                            }
                        }, t.prototype.serialize = function () {
                            return this._source.serialize();
                        }, t.prototype.prepare = function (e) {
                            var t = this;
                            this._source.prepare && this._source.prepare();
                            for (var i in t._tiles) {
                                t._tiles[i].upload(e);
                            }
                        }, t.prototype.getIds = function () {
                            var e = this, t = function (t, i) {
                                    var r = e._tiles[t].tileID, o = e._tiles[i].tileID, a = new Point(r.canonical.x, r.canonical.y).rotate(e.transform.angle), s = new Point(o.canonical.x, o.canonical.y).rotate(e.transform.angle);
                                    return r.overscaledZ - o.overscaledZ || s.y - a.y || s.x - a.x;
                                };
                            return Object.keys(this._tiles).map(Number).sort(t);
                        }, t.prototype.getRenderableIds = function () {
                            return this.getIds().filter(this._isIdRenderable);
                        }, t.prototype.hasRenderableParent = function (e) {
                            var t = this.findLoadedParent(e, 0, {});
                            return !!t && this._isIdRenderable(t.tileID.key);
                        }, t.prototype._isIdRenderable = function (e) {
                            return this._tiles[e] && this._tiles[e].hasData() && !this._coveredTiles[e];
                        }, t.prototype.reload = function () {
                            var e = this;
                            if (this._paused) {
                                return void (this._shouldReloadOnResume = !0);
                            }
                            this._resetCache();
                            for (var t in e._tiles) {
                                e._reloadTile(t, 'reloading');
                            }
                        }, t.prototype._reloadTile = function (e, t) {
                            var i = this._tiles[e];
                            i && ('loading' !== i.state && (i.state = t), this._loadTile(i, this._tileLoaded.bind(this, i, e, t)));
                        }, t.prototype._tileLoaded = function (e, t, i, r) {
                            if (r) {
                                return e.state = 'errored', void (404 !== r.status ? this._source.fire('error', {
                                    tile: e,
                                    error: r
                                }) : this.update(this.transform));
                            }
                            e.timeAdded = browser.now(), 'expired' === i && (e.refreshedUponExpiration = !0), this._setTileReloadTimer(t, e), 'raster-dem' === this.getSource().type && e.dem && this._backfillDEM(e), this._source.fire('data', {
                                dataType: 'source',
                                tile: e,
                                coord: e.tileID
                            }), this.map && (this.map.painter.tileExtentVAO.vao = null);
                        }, t.prototype._backfillDEM = function (e) {
                            function t(e, t) {
                                e.needsHillshadePrepare = !0;
                                var i = t.tileID.canonical.x - e.tileID.canonical.x, r = t.tileID.canonical.y - e.tileID.canonical.y, o = Math.pow(2, e.tileID.canonical.z), a = t.tileID.key;
                                0 === i && 0 === r || Math.abs(r) > 1 || (Math.abs(i) > 1 && (1 === Math.abs(i + o) ? i += o : 1 === Math.abs(i - o) && (i -= o)), t.dem && e.dem && (e.dem.backfillBorder(t.dem, i, r), e.neighboringTiles && e.neighboringTiles[a] && (e.neighboringTiles[a].backfilled = !0)));
                            }
                            for (var i = this, r = this.getRenderableIds(), o = 0; o < r.length; o++) {
                                var a = r[o];
                                if (e.neighboringTiles && e.neighboringTiles[a]) {
                                    var s = i.getTileByID(a);
                                    t(e, s), t(s, e);
                                }
                            }
                        }, t.prototype.getTile = function (e) {
                            return this.getTileByID(e.key);
                        }, t.prototype.getTileByID = function (e) {
                            return this._tiles[e];
                        }, t.prototype.getZoom = function (e) {
                            return e.zoom + e.scaleZoom(e.tileSize / this._source.tileSize);
                        }, t.prototype._findLoadedChildren = function (e, t, i) {
                            var r = this, o = !1;
                            for (var a in r._tiles) {
                                var s = r._tiles[a];
                                if (!(i[a] || !s.hasData() || s.tileID.overscaledZ <= e.overscaledZ || s.tileID.overscaledZ > t)) {
                                    var n = Math.pow(2, s.tileID.canonical.z - e.canonical.z);
                                    if (Math.floor(s.tileID.canonical.x / n) === e.canonical.x && Math.floor(s.tileID.canonical.y / n) === e.canonical.y) {
                                        for (i[a] = s.tileID, o = !0; s && s.tileID.overscaledZ - 1 > e.overscaledZ;) {
                                            var l = s.tileID.scaledTo(s.tileID.overscaledZ - 1);
                                            if (!l) {
                                                break;
                                            }
                                            s = r._tiles[l.key], s && s.hasData() && (delete i[a], i[l.key] = l);
                                        }
                                    }
                                }
                            }
                            return o;
                        }, t.prototype.findLoadedParent = function (e, t, i) {
                            for (var r = this, o = e.overscaledZ - 1; o >= t; o--) {
                                var a = e.scaledTo(o);
                                if (!a) {
                                    return;
                                }
                                var s = String(a.key), n = r._tiles[s];
                                if (n && n.hasData()) {
                                    return i[s] = a, n;
                                }
                                if (r._cache.has(s)) {
                                    return i[s] = a, r._cache.get(s);
                                }
                            }
                        }, t.prototype.updateCacheSize = function (e) {
                            var t = Math.ceil(e.width / this._source.tileSize) + 1, i = Math.ceil(e.height / this._source.tileSize) + 1, r = t * i, o = Math.floor(5 * r), a = 'number' == typeof this._maxTileCacheSize ? Math.min(this._maxTileCacheSize, o) : o;
                            this._cache.setMaxSize(a);
                        }, t.prototype.update = function (e) {
                            var i = this;
                            if (this.transform = e, this._sourceLoaded && !this._paused) {
                                this.updateCacheSize(e), this._coveredTiles = {};
                                var r;
                                this.used ? this._source.tileID ? r = e.getVisibleUnwrappedCoordinates(this._source.tileID).map(function (e) {
                                    return new OverscaledTileID(e.canonical.z, e.wrap, e.canonical.z, e.canonical.x, e.canonical.y);
                                }) : (r = e.coveringTiles({
                                    tileSize: this._source.tileSize,
                                    minzoom: this._source.minzoom,
                                    maxzoom: this._source.maxzoom,
                                    roundZoom: this._source.roundZoom,
                                    reparseOverscaled: this._source.reparseOverscaled
                                }), this._source.hasTile && (r = r.filter(function (e) {
                                    return i._source.hasTile(e);
                                }))) : r = [];
                                var o = (this._source.roundZoom ? Math.round : Math.floor)(this.getZoom(e)), a = Math.max(o - t.maxOverzooming, this._source.minzoom), s = Math.max(o + t.maxUnderzooming, this._source.minzoom), n = this._updateRetainedTiles(r, o), l = {};
                                if (isRasterType(this._source.type)) {
                                    for (var c = Object.keys(n), h = 0; h < c.length; h++) {
                                        var d = c[h], u = n[d], _ = i._tiles[d];
                                        if (_ && (void 0 === _.fadeEndTime || _.fadeEndTime >= browser.now())) {
                                            i._findLoadedChildren(u, s, n) && (n[d] = u);
                                            var p = i.findLoadedParent(u, a, l);
                                            p && i._addTile(p.tileID);
                                        }
                                    }
                                }
                                var m;
                                for (m in l) {
                                    n[m] || (i._coveredTiles[m] = !0);
                                }
                                for (m in l) {
                                    n[m] = l[m];
                                }
                                for (var f = util.keysDifference(this._tiles, n), T = 0; T < f.length; T++) {
                                    i._removeTile(f[T]);
                                }
                            }
                        }, t.prototype._updateRetainedTiles = function (e, i) {
                            for (var r = this, o = {}, a = {}, s = Math.max(i - t.maxOverzooming, this._source.minzoom), n = Math.max(i + t.maxUnderzooming, this._source.minzoom), l = 0; l < e.length; l++) {
                                var c = e[l], h = r._addTile(c), d = !1;
                                if (h.hasData()) {
                                    o[c.key] = c;
                                } else {
                                    d = h.wasRequested(), o[c.key] = c;
                                    var u = !0;
                                    if (i + 1 > r._source.maxzoom) {
                                        var _ = c.children(r._source.maxzoom)[0], p = r.getTile(_);
                                        p && p.hasData() ? o[_.key] = _ : u = !1;
                                    } else {
                                        r._findLoadedChildren(c, n, o);
                                        for (var m = c.children(r._source.maxzoom), f = 0; f < m.length; f++) {
                                            if (!o[m[f].key]) {
                                                u = !1;
                                                break;
                                            }
                                        }
                                    }
                                    if (!u) {
                                        for (var T = c.overscaledZ - 1; T >= s; --T) {
                                            var v = c.scaledTo(T);
                                            if (a[v.key]) {
                                                break;
                                            }
                                            if (a[v.key] = !0, h = r.getTile(v), !h && d && (h = r._addTile(v)), h && (o[v.key] = v, d = h.wasRequested(), h.hasData())) {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            return o;
                        }, t.prototype._addTile = function (e) {
                            var t = this._tiles[e.key];
                            if (t) {
                                return t;
                            }
                            (t = this._cache.getAndRemove(e.key)) && this._cacheTimers[e.key] && (clearTimeout(this._cacheTimers[e.key]), delete this._cacheTimers[e.key], this._setTileReloadTimer(e.key, t));
                            var i = Boolean(t);
                            return i || (t = new Tile(e, this._source.tileSize * e.overscaleFactor()), this._loadTile(t, this._tileLoaded.bind(this, t, e.key, t.state))), t ? (t.uses++, this._tiles[e.key] = t, i || this._source.fire('dataloading', {
                                tile: t,
                                coord: t.tileID,
                                dataType: 'source'
                            }), t) : null;
                        }, t.prototype._setTileReloadTimer = function (e, t) {
                            var i = this;
                            e in this._timers && (clearTimeout(this._timers[e]), delete this._timers[e]);
                            var r = t.getExpiryTimeout();
                            r && (this._timers[e] = setTimeout(function () {
                                i._reloadTile(e, 'expired'), delete i._timers[e];
                            }, r));
                        }, t.prototype._setCacheInvalidationTimer = function (e, t) {
                            var i = this;
                            e in this._cacheTimers && (clearTimeout(this._cacheTimers[e]), delete this._cacheTimers[e]);
                            var r = t.getExpiryTimeout();
                            r && (this._cacheTimers[e] = setTimeout(function () {
                                i._cache.remove(e), delete i._cacheTimers[e];
                            }, r));
                        }, t.prototype._removeTile = function (e) {
                            var t = this._tiles[e];
                            if (t && (t.uses--, delete this._tiles[e], this._timers[e] && (clearTimeout(this._timers[e]), delete this._timers[e]), !(t.uses > 0))) {
                                if (t.hasData()) {
                                    t.tileID = t.tileID.wrapped();
                                    var i = t.tileID.key;
                                    this._cache.add(i, t), this._setCacheInvalidationTimer(i, t);
                                } else {
                                    t.aborted = !0, this._abortTile(t), this._unloadTile(t);
                                }
                            }
                        }, t.prototype.clearTiles = function () {
                            var e = this;
                            this._shouldReloadOnResume = !1, this._paused = !1;
                            for (var t in e._tiles) {
                                e._removeTile(t);
                            }
                            this._resetCache();
                        }, t.prototype._resetCache = function () {
                            var e = this;
                            for (var t in e._cacheTimers) {
                                clearTimeout(e._cacheTimers[t]);
                            }
                            this._cacheTimers = {}, this._cache.reset();
                        }, t.prototype.tilesIn = function (e) {
                            for (var t = this, i = [], r = this.getIds(), o = 1 / 0, a = 1 / 0, s = -1 / 0, n = -1 / 0, l = e[0].zoom, c = 0; c < e.length; c++) {
                                var h = e[c];
                                o = Math.min(o, h.column), a = Math.min(a, h.row), s = Math.max(s, h.column), n = Math.max(n, h.row);
                            }
                            for (var d = 0; d < r.length; d++) {
                                var u = t._tiles[r[d]], _ = u.tileID, p = [
                                        coordinateToTilePoint(_, new Coordinate(o, a, l)),
                                        coordinateToTilePoint(_, new Coordinate(s, n, l))
                                    ];
                                if (p[0].x < EXTENT && p[0].y < EXTENT && p[1].x >= 0 && p[1].y >= 0) {
                                    for (var m = [], f = 0; f < e.length; f++) {
                                        m.push(coordinateToTilePoint(_, e[f]));
                                    }
                                    i.push({
                                        tile: u,
                                        tileID: _,
                                        queryGeometry: [m],
                                        scale: Math.pow(2, t.transform.zoom - u.tileID.overscaledZ)
                                    });
                                }
                            }
                            return i;
                        }, t.prototype.getVisibleCoordinates = function () {
                            for (var e = this, t = this.getRenderableIds().map(function (t) {
                                        return e._tiles[t].tileID;
                                    }), i = 0, r = t; i < r.length; i += 1) {
                                var o = r[i];
                                o.posMatrix = e.transform.calculatePosMatrix(o.toUnwrapped());
                            }
                            return t;
                        }, t.prototype.hasTransition = function () {
                            var e = this;
                            if (this._source.hasTransition()) {
                                return !0;
                            }
                            if (isRasterType(this._source.type)) {
                                for (var t in e._tiles) {
                                    var i = e._tiles[t];
                                    if (void 0 !== i.fadeEndTime && i.fadeEndTime >= browser.now()) {
                                        return !0;
                                    }
                                }
                            }
                            return !1;
                        }, t;
                    }(Evented);
                SourceCache.maxOverzooming = 10, SourceCache.maxUnderzooming = 3, module.exports = SourceCache;
            },
            {
                '../data/extent': 53,
                '../geo/coordinate': 61,
                '../gl/context': 66,
                '../util/browser': 252,
                '../util/evented': 260,
                '../util/lru_cache': 266,
                '../util/util': 275,
                './source': 110,
                './tile': 112,
                './tile_id': 114,
                '@mapbox/point-geometry': 4
            }
        ],
        112: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), deserializeBucket = _dereq_('../data/bucket').deserialize, FeatureIndex = _dereq_('../data/feature_index'), vt = _dereq_('@mapbox/vector-tile'), Protobuf = _dereq_('pbf'), GeoJSONFeature = _dereq_('../util/vectortile_to_geojson'), featureFilter = _dereq_('../style-spec/feature_filter'), CollisionIndex = _dereq_('../symbol/collision_index'), SymbolBucket = _dereq_('../data/bucket/symbol_bucket'), ref = _dereq_('../data/array_types'), RasterBoundsArray = ref.RasterBoundsArray, CollisionBoxArray = ref.CollisionBoxArray, rasterBoundsAttributes = _dereq_('../data/raster_bounds_attributes'), EXTENT = _dereq_('../data/extent'), Point = _dereq_('@mapbox/point-geometry'), Texture = _dereq_('../render/texture'), ref$1 = _dereq_('../data/segment'), SegmentVector = ref$1.SegmentVector, ref$2 = _dereq_('../data/index_array_type'), TriangleIndexArray = ref$2.TriangleIndexArray, browser = _dereq_('../util/browser'), CLOCK_SKEW_RETRY_TIMEOUT = 30000, Tile = function (e, t) {
                        this.tileID = e, this.uid = util.uniqueId(), this.uses = 0, this.tileSize = t, this.buckets = {}, this.expirationTime = null, this.expiredRequestCount = 0, this.state = 'loading';
                    };
                Tile.prototype.registerFadeDuration = function (e) {
                    var t = e + this.timeAdded;
                    t < browser.now() || this.fadeEndTime && t < this.fadeEndTime || (this.fadeEndTime = t);
                }, Tile.prototype.wasRequested = function () {
                    return 'errored' === this.state || 'loaded' === this.state || 'reloading' === this.state;
                }, Tile.prototype.loadVectorData = function (e, t, i) {
                    var r = this;
                    if (this.hasData() && this.unloadVectorData(), this.state = 'loaded', !e) {
                        return void (this.collisionBoxArray = new CollisionBoxArray());
                    }
                    if (e.rawTileData && (this.rawTileData = e.rawTileData), this.collisionBoxArray = e.collisionBoxArray, this.featureIndex = e.featureIndex, this.featureIndex.rawTileData = this.rawTileData, this.buckets = deserializeBucket(e.buckets, t.style), i) {
                        for (var a in r.buckets) {
                            var s = r.buckets[a];
                            s instanceof SymbolBucket && (s.justReloaded = !0);
                        }
                    }
                    e.iconAtlasImage && (this.iconAtlasImage = e.iconAtlasImage), e.glyphAtlasImage && (this.glyphAtlasImage = e.glyphAtlasImage);
                }, Tile.prototype.unloadVectorData = function () {
                    var e = this;
                    for (var t in e.buckets) {
                        e.buckets[t].destroy();
                    }
                    this.buckets = {}, this.iconAtlasTexture && this.iconAtlasTexture.destroy(), this.glyphAtlasTexture && this.glyphAtlasTexture.destroy(), this.collisionBoxArray = null, this.featureIndex = null, this.state = 'unloaded';
                }, Tile.prototype.unloadDEMData = function () {
                    this.dem = null, this.neighboringTiles = null, this.state = 'unloaded';
                }, Tile.prototype.getBucket = function (e) {
                    return this.buckets[e.id];
                }, Tile.prototype.upload = function (e) {
                    var t = this;
                    for (var i in t.buckets) {
                        var r = t.buckets[i];
                        r.uploaded || (r.upload(e), r.uploaded = !0);
                    }
                    var a = e.gl;
                    this.iconAtlasImage && (this.iconAtlasTexture = new Texture(e, this.iconAtlasImage, a.RGBA), this.iconAtlasImage = null), this.glyphAtlasImage && (this.glyphAtlasTexture = new Texture(e, this.glyphAtlasImage, a.ALPHA), this.glyphAtlasImage = null);
                }, Tile.prototype.queryRenderedFeatures = function (e, t, i, r, a, s, o) {
                    var n = this;
                    if (!this.featureIndex || !this.collisionBoxArray) {
                        return {};
                    }
                    var l = 0, u = {};
                    for (var h in e) {
                        var d = n.getBucket(e[h]);
                        d && (l = Math.max(l, e[h].queryRadius(d)), d instanceof SymbolBucket && void 0 !== d.bucketInstanceId && (u[d.bucketInstanceId] = !0));
                    }
                    return this.featureIndex.query({
                        queryGeometry: t,
                        scale: i,
                        tileSize: this.tileSize,
                        bearing: a,
                        params: r,
                        additionalRadius: l,
                        collisionBoxArray: this.collisionBoxArray,
                        sourceID: s,
                        collisionIndex: o,
                        bucketInstanceIds: u
                    }, e);
                }, Tile.prototype.querySourceFeatures = function (e, t) {
                    var i = this;
                    if (this.rawTileData) {
                        this.vtLayers || (this.vtLayers = new vt.VectorTile(new Protobuf(this.rawTileData)).layers);
                        var r = t ? t.sourceLayer : '', a = this.vtLayers._geojsonTileLayer || this.vtLayers[r];
                        if (a) {
                            for (var s = featureFilter(t && t.filter), o = {
                                        z: this.tileID.overscaledZ,
                                        x: this.tileID.canonical.x,
                                        y: this.tileID.canonical.y
                                    }, n = 0; n < a.length; n++) {
                                var l = a.feature(n);
                                if (s({ zoom: i.tileID.overscaledZ }, l)) {
                                    var u = new GeoJSONFeature(l, o.z, o.x, o.y);
                                    u.tile = o, e.push(u);
                                }
                            }
                        }
                    }
                }, Tile.prototype.clearMask = function () {
                    this.segments && (this.segments.destroy(), delete this.segments), this.maskedBoundsBuffer && (this.maskedBoundsBuffer.destroy(), delete this.maskedBoundsBuffer), this.maskedIndexBuffer && (this.maskedIndexBuffer.destroy(), delete this.maskedIndexBuffer);
                }, Tile.prototype.setMask = function (e, t) {
                    var i = this;
                    if (!util.deepEqual(this.mask, e) && (this.mask = e, this.clearMask(), !util.deepEqual(e, { 0: !0 }))) {
                        var r = new RasterBoundsArray(), a = new TriangleIndexArray();
                        this.segments = new SegmentVector(), this.segments.prepareSegment(0, r, a);
                        for (var s = Object.keys(e), o = 0; o < s.length; o++) {
                            var n = e[s[o]], l = EXTENT >> n.z, u = new Point(n.x * l, n.y * l), h = new Point(u.x + l, u.y + l), d = i.segments.prepareSegment(4, r, a);
                            r.emplaceBack(u.x, u.y, u.x, u.y), r.emplaceBack(h.x, u.y, h.x, u.y), r.emplaceBack(u.x, h.y, u.x, h.y), r.emplaceBack(h.x, h.y, h.x, h.y);
                            var c = d.vertexLength;
                            a.emplaceBack(c, c + 1, c + 2), a.emplaceBack(c + 1, c + 2, c + 3), d.vertexLength += 4, d.primitiveLength += 2;
                        }
                        this.maskedBoundsBuffer = t.createVertexBuffer(r, rasterBoundsAttributes.members), this.maskedIndexBuffer = t.createIndexBuffer(a);
                    }
                }, Tile.prototype.hasData = function () {
                    return 'loaded' === this.state || 'reloading' === this.state || 'expired' === this.state;
                }, Tile.prototype.setExpiryData = function (e) {
                    var t = this.expirationTime;
                    if (e.cacheControl) {
                        var i = util.parseCacheControl(e.cacheControl);
                        i['max-age'] && (this.expirationTime = Date.now() + 1000 * i['max-age']);
                    } else {
                        e.expires && (this.expirationTime = new Date(e.expires).getTime());
                    }
                    if (this.expirationTime) {
                        var r = Date.now(), a = !1;
                        if (this.expirationTime > r) {
                            a = !1;
                        } else if (t) {
                            if (this.expirationTime < t) {
                                a = !0;
                            } else {
                                var s = this.expirationTime - t;
                                s ? this.expirationTime = r + Math.max(s, CLOCK_SKEW_RETRY_TIMEOUT) : a = !0;
                            }
                        } else {
                            a = !0;
                        }
                        a ? (this.expiredRequestCount++, this.state = 'expired') : this.expiredRequestCount = 0;
                    }
                }, Tile.prototype.getExpiryTimeout = function () {
                    if (this.expirationTime) {
                        return this.expiredRequestCount ? 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31)) : Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);
                    }
                }, module.exports = Tile;
            },
            {
                '../data/array_types': 39,
                '../data/bucket': 40,
                '../data/bucket/symbol_bucket': 51,
                '../data/extent': 53,
                '../data/feature_index': 54,
                '../data/index_array_type': 55,
                '../data/raster_bounds_attributes': 59,
                '../data/segment': 60,
                '../render/texture': 93,
                '../style-spec/feature_filter': 148,
                '../symbol/collision_index': 217,
                '../util/browser': 252,
                '../util/util': 275,
                '../util/vectortile_to_geojson': 276,
                '@mapbox/point-geometry': 4,
                '@mapbox/vector-tile': 8,
                'pbf': 30
            }
        ],
        113: [
            function (_dereq_, module, exports) {
                'use strict';
                var LngLatBounds = _dereq_('../geo/lng_lat_bounds'), clamp = _dereq_('../util/util').clamp, TileBounds = function (t, n, o) {
                        this.bounds = LngLatBounds.convert(this.validateBounds(t)), this.minzoom = n || 0, this.maxzoom = o || 24;
                    };
                TileBounds.prototype.validateBounds = function (t) {
                    return Array.isArray(t) && 4 === t.length ? [
                        Math.max(-180, t[0]),
                        Math.max(-90, t[1]),
                        Math.min(180, t[2]),
                        Math.min(90, t[3])
                    ] : [
                        -180,
                        -90,
                        180,
                        90
                    ];
                }, TileBounds.prototype.contains = function (t) {
                    var n = {
                        minX: Math.floor(this.lngX(this.bounds.getWest(), t.z)),
                        minY: Math.floor(this.latY(this.bounds.getNorth(), t.z)),
                        maxX: Math.ceil(this.lngX(this.bounds.getEast(), t.z)),
                        maxY: Math.ceil(this.latY(this.bounds.getSouth(), t.z))
                    };
                    return t.x >= n.minX && t.x < n.maxX && t.y >= n.minY && t.y < n.maxY;
                }, TileBounds.prototype.lngX = function (t, n) {
                    return (t + 180) * (Math.pow(2, n) / 360);
                }, TileBounds.prototype.latY = function (t, n) {
                    var o = clamp(Math.sin(Math.PI / 180 * t), -0.9999, 0.9999), a = Math.pow(2, n) / (2 * Math.PI);
                    return Math.pow(2, n - 1) + 0.5 * Math.log((1 + o) / (1 - o)) * -a;
                }, module.exports = TileBounds;
            },
            {
                '../geo/lng_lat_bounds': 63,
                '../util/util': 275
            }
        ],
        114: [
            function (_dereq_, module, exports) {
                'use strict';
                function calculateKey(e, i, a, t) {
                    (e *= 2) < 0 && (e = -1 * e - 1);
                    var n = 1 << i;
                    return 32 * (n * n * e + n * t + a) + i;
                }
                function getQuadkey(e, i, a) {
                    for (var t, n = '', c = e; c > 0; c--) {
                        t = 1 << c - 1, n += (i & t ? 1 : 0) + (a & t ? 2 : 0);
                    }
                    return n;
                }
                var WhooTS = _dereq_('@mapbox/whoots-js'), ref = _dereq_('../util/web_worker_transfer'), register = ref.register, Coordinate = _dereq_('../geo/coordinate'), CanonicalTileID = function (e, i, a) {
                        this.z = e, this.x = i, this.y = a, this.key = calculateKey(0, e, i, a);
                    };
                CanonicalTileID.prototype.equals = function (e) {
                    return this.z === e.z && this.x === e.x && this.y === e.y;
                }, CanonicalTileID.prototype.url = function (e, i) {
                    var a = WhooTS.getTileBBox(this.x, this.y, this.z), t = getQuadkey(this.z, this.x, this.y);
                    return e[(this.x + this.y) % e.length].replace('{prefix}', (this.x % 16).toString(16) + (this.y % 16).toString(16)).replace('{z}', String(this.z)).replace('{x}', String(this.x)).replace('{y}', String('tms' === i ? Math.pow(2, this.z) - this.y - 1 : this.y)).replace('{quadkey}', t).replace('{bbox-epsg-3857}', a);
                };
                var UnwrappedTileID = function (e, i) {
                        this.wrap = e, this.canonical = i, this.key = calculateKey(e, i.z, i.x, i.y);
                    }, OverscaledTileID = function (e, i, a, t, n) {
                        this.overscaledZ = e, this.wrap = i, this.canonical = new CanonicalTileID(a, +t, +n), this.key = calculateKey(i, e, t, n);
                    };
                OverscaledTileID.prototype.scaledTo = function (e) {
                    var i = this.canonical.z - e;
                    return e > this.canonical.z ? new OverscaledTileID(e, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y) : new OverscaledTileID(e, this.wrap, e, this.canonical.x >> i, this.canonical.y >> i);
                }, OverscaledTileID.prototype.isChildOf = function (e) {
                    var i = this.canonical.z - e.canonical.z;
                    return 0 === e.overscaledZ || e.overscaledZ < this.overscaledZ && e.canonical.x === this.canonical.x >> i && e.canonical.y === this.canonical.y >> i;
                }, OverscaledTileID.prototype.children = function (e) {
                    if (this.overscaledZ >= e) {
                        return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];
                    }
                    var i = this.canonical.z + 1, a = 2 * this.canonical.x, t = 2 * this.canonical.y;
                    return [
                        new OverscaledTileID(i, this.wrap, i, a, t),
                        new OverscaledTileID(i, this.wrap, i, a + 1, t),
                        new OverscaledTileID(i, this.wrap, i, a, t + 1),
                        new OverscaledTileID(i, this.wrap, i, a + 1, t + 1)
                    ];
                }, OverscaledTileID.prototype.isLessThan = function (e) {
                    return this.wrap < e.wrap || !(this.wrap > e.wrap) && (this.overscaledZ < e.overscaledZ || !(this.overscaledZ > e.overscaledZ) && (this.canonical.x < e.canonical.x || !(this.canonical.x > e.canonical.x) && this.canonical.y < e.canonical.y));
                }, OverscaledTileID.prototype.wrapped = function () {
                    return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);
                }, OverscaledTileID.prototype.overscaleFactor = function () {
                    return Math.pow(2, this.overscaledZ - this.canonical.z);
                }, OverscaledTileID.prototype.toUnwrapped = function () {
                    return new UnwrappedTileID(this.wrap, this.canonical);
                }, OverscaledTileID.prototype.toString = function () {
                    return this.overscaledZ + '/' + this.canonical.x + '/' + this.canonical.y;
                }, OverscaledTileID.prototype.toCoordinate = function () {
                    return new Coordinate(this.canonical.x + Math.pow(2, this.wrap), this.canonical.y, this.canonical.z);
                }, register('CanonicalTileID', CanonicalTileID), register('OverscaledTileID', OverscaledTileID, { omit: ['posMatrix'] }), module.exports = {
                    CanonicalTileID: CanonicalTileID,
                    OverscaledTileID: OverscaledTileID,
                    UnwrappedTileID: UnwrappedTileID
                };
            },
            {
                '../geo/coordinate': 61,
                '../util/web_worker_transfer': 278,
                '@mapbox/whoots-js': 12
            }
        ],
        115: [
            function (_dereq_, module, exports) {
                'use strict';
                var Evented = _dereq_('../util/evented'), util = _dereq_('../util/util'), loadTileJSON = _dereq_('./load_tilejson'), normalizeURL = _dereq_('../util/mapbox').normalizeTileURL, TileBounds = _dereq_('./tile_bounds'), ResourceType = _dereq_('../util/ajax').ResourceType, browser = _dereq_('../util/browser'), VectorTileSource = function (e) {
                        function t(t, i, o, r) {
                            if (e.call(this), this.id = t, this.dispatcher = o, this.type = 'vector', this.minzoom = 0, this.maxzoom = 22, this.scheme = 'xyz', this.tileSize = 512, this.reparseOverscaled = !0, this.isTileClipped = !0, util.extend(this, util.pick(i, [
                                    'url',
                                    'scheme',
                                    'tileSize'
                                ])), this._options = util.extend({ type: 'vector' }, i), this._collectResourceTiming = i.collectResourceTiming, 512 !== this.tileSize) {
                                throw new Error('vector tile sources must have a tileSize of 512');
                            }
                            this.setEventedParent(r);
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t.prototype.load = function () {
                            var e = this;
                            this.fire('dataloading', { dataType: 'source' }), loadTileJSON(this._options, this.map._transformRequest, function (t, i) {
                                t ? e.fire('error', t) : i && (util.extend(e, i), i.bounds && (e.tileBounds = new TileBounds(i.bounds, e.minzoom, e.maxzoom)), e.fire('data', {
                                    dataType: 'source',
                                    sourceDataType: 'metadata'
                                }), e.fire('data', {
                                    dataType: 'source',
                                    sourceDataType: 'content'
                                }));
                            });
                        }, t.prototype.hasTile = function (e) {
                            return !this.tileBounds || this.tileBounds.contains(e.canonical);
                        }, t.prototype.onAdd = function (e) {
                            this.map = e, this.load();
                        }, t.prototype.serialize = function () {
                            return util.extend({}, this._options);
                        }, t.prototype.loadTile = function (e, t) {
                            function i(i, o) {
                                return e.aborted ? t(null) : i ? t(i) : (o && o.resourceTiming && (e.resourceTiming = o.resourceTiming), this.map._refreshExpiredTiles && e.setExpiryData(o), e.loadVectorData(o, this.map.painter), t(null), void (e.reloadCallback && (this.loadTile(e, e.reloadCallback), e.reloadCallback = null)));
                            }
                            var o = e.tileID.overscaleFactor(), r = normalizeURL(e.tileID.canonical.url(this.tiles, this.scheme), this.url), s = {
                                    request: this.map._transformRequest(r, ResourceType.Tile),
                                    uid: e.uid,
                                    tileID: e.tileID,
                                    zoom: e.tileID.overscaledZ,
                                    tileSize: this.tileSize * o,
                                    type: this.type,
                                    source: this.id,
                                    pixelRatio: browser.devicePixelRatio,
                                    overscaling: o,
                                    showCollisionBoxes: this.map.showCollisionBoxes
                                };
                            s.request.collectResourceTiming = this._collectResourceTiming, void 0 === e.workerID || 'expired' === e.state ? e.workerID = this.dispatcher.send('loadTile', s, i.bind(this)) : 'loading' === e.state ? e.reloadCallback = t : this.dispatcher.send('reloadTile', s, i.bind(this), e.workerID);
                        }, t.prototype.abortTile = function (e) {
                            this.dispatcher.send('abortTile', {
                                uid: e.uid,
                                type: this.type,
                                source: this.id
                            }, void 0, e.workerID);
                        }, t.prototype.unloadTile = function (e) {
                            e.unloadVectorData(), this.dispatcher.send('removeTile', {
                                uid: e.uid,
                                type: this.type,
                                source: this.id
                            }, void 0, e.workerID);
                        }, t.prototype.hasTransition = function () {
                            return !1;
                        }, t;
                    }(Evented);
                module.exports = VectorTileSource;
            },
            {
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/evented': 260,
                '../util/mapbox': 267,
                '../util/util': 275,
                './load_tilejson': 103,
                './tile_bounds': 113
            }
        ],
        116: [
            function (_dereq_, module, exports) {
                'use strict';
                function loadVectorTile(e, r) {
                    var o = ajax.getArrayBuffer(e.request, function (e, o) {
                        e ? r(e) : o && r(null, {
                            vectorTile: new vt.VectorTile(new Protobuf(o.data)),
                            rawData: o.data,
                            cacheControl: o.cacheControl,
                            expires: o.expires
                        });
                    });
                    return function () {
                        o.abort(), r();
                    };
                }
                var ajax = _dereq_('../util/ajax'), vt = _dereq_('@mapbox/vector-tile'), Protobuf = _dereq_('pbf'), WorkerTile = _dereq_('./worker_tile'), util = _dereq_('../util/util'), perf = _dereq_('../util/performance'), VectorTileWorkerSource = function (e, r, o) {
                        this.actor = e, this.layerIndex = r, this.loadVectorData = o || loadVectorTile, this.loading = {}, this.loaded = {};
                    };
                VectorTileWorkerSource.prototype.loadTile = function (e, r) {
                    var o = this, t = e.source, i = e.uid;
                    this.loading[t] || (this.loading[t] = {});
                    var a = this.loading[t][i] = new WorkerTile(e);
                    a.abort = this.loadVectorData(e, function (l, c) {
                        if (delete o.loading[t][i], l || !c) {
                            return r(l);
                        }
                        var s = c.rawData, n = {};
                        c.expires && (n.expires = c.expires), c.cacheControl && (n.cacheControl = c.cacheControl);
                        var u = {};
                        if (e.request && e.request.collectResourceTiming) {
                            var d = perf.getEntriesByName(e.request.url);
                            d && (u.resourceTiming = JSON.parse(JSON.stringify(d)));
                        }
                        a.vectorTile = c.vectorTile, a.parse(c.vectorTile, o.layerIndex, o.actor, function (e, o) {
                            if (e || !o) {
                                return r(e);
                            }
                            r(null, util.extend({ rawTileData: s.slice(0) }, o, n, u));
                        }), o.loaded[t] = o.loaded[t] || {}, o.loaded[t][i] = a;
                    });
                }, VectorTileWorkerSource.prototype.reloadTile = function (e, r) {
                    function o(e, o) {
                        if (this.reloadCallback) {
                            var t = this.reloadCallback;
                            delete this.reloadCallback, this.parse(this.vectorTile, a.layerIndex, a.actor, t);
                        }
                        r(e, o);
                    }
                    var t = this.loaded[e.source], i = e.uid, a = this;
                    if (t && t[i]) {
                        var l = t[i];
                        l.showCollisionBoxes = e.showCollisionBoxes, 'parsing' === l.status ? l.reloadCallback = r : 'done' === l.status && l.parse(l.vectorTile, this.layerIndex, this.actor, o.bind(l));
                    }
                }, VectorTileWorkerSource.prototype.abortTile = function (e, r) {
                    var o = this.loading[e.source], t = e.uid;
                    o && o[t] && o[t].abort && (o[t].abort(), delete o[t]), r();
                }, VectorTileWorkerSource.prototype.removeTile = function (e, r) {
                    var o = this.loaded[e.source], t = e.uid;
                    o && o[t] && delete o[t], r();
                }, module.exports = VectorTileWorkerSource;
            },
            {
                '../util/ajax': 251,
                '../util/performance': 268,
                '../util/util': 275,
                './worker_tile': 119,
                '@mapbox/vector-tile': 8,
                'pbf': 30
            }
        ],
        117: [
            function (_dereq_, module, exports) {
                'use strict';
                var ajax = _dereq_('../util/ajax'), ImageSource = _dereq_('./image_source'), rasterBoundsAttributes = _dereq_('../data/raster_bounds_attributes'), VertexArrayObject = _dereq_('../render/vertex_array_object'), Texture = _dereq_('../render/texture'), VideoSource = function (e) {
                        function t(t, r, i, o) {
                            e.call(this, t, r, i, o), this.roundZoom = !0, this.type = 'video', this.options = r;
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t.prototype.load = function () {
                            var e = this, t = this.options;
                            this.urls = t.urls, ajax.getVideo(t.urls, function (t, r) {
                                t ? e.fire('error', { error: t }) : r && (e.video = r, e.video.loop = !0, e.video.addEventListener('playing', function () {
                                    e.map._rerender();
                                }), e.map && e.video.play(), e._finishLoading());
                            });
                        }, t.prototype.getVideo = function () {
                            return this.video;
                        }, t.prototype.onAdd = function (e) {
                            this.map || (this.map = e, this.load(), this.video && (this.video.play(), this.setCoordinates(this.coordinates)));
                        }, t.prototype.prepare = function () {
                            var e = this;
                            if (!(0 === Object.keys(this.tiles).length || this.video.readyState < 2)) {
                                var t = this.map.painter.context, r = t.gl;
                                this.boundsBuffer || (this.boundsBuffer = t.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members)), this.boundsVAO || (this.boundsVAO = new VertexArrayObject()), this.texture ? this.video.paused || (this.texture.bind(r.LINEAR, r.CLAMP_TO_EDGE), r.texSubImage2D(r.TEXTURE_2D, 0, 0, 0, r.RGBA, r.UNSIGNED_BYTE, this.video)) : (this.texture = new Texture(t, this.video, r.RGBA), this.texture.bind(r.LINEAR, r.CLAMP_TO_EDGE));
                                for (var i in e.tiles) {
                                    var o = e.tiles[i];
                                    'loaded' !== o.state && (o.state = 'loaded', o.texture = e.texture);
                                }
                            }
                        }, t.prototype.serialize = function () {
                            return {
                                type: 'video',
                                urls: this.urls,
                                coordinates: this.coordinates
                            };
                        }, t.prototype.hasTransition = function () {
                            return this.video && !this.video.paused;
                        }, t;
                    }(ImageSource);
                module.exports = VideoSource;
            },
            {
                '../data/raster_bounds_attributes': 59,
                '../render/texture': 93,
                '../render/vertex_array_object': 95,
                '../util/ajax': 251,
                './image_source': 102
            }
        ],
        118: [
            function (_dereq_, module, exports) {
                'use strict';
                var Actor = _dereq_('../util/actor'), StyleLayerIndex = _dereq_('../style/style_layer_index'), VectorTileWorkerSource = _dereq_('./vector_tile_worker_source'), RasterDEMTileWorkerSource = _dereq_('./raster_dem_tile_worker_source'), GeoJSONWorkerSource = _dereq_('./geojson_worker_source'), globalRTLTextPlugin = _dereq_('./rtl_text_plugin'), Worker = function (e) {
                        var r = this;
                        this.self = e, this.actor = new Actor(e, this), this.layerIndexes = {}, this.workerSourceTypes = {
                            vector: VectorTileWorkerSource,
                            geojson: GeoJSONWorkerSource
                        }, this.workerSources = {}, this.demWorkerSources = {}, this.self.registerWorkerSource = function (e, o) {
                            if (r.workerSourceTypes[e]) {
                                throw new Error('Worker source with name "' + e + '" already registered.');
                            }
                            r.workerSourceTypes[e] = o;
                        }, this.self.registerRTLTextPlugin = function (e) {
                            if (globalRTLTextPlugin.applyArabicShaping || globalRTLTextPlugin.processBidirectionalText) {
                                throw new Error('RTL text plugin already registered.');
                            }
                            globalRTLTextPlugin.applyArabicShaping = e.applyArabicShaping, globalRTLTextPlugin.processBidirectionalText = e.processBidirectionalText;
                        };
                    };
                Worker.prototype.setLayers = function (e, r, o) {
                    this.getLayerIndex(e).replace(r), o();
                }, Worker.prototype.updateLayers = function (e, r, o) {
                    this.getLayerIndex(e).update(r.layers, r.removedIds), o();
                }, Worker.prototype.loadTile = function (e, r, o) {
                    this.getWorkerSource(e, r.type).loadTile(r, o);
                }, Worker.prototype.loadDEMTile = function (e, r, o) {
                    this.getDEMWorkerSource(e).loadTile(r, o);
                }, Worker.prototype.reloadTile = function (e, r, o) {
                    this.getWorkerSource(e, r.type).reloadTile(r, o);
                }, Worker.prototype.abortTile = function (e, r, o) {
                    this.getWorkerSource(e, r.type).abortTile(r, o);
                }, Worker.prototype.removeTile = function (e, r, o) {
                    this.getWorkerSource(e, r.type).removeTile(r, o);
                }, Worker.prototype.removeDEMTile = function (e, r) {
                    this.getDEMWorkerSource(e).removeTile(r);
                }, Worker.prototype.removeSource = function (e, r, o) {
                    var t = this.getWorkerSource(e, r.type);
                    void 0 !== t.removeSource ? t.removeSource(r, o) : o();
                }, Worker.prototype.loadWorkerSource = function (e, r, o) {
                    try {
                        this.self.importScripts(r.url), o();
                    } catch (e) {
                        o(e);
                    }
                }, Worker.prototype.loadRTLTextPlugin = function (e, r, o) {
                    try {
                        globalRTLTextPlugin.applyArabicShaping || globalRTLTextPlugin.processBidirectionalText || (this.self.importScripts(r), globalRTLTextPlugin.applyArabicShaping && globalRTLTextPlugin.processBidirectionalText || o(new Error('RTL Text Plugin failed to import scripts from ' + r)));
                    } catch (e) {
                        o(e);
                    }
                }, Worker.prototype.getLayerIndex = function (e) {
                    var r = this.layerIndexes[e];
                    return r || (r = this.layerIndexes[e] = new StyleLayerIndex()), r;
                }, Worker.prototype.getWorkerSource = function (e, r) {
                    var o = this;
                    if (this.workerSources[e] || (this.workerSources[e] = {}), !this.workerSources[e][r]) {
                        var t = {
                            send: function (r, t, i) {
                                o.actor.send(r, t, i, e);
                            }
                        };
                        this.workerSources[e][r] = new this.workerSourceTypes[r](t, this.getLayerIndex(e));
                    }
                    return this.workerSources[e][r];
                }, Worker.prototype.getDEMWorkerSource = function (e) {
                    return this.demWorkerSources[e] || (this.demWorkerSources[e] = new RasterDEMTileWorkerSource()), this.demWorkerSources[e];
                }, module.exports = function (e) {
                    return new Worker(e);
                };
            },
            {
                '../style/style_layer_index': 210,
                '../util/actor': 250,
                './geojson_worker_source': 100,
                './raster_dem_tile_worker_source': 107,
                './rtl_text_plugin': 109,
                './vector_tile_worker_source': 116
            }
        ],
        119: [
            function (_dereq_, module, exports) {
                'use strict';
                function recalculateLayers(e, r) {
                    for (var i = new EvaluationParameters(r), o = 0, a = e; o < a.length; o += 1) {
                        a[o].recalculate(i);
                    }
                }
                var FeatureIndex = _dereq_('../data/feature_index'), ref = _dereq_('../symbol/symbol_layout'), performSymbolLayout = ref.performSymbolLayout, ref$1 = _dereq_('../data/array_types'), CollisionBoxArray = ref$1.CollisionBoxArray, DictionaryCoder = _dereq_('../util/dictionary_coder'), SymbolBucket = _dereq_('../data/bucket/symbol_bucket'), util = _dereq_('../util/util'), ref$2 = _dereq_('../render/image_atlas'), makeImageAtlas = ref$2.makeImageAtlas, ref$3 = _dereq_('../render/glyph_atlas'), makeGlyphAtlas = ref$3.makeGlyphAtlas, EvaluationParameters = _dereq_('../style/evaluation_parameters'), ref$4 = _dereq_('./tile_id'), OverscaledTileID = ref$4.OverscaledTileID, WorkerTile = function (e) {
                        this.tileID = new OverscaledTileID(e.tileID.overscaledZ, e.tileID.wrap, e.tileID.canonical.z, e.tileID.canonical.x, e.tileID.canonical.y), this.uid = e.uid, this.zoom = e.zoom, this.pixelRatio = e.pixelRatio, this.tileSize = e.tileSize, this.source = e.source, this.overscaling = e.overscaling, this.showCollisionBoxes = e.showCollisionBoxes, this.collectResourceTiming = !!e.collectResourceTiming;
                    };
                WorkerTile.prototype.parse = function (e, r, i, o) {
                    function a() {
                        var e = this;
                        if (k) {
                            return o(k);
                        }
                        if (b && D) {
                            var r = makeGlyphAtlas(b), i = makeImageAtlas(D);
                            for (var a in n) {
                                var t = n[a];
                                t instanceof SymbolBucket && (recalculateLayers(t.layers, e.zoom), performSymbolLayout(t, b, r.positions, D, i.positions, e.showCollisionBoxes));
                            }
                            this.status = 'done', o(null, {
                                buckets: util.values(n).filter(function (e) {
                                    return !e.isEmpty();
                                }),
                                featureIndex: s,
                                collisionBoxArray: this.collisionBoxArray,
                                glyphAtlasImage: r.image,
                                iconAtlasImage: i.image
                            });
                        }
                    }
                    var t = this;
                    this.status = 'parsing', this.data = e, this.collisionBoxArray = new CollisionBoxArray();
                    var l = new DictionaryCoder(Object.keys(e.layers).sort()), s = new FeatureIndex(this.tileID, this.overscaling);
                    s.bucketLayerIDs = [];
                    var n = {}, c = {
                            featureIndex: s,
                            iconDependencies: {},
                            glyphDependencies: {}
                        }, u = r.familiesBySource[this.source];
                    for (var m in u) {
                        var y = e.layers[m];
                        if (y) {
                            1 === y.version && util.warnOnce('Vector tile source "' + t.source + '" layer "' + m + '" does not use vector tile spec v2 and therefore may have some rendering errors.');
                            for (var h = l.encode(m), d = [], f = 0; f < y.length; f++) {
                                var p = y.feature(f);
                                d.push({
                                    feature: p,
                                    index: f,
                                    sourceLayerIndex: h
                                });
                            }
                            for (var v = 0, g = u[m]; v < g.length; v += 1) {
                                var x = g[v], I = x[0];
                                if (!(I.minzoom && t.zoom < Math.floor(I.minzoom)) && (!(I.maxzoom && t.zoom >= I.maxzoom) && 'none' !== I.visibility)) {
                                    recalculateLayers(x, t.zoom);
                                    (n[I.id] = I.createBucket({
                                        index: s.bucketLayerIDs.length,
                                        layers: x,
                                        zoom: t.zoom,
                                        pixelRatio: t.pixelRatio,
                                        overscaling: t.overscaling,
                                        collisionBoxArray: t.collisionBoxArray
                                    })).populate(d, c), s.bucketLayerIDs.push(x.map(function (e) {
                                        return e.id;
                                    }));
                                }
                            }
                        }
                    }
                    var k, b, D, A = util.mapObject(c.glyphDependencies, function (e) {
                            return Object.keys(e).map(Number);
                        });
                    Object.keys(A).length ? i.send('getGlyphs', {
                        uid: this.uid,
                        stacks: A
                    }, function (e, r) {
                        k || (k = e, b = r, a.call(t));
                    }) : b = {};
                    var z = Object.keys(c.iconDependencies);
                    z.length ? i.send('getImages', { icons: z }, function (e, r) {
                        k || (k = e, D = r, a.call(t));
                    }) : D = {}, a.call(this);
                }, module.exports = WorkerTile;
            },
            {
                '../data/array_types': 39,
                '../data/bucket/symbol_bucket': 51,
                '../data/feature_index': 54,
                '../render/glyph_atlas': 85,
                '../render/image_atlas': 87,
                '../style/evaluation_parameters': 182,
                '../symbol/symbol_layout': 227,
                '../util/dictionary_coder': 257,
                '../util/util': 275,
                './tile_id': 114
            }
        ],
        120: [
            function (_dereq_, module, exports) {
                'use strict';
                function deref(r, e) {
                    var f = {};
                    for (var t in r) {
                        'ref' !== t && (f[t] = r[t]);
                    }
                    return refProperties.forEach(function (r) {
                        r in e && (f[r] = e[r]);
                    }), f;
                }
                function derefLayers(r) {
                    r = r.slice();
                    for (var e = Object.create(null), f = 0; f < r.length; f++) {
                        e[r[f].id] = r[f];
                    }
                    for (var t = 0; t < r.length; t++) {
                        'ref' in r[t] && (r[t] = deref(r[t], e[r[t].ref]));
                    }
                    return r;
                }
                var refProperties = _dereq_('./util/ref_properties');
                module.exports = derefLayers;
            },
            { './util/ref_properties': 159 }
        ],
        121: [
            function (_dereq_, module, exports) {
                'use strict';
                function addSource(e, r, o) {
                    o.push({
                        command: operations.addSource,
                        args: [
                            e,
                            r[e]
                        ]
                    });
                }
                function removeSource(e, r, o) {
                    r.push({
                        command: operations.removeSource,
                        args: [e]
                    }), o[e] = !0;
                }
                function updateSource(e, r, o, a) {
                    removeSource(e, o, a), addSource(e, r, o);
                }
                function canUpdateGeoJSON(e, r, o) {
                    var a;
                    for (a in e[o]) {
                        if (e[o].hasOwnProperty(a) && 'data' !== a && !isEqual(e[o][a], r[o][a])) {
                            return !1;
                        }
                    }
                    for (a in r[o]) {
                        if (r[o].hasOwnProperty(a) && 'data' !== a && !isEqual(e[o][a], r[o][a])) {
                            return !1;
                        }
                    }
                    return !0;
                }
                function diffSources(e, r, o, a) {
                    e = e || {}, r = r || {};
                    var t;
                    for (t in e) {
                        e.hasOwnProperty(t) && (r.hasOwnProperty(t) || removeSource(t, o, a));
                    }
                    for (t in r) {
                        r.hasOwnProperty(t) && (e.hasOwnProperty(t) ? isEqual(e[t], r[t]) || ('geojson' === e[t].type && 'geojson' === r[t].type && canUpdateGeoJSON(e, r, t) ? o.push({
                            command: operations.setGeoJSONSourceData,
                            args: [
                                t,
                                r[t].data
                            ]
                        }) : updateSource(t, r, o, a)) : addSource(t, r, o));
                    }
                }
                function diffLayerPropertyChanges(e, r, o, a, t, s) {
                    e = e || {}, r = r || {};
                    var n;
                    for (n in e) {
                        e.hasOwnProperty(n) && (isEqual(e[n], r[n]) || o.push({
                            command: s,
                            args: [
                                a,
                                n,
                                r[n],
                                t
                            ]
                        }));
                    }
                    for (n in r) {
                        r.hasOwnProperty(n) && !e.hasOwnProperty(n) && (isEqual(e[n], r[n]) || o.push({
                            command: s,
                            args: [
                                a,
                                n,
                                r[n],
                                t
                            ]
                        }));
                    }
                }
                function pluckId(e) {
                    return e.id;
                }
                function indexById(e, r) {
                    return e[r.id] = r, e;
                }
                function diffLayers(e, r, o) {
                    e = e || [], r = r || [];
                    var a, t, s, n, i, p, u, m = e.map(pluckId), c = r.map(pluckId), l = e.reduce(indexById, {}), d = r.reduce(indexById, {}), y = m.slice(), h = Object.create(null);
                    for (a = 0, t = 0; a < m.length; a++) {
                        s = m[a], d.hasOwnProperty(s) ? t++ : (o.push({
                            command: operations.removeLayer,
                            args: [s]
                        }), y.splice(y.indexOf(s, t), 1));
                    }
                    for (a = 0, t = 0; a < c.length; a++) {
                        s = c[c.length - 1 - a], y[y.length - 1 - a] !== s && (l.hasOwnProperty(s) ? (o.push({
                            command: operations.removeLayer,
                            args: [s]
                        }), y.splice(y.lastIndexOf(s, y.length - t), 1)) : t++, p = y[y.length - a], o.push({
                            command: operations.addLayer,
                            args: [
                                d[s],
                                p
                            ]
                        }), y.splice(y.length - a, 0, s), h[s] = !0);
                    }
                    for (a = 0; a < c.length; a++) {
                        if (s = c[a], n = l[s], i = d[s], !h[s] && !isEqual(n, i)) {
                            if (isEqual(n.source, i.source) && isEqual(n['source-layer'], i['source-layer']) && isEqual(n.type, i.type)) {
                                diffLayerPropertyChanges(n.layout, i.layout, o, s, null, operations.setLayoutProperty), diffLayerPropertyChanges(n.paint, i.paint, o, s, null, operations.setPaintProperty), isEqual(n.filter, i.filter) || o.push({
                                    command: operations.setFilter,
                                    args: [
                                        s,
                                        i.filter
                                    ]
                                }), isEqual(n.minzoom, i.minzoom) && isEqual(n.maxzoom, i.maxzoom) || o.push({
                                    command: operations.setLayerZoomRange,
                                    args: [
                                        s,
                                        i.minzoom,
                                        i.maxzoom
                                    ]
                                });
                                for (u in n) {
                                    n.hasOwnProperty(u) && 'layout' !== u && 'paint' !== u && 'filter' !== u && 'metadata' !== u && 'minzoom' !== u && 'maxzoom' !== u && (0 === u.indexOf('paint.') ? diffLayerPropertyChanges(n[u], i[u], o, s, u.slice(6), operations.setPaintProperty) : isEqual(n[u], i[u]) || o.push({
                                        command: operations.setLayerProperty,
                                        args: [
                                            s,
                                            u,
                                            i[u]
                                        ]
                                    }));
                                }
                                for (u in i) {
                                    i.hasOwnProperty(u) && !n.hasOwnProperty(u) && 'layout' !== u && 'paint' !== u && 'filter' !== u && 'metadata' !== u && 'minzoom' !== u && 'maxzoom' !== u && (0 === u.indexOf('paint.') ? diffLayerPropertyChanges(n[u], i[u], o, s, u.slice(6), operations.setPaintProperty) : isEqual(n[u], i[u]) || o.push({
                                        command: operations.setLayerProperty,
                                        args: [
                                            s,
                                            u,
                                            i[u]
                                        ]
                                    }));
                                }
                            } else {
                                o.push({
                                    command: operations.removeLayer,
                                    args: [s]
                                }), p = y[y.lastIndexOf(s) + 1], o.push({
                                    command: operations.addLayer,
                                    args: [
                                        i,
                                        p
                                    ]
                                });
                            }
                        }
                    }
                }
                function diffStyles(e, r) {
                    if (!e) {
                        return [{
                                command: operations.setStyle,
                                args: [r]
                            }];
                    }
                    var o = [];
                    try {
                        if (!isEqual(e.version, r.version)) {
                            return [{
                                    command: operations.setStyle,
                                    args: [r]
                                }];
                        }
                        isEqual(e.center, r.center) || o.push({
                            command: operations.setCenter,
                            args: [r.center]
                        }), isEqual(e.zoom, r.zoom) || o.push({
                            command: operations.setZoom,
                            args: [r.zoom]
                        }), isEqual(e.bearing, r.bearing) || o.push({
                            command: operations.setBearing,
                            args: [r.bearing]
                        }), isEqual(e.pitch, r.pitch) || o.push({
                            command: operations.setPitch,
                            args: [r.pitch]
                        }), isEqual(e.sprite, r.sprite) || o.push({
                            command: operations.setSprite,
                            args: [r.sprite]
                        }), isEqual(e.glyphs, r.glyphs) || o.push({
                            command: operations.setGlyphs,
                            args: [r.glyphs]
                        }), isEqual(e.transition, r.transition) || o.push({
                            command: operations.setTransition,
                            args: [r.transition]
                        }), isEqual(e.light, r.light) || o.push({
                            command: operations.setLight,
                            args: [r.light]
                        });
                        var a = {}, t = [];
                        diffSources(e.sources, r.sources, t, a);
                        var s = [];
                        e.layers && e.layers.forEach(function (e) {
                            a[e.source] ? o.push({
                                command: operations.removeLayer,
                                args: [e.id]
                            }) : s.push(e);
                        }), o = o.concat(t), diffLayers(s, r.layers, o);
                    } catch (e) {
                        console.warn('Unable to compute style diff:', e), o = [{
                                command: operations.setStyle,
                                args: [r]
                            }];
                    }
                    return o;
                }
                var isEqual = _dereq_('./util/deep_equal'), operations = {
                        setStyle: 'setStyle',
                        addLayer: 'addLayer',
                        removeLayer: 'removeLayer',
                        setPaintProperty: 'setPaintProperty',
                        setLayoutProperty: 'setLayoutProperty',
                        setFilter: 'setFilter',
                        addSource: 'addSource',
                        removeSource: 'removeSource',
                        setGeoJSONSourceData: 'setGeoJSONSourceData',
                        setLayerZoomRange: 'setLayerZoomRange',
                        setLayerProperty: 'setLayerProperty',
                        setCenter: 'setCenter',
                        setZoom: 'setZoom',
                        setBearing: 'setBearing',
                        setPitch: 'setPitch',
                        setSprite: 'setSprite',
                        setGlyphs: 'setGlyphs',
                        setTransition: 'setTransition',
                        setLight: 'setLight'
                    };
                module.exports = diffStyles, module.exports.operations = operations;
            },
            { './util/deep_equal': 155 }
        ],
        122: [
            function (_dereq_, module, exports) {
                'use strict';
                function ValidationError(i, e, l) {
                    this.message = (i ? i + ': ' : '') + l, null !== e && void 0 !== e && e.__line__ && (this.line = e.__line__);
                }
                module.exports = ValidationError;
            },
            {}
        ],
        123: [
            function (_dereq_, module, exports) {
                'use strict';
                function varargs(r) {
                    return { type: r };
                }
                function stringifySignature(r) {
                    return Array.isArray(r) ? '(' + r.map(toString).join(', ') + ')' : '(' + toString(r.type) + '...)';
                }
                var ref = _dereq_('./types'), toString = ref.toString, ParsingContext = _dereq_('./parsing_context'), EvaluationContext = _dereq_('./evaluation_context'), CompoundExpression = function (r, e, n, t) {
                        this.name = r, this.type = e, this._evaluate = n, this.args = t;
                    };
                CompoundExpression.prototype.evaluate = function (r) {
                    return this._evaluate(r, this.args);
                }, CompoundExpression.prototype.eachChild = function (r) {
                    this.args.forEach(r);
                }, CompoundExpression.prototype.possibleOutputs = function () {
                    return [void 0];
                }, CompoundExpression.parse = function (r, e) {
                    var n = r[0], t = CompoundExpression.definitions[n];
                    if (!t) {
                        return e.error('Unknown expression "' + n + '". If you wanted a literal array, use ["literal", [...]].', 0);
                    }
                    for (var o = Array.isArray(t) ? t[0] : t.type, i = Array.isArray(t) ? [[
                                    t[1],
                                    t[2]
                                ]] : t.overloads, s = i.filter(function (e) {
                                var n = e[0];
                                return !Array.isArray(n) || n.length === r.length - 1;
                            }), a = [], u = 1; u < r.length; u++) {
                        var p = r[u], l = void 0;
                        if (1 === s.length) {
                            var g = s[0][0];
                            l = Array.isArray(g) ? g[u - 1] : g.type;
                        }
                        var y = e.parse(p, 1 + a.length, l);
                        if (!y) {
                            return null;
                        }
                        a.push(y);
                    }
                    for (var f = null, h = 0, d = s; h < d.length; h += 1) {
                        var v = d[h], c = v[0], x = v[1];
                        if (f = new ParsingContext(e.registry, e.path, null, e.scope), Array.isArray(c) && c.length !== a.length) {
                            f.error('Expected ' + c.length + ' arguments, but found ' + a.length + ' instead.');
                        } else {
                            for (var m = 0; m < a.length; m++) {
                                var C = Array.isArray(c) ? c[m] : c.type, E = a[m];
                                f.concat(m + 1).checkSubtype(C, E.type);
                            }
                            if (0 === f.errors.length) {
                                return new CompoundExpression(n, o, x, a);
                            }
                        }
                    }
                    if (1 === s.length) {
                        e.errors.push.apply(e.errors, f.errors);
                    } else {
                        var A = s.length ? s : i, S = A.map(function (r) {
                                return stringifySignature(r[0]);
                            }).join(' | '), b = a.map(function (r) {
                                return toString(r.type);
                            }).join(', ');
                        e.error('Expected arguments of type ' + S + ', but found (' + b + ') instead.');
                    }
                    return null;
                }, CompoundExpression.register = function (r, e) {
                    CompoundExpression.definitions = e;
                    for (var n in e) {
                        r[n] = CompoundExpression;
                    }
                }, module.exports = {
                    CompoundExpression: CompoundExpression,
                    varargs: varargs
                };
            },
            {
                './evaluation_context': 138,
                './parsing_context': 141,
                './types': 146
            }
        ],
        124: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), toString = ref.toString, array = ref.array, ValueType = ref.ValueType, StringType = ref.StringType, NumberType = ref.NumberType, BooleanType = ref.BooleanType, checkSubtype = ref.checkSubtype, ref$1 = _dereq_('../values'), typeOf = ref$1.typeOf, RuntimeError = _dereq_('../runtime_error'), types = {
                        string: StringType,
                        number: NumberType,
                        boolean: BooleanType
                    }, ArrayAssertion = function (e, r) {
                        this.type = e, this.input = r;
                    };
                ArrayAssertion.parse = function (e, r) {
                    if (e.length < 2 || e.length > 4) {
                        return r.error('Expected 1, 2, or 3 arguments, but found ' + (e.length - 1) + ' instead.');
                    }
                    var t, n;
                    if (e.length > 2) {
                        var i = e[1];
                        if ('string' != typeof i || !(i in types)) {
                            return r.error('The item type argument of "array" must be one of string, number, boolean', 1);
                        }
                        t = types[i];
                    } else {
                        t = ValueType;
                    }
                    if (e.length > 3) {
                        if ('number' != typeof e[2] || e[2] < 0 || e[2] !== Math.floor(e[2])) {
                            return r.error('The length argument to "array" must be a positive integer literal', 2);
                        }
                        n = e[2];
                    }
                    var o = array(t, n), u = r.parse(e[e.length - 1], e.length - 1, ValueType);
                    return u ? new ArrayAssertion(o, u) : null;
                }, ArrayAssertion.prototype.evaluate = function (e) {
                    var r = this.input.evaluate(e);
                    if (checkSubtype(this.type, typeOf(r))) {
                        throw new RuntimeError('Expected value to be of type ' + toString(this.type) + ', but found ' + toString(typeOf(r)) + ' instead.');
                    }
                    return r;
                }, ArrayAssertion.prototype.eachChild = function (e) {
                    e(this.input);
                }, ArrayAssertion.prototype.possibleOutputs = function () {
                    return this.input.possibleOutputs();
                }, module.exports = ArrayAssertion;
            },
            {
                '../runtime_error': 143,
                '../types': 146,
                '../values': 147
            }
        ],
        125: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), ObjectType = ref.ObjectType, ValueType = ref.ValueType, StringType = ref.StringType, NumberType = ref.NumberType, BooleanType = ref.BooleanType, RuntimeError = _dereq_('../runtime_error'), ref$1 = _dereq_('../types'), checkSubtype = ref$1.checkSubtype, toString = ref$1.toString, ref$2 = _dereq_('../values'), typeOf = ref$2.typeOf, types = {
                        string: StringType,
                        number: NumberType,
                        boolean: BooleanType,
                        object: ObjectType
                    }, Assertion = function (e, r) {
                        this.type = e, this.args = r;
                    };
                Assertion.parse = function (e, r) {
                    if (e.length < 2) {
                        return r.error('Expected at least one argument.');
                    }
                    for (var t = e[0], n = types[t], o = [], p = 1; p < e.length; p++) {
                        var s = r.parse(e[p], p, ValueType);
                        if (!s) {
                            return null;
                        }
                        o.push(s);
                    }
                    return new Assertion(n, o);
                }, Assertion.prototype.evaluate = function (e) {
                    for (var r = this, t = 0; t < this.args.length; t++) {
                        var n = r.args[t].evaluate(e);
                        if (!checkSubtype(r.type, typeOf(n))) {
                            return n;
                        }
                        if (t === r.args.length - 1) {
                            throw new RuntimeError('Expected value to be of type ' + toString(r.type) + ', but found ' + toString(typeOf(n)) + ' instead.');
                        }
                    }
                    return null;
                }, Assertion.prototype.eachChild = function (e) {
                    this.args.forEach(e);
                }, Assertion.prototype.possibleOutputs = function () {
                    return (e = []).concat.apply(e, this.args.map(function (e) {
                        return e.possibleOutputs();
                    }));
                    var e;
                }, module.exports = Assertion;
            },
            {
                '../runtime_error': 143,
                '../types': 146,
                '../values': 147
            }
        ],
        126: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), array = ref.array, ValueType = ref.ValueType, NumberType = ref.NumberType, RuntimeError = _dereq_('../runtime_error'), At = function (e, t, r) {
                        this.type = e, this.index = t, this.input = r;
                    };
                At.parse = function (e, t) {
                    if (3 !== e.length) {
                        return t.error('Expected 2 arguments, but found ' + (e.length - 1) + ' instead.');
                    }
                    var r = t.parse(e[1], 1, NumberType), n = t.parse(e[2], 2, array(t.expectedType || ValueType));
                    if (!r || !n) {
                        return null;
                    }
                    var u = n.type;
                    return new At(u.itemType, r, n);
                }, At.prototype.evaluate = function (e) {
                    var t = this.index.evaluate(e), r = this.input.evaluate(e);
                    if (t < 0 || t >= r.length) {
                        throw new RuntimeError('Array index out of bounds: ' + t + ' > ' + r.length + '.');
                    }
                    if (t !== Math.floor(t)) {
                        throw new RuntimeError('Array index must be an integer, but found ' + t + ' instead.');
                    }
                    return r[t];
                }, At.prototype.eachChild = function (e) {
                    e(this.index), e(this.input);
                }, At.prototype.possibleOutputs = function () {
                    return [void 0];
                }, module.exports = At;
            },
            {
                '../runtime_error': 143,
                '../types': 146
            }
        ],
        127: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), BooleanType = ref.BooleanType, Case = function (e, t, r) {
                        this.type = e, this.branches = t, this.otherwise = r;
                    };
                Case.parse = function (e, t) {
                    if (e.length < 4) {
                        return t.error('Expected at least 3 arguments, but found only ' + (e.length - 1) + '.');
                    }
                    if (e.length % 2 != 0) {
                        return t.error('Expected an odd number of arguments.');
                    }
                    var r;
                    t.expectedType && 'value' !== t.expectedType.kind && (r = t.expectedType);
                    for (var n = [], a = 1; a < e.length - 1; a += 2) {
                        var s = t.parse(e[a], a, BooleanType);
                        if (!s) {
                            return null;
                        }
                        var o = t.parse(e[a + 1], a + 1, r);
                        if (!o) {
                            return null;
                        }
                        n.push([
                            s,
                            o
                        ]), r = r || o.type;
                    }
                    var u = t.parse(e[e.length - 1], e.length - 1, r);
                    return u ? new Case(r, n, u) : null;
                }, Case.prototype.evaluate = function (e) {
                    for (var t = this, r = 0, n = t.branches; r < n.length; r += 1) {
                        var a = n[r], s = a[0], o = a[1];
                        if (s.evaluate(e)) {
                            return o.evaluate(e);
                        }
                    }
                    return this.otherwise.evaluate(e);
                }, Case.prototype.eachChild = function (e) {
                    for (var t = this, r = 0, n = t.branches; r < n.length; r += 1) {
                        var a = n[r], s = a[0], o = a[1];
                        e(s), e(o);
                    }
                    e(this.otherwise);
                }, Case.prototype.possibleOutputs = function () {
                    return (e = []).concat.apply(e, this.branches.map(function (e) {
                        e[0];
                        return e[1].possibleOutputs();
                    })).concat(this.otherwise.possibleOutputs());
                    var e;
                }, module.exports = Case;
            },
            { '../types': 146 }
        ],
        128: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), checkSubtype = ref.checkSubtype, ValueType = ref.ValueType, Coalesce = function (e, t) {
                        this.type = e, this.args = t;
                    };
                Coalesce.parse = function (e, t) {
                    if (e.length < 2) {
                        return t.error('Expectected at least one argument.');
                    }
                    var r = null, a = t.expectedType;
                    a && 'value' !== a.kind && (r = a);
                    for (var n = [], o = 0, u = e.slice(1); o < u.length; o += 1) {
                        var s = u[o], l = t.parse(s, 1 + n.length, r, void 0, { omitTypeAnnotations: !0 });
                        if (!l) {
                            return null;
                        }
                        r = r || l.type, n.push(l);
                    }
                    return a && n.some(function (e) {
                        return checkSubtype(a, e.type);
                    }) ? new Coalesce(ValueType, n) : new Coalesce(r, n);
                }, Coalesce.prototype.evaluate = function (e) {
                    for (var t = this, r = null, a = 0, n = t.args; a < n.length; a += 1) {
                        if (null !== (r = n[a].evaluate(e))) {
                            break;
                        }
                    }
                    return r;
                }, Coalesce.prototype.eachChild = function (e) {
                    this.args.forEach(e);
                }, Coalesce.prototype.possibleOutputs = function () {
                    return (e = []).concat.apply(e, this.args.map(function (e) {
                        return e.possibleOutputs();
                    }));
                    var e;
                }, module.exports = Coalesce;
            },
            { '../types': 146 }
        ],
        129: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), ColorType = ref.ColorType, ValueType = ref.ValueType, NumberType = ref.NumberType, ref$1 = _dereq_('../values'), Color = ref$1.Color, validateRGBA = ref$1.validateRGBA, RuntimeError = _dereq_('../runtime_error'), types = {
                        'to-number': NumberType,
                        'to-color': ColorType
                    }, Coercion = function (r, e) {
                        this.type = r, this.args = e;
                    };
                Coercion.parse = function (r, e) {
                    if (r.length < 2) {
                        return e.error('Expected at least one argument.');
                    }
                    for (var t = r[0], o = types[t], n = [], i = 1; i < r.length; i++) {
                        var a = e.parse(r[i], i, ValueType);
                        if (!a) {
                            return null;
                        }
                        n.push(a);
                    }
                    return new Coercion(o, n);
                }, Coercion.prototype.evaluate = function (r) {
                    var e = this;
                    if ('color' === this.type.kind) {
                        for (var t, o, n = 0, i = e.args; n < i.length; n += 1) {
                            if (t = i[n].evaluate(r), o = null, 'string' == typeof t) {
                                var a = r.parseColor(t);
                                if (a) {
                                    return a;
                                }
                            } else if (Array.isArray(t) && !(o = t.length < 3 || t.length > 4 ? 'Invalid rbga value ' + JSON.stringify(t) + ': expected an array containing either three or four numeric values.' : validateRGBA(t[0], t[1], t[2], t[3]))) {
                                return new Color(t[0] / 255, t[1] / 255, t[2] / 255, t[3]);
                            }
                        }
                        throw new RuntimeError(o || 'Could not parse color from value \'' + ('string' == typeof t ? t : JSON.stringify(t)) + '\'');
                    }
                    for (var u = null, l = 0, s = e.args; l < s.length; l += 1) {
                        if (null !== (u = s[l].evaluate(r))) {
                            var p = Number(u);
                            if (!isNaN(p)) {
                                return p;
                            }
                        }
                    }
                    throw new RuntimeError('Could not convert ' + JSON.stringify(u) + ' to number.');
                }, Coercion.prototype.eachChild = function (r) {
                    this.args.forEach(r);
                }, Coercion.prototype.possibleOutputs = function () {
                    return (r = []).concat.apply(r, this.args.map(function (r) {
                        return r.possibleOutputs();
                    }));
                    var r;
                }, module.exports = Coercion;
            },
            {
                '../runtime_error': 143,
                '../types': 146,
                '../values': 147
            }
        ],
        130: [
            function (_dereq_, module, exports) {
                'use strict';
                function isComparableType(e) {
                    return 'string' === e.kind || 'number' === e.kind || 'boolean' === e.kind || 'null' === e.kind;
                }
                function makeComparison(e) {
                    return function () {
                        function t(e, t) {
                            this.type = BooleanType, this.lhs = e, this.rhs = t;
                        }
                        return t.parse = function (e, r) {
                            if (3 !== e.length) {
                                return r.error('Expected two arguments.');
                            }
                            var n = r.parse(e[1], 1, ValueType);
                            if (!n) {
                                return null;
                            }
                            var o = r.parse(e[2], 2, ValueType);
                            return o ? isComparableType(n.type) || isComparableType(o.type) ? n.type.kind !== o.type.kind && 'value' !== n.type.kind && 'value' !== o.type.kind ? r.error('Cannot compare ' + toString(n.type) + ' and ' + toString(o.type) + '.') : new t(n, o) : r.error('Expected at least one argument to be a string, number, boolean, or null, but found (' + toString(n.type) + ', ' + toString(o.type) + ') instead.') : null;
                        }, t.prototype.evaluate = function (t) {
                            return e(this.lhs.evaluate(t), this.rhs.evaluate(t));
                        }, t.prototype.eachChild = function (e) {
                            e(this.lhs), e(this.rhs);
                        }, t.prototype.possibleOutputs = function () {
                            return [
                                !0,
                                !1
                            ];
                        }, t;
                    }();
                }
                var ref = _dereq_('../types'), ValueType = ref.ValueType, BooleanType = ref.BooleanType, ref$1 = _dereq_('../types'), toString = ref$1.toString;
                module.exports = {
                    Equals: makeComparison(function (e, t) {
                        return e === t;
                    }),
                    NotEquals: makeComparison(function (e, t) {
                        return e !== t;
                    })
                };
            },
            { '../types': 146 }
        ],
        131: [
            function (_dereq_, module, exports) {
                'use strict';
                function rgba(e, r) {
                    var t = r[0], a = r[1], n = r[2], u = r[3];
                    t = t.evaluate(e), a = a.evaluate(e), n = n.evaluate(e);
                    var o = u ? u.evaluate(e) : 1, p = validateRGBA(t, a, n, o);
                    if (p) {
                        throw new RuntimeError(p);
                    }
                    return new Color(t / 255 * o, a / 255 * o, n / 255 * o, o);
                }
                function has(e, r) {
                    return e in r;
                }
                function get(e, r) {
                    var t = r[e];
                    return void 0 === t ? null : t;
                }
                function length(e, r) {
                    return r[0].evaluate(e).length;
                }
                function lt(e, r) {
                    var t = r[0], a = r[1];
                    return t.evaluate(e) < a.evaluate(e);
                }
                function gt(e, r) {
                    var t = r[0], a = r[1];
                    return t.evaluate(e) > a.evaluate(e);
                }
                function lteq(e, r) {
                    var t = r[0], a = r[1];
                    return t.evaluate(e) <= a.evaluate(e);
                }
                function gteq(e, r) {
                    var t = r[0], a = r[1];
                    return t.evaluate(e) >= a.evaluate(e);
                }
                function binarySearch(e, r, t, a) {
                    for (; t <= a;) {
                        var n = t + a >> 1;
                        if (r[n] === e) {
                            return !0;
                        }
                        r[n] > e ? a = n - 1 : t = n + 1;
                    }
                    return !1;
                }
                var ref = _dereq_('../types'), NumberType = ref.NumberType, StringType = ref.StringType, BooleanType = ref.BooleanType, ColorType = ref.ColorType, ObjectType = ref.ObjectType, ValueType = ref.ValueType, ErrorType = ref.ErrorType, array = ref.array, toString = ref.toString, ref$1 = _dereq_('../values'), typeOf = ref$1.typeOf, Color = ref$1.Color, validateRGBA = ref$1.validateRGBA, ref$2 = _dereq_('../compound_expression'), CompoundExpression = ref$2.CompoundExpression, varargs = ref$2.varargs, RuntimeError = _dereq_('../runtime_error'), Let = _dereq_('./let'), Var = _dereq_('./var'), Literal = _dereq_('./literal'), Assertion = _dereq_('./assertion'), ArrayAssertion = _dereq_('./array'), Coercion = _dereq_('./coercion'), At = _dereq_('./at'), Match = _dereq_('./match'), Case = _dereq_('./case'), Step = _dereq_('./step'), Interpolate = _dereq_('./interpolate'), Coalesce = _dereq_('./coalesce'), ref$3 = _dereq_('./equals'), Equals = ref$3.Equals, NotEquals = ref$3.NotEquals, expressions = {
                        '==': Equals,
                        '!=': NotEquals,
                        array: ArrayAssertion,
                        at: At,
                        boolean: Assertion,
                        case: Case,
                        coalesce: Coalesce,
                        interpolate: Interpolate,
                        let: Let,
                        literal: Literal,
                        match: Match,
                        number: Assertion,
                        object: Assertion,
                        step: Step,
                        string: Assertion,
                        'to-color': Coercion,
                        'to-number': Coercion,
                        var: Var
                    };
                CompoundExpression.register(expressions, {
                    error: [
                        ErrorType,
                        [StringType],
                        function (e, r) {
                            var t = r[0];
                            throw new RuntimeError(t.evaluate(e));
                        }
                    ],
                    typeof: [
                        StringType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0];
                            return toString(typeOf(t.evaluate(e)));
                        }
                    ],
                    'to-string': [
                        StringType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0];
                            t = t.evaluate(e);
                            var a = typeof t;
                            return null === t || 'string' === a || 'number' === a || 'boolean' === a ? String(t) : t instanceof Color ? t.toString() : JSON.stringify(t);
                        }
                    ],
                    'to-boolean': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0];
                            return Boolean(t.evaluate(e));
                        }
                    ],
                    'to-rgba': [
                        array(NumberType, 4),
                        [ColorType],
                        function (e, r) {
                            var t = r[0], a = t.evaluate(e), n = a.r, u = a.g, o = a.b, p = a.a;
                            return [
                                255 * n / p,
                                255 * u / p,
                                255 * o / p,
                                p
                            ];
                        }
                    ],
                    rgb: [
                        ColorType,
                        [
                            NumberType,
                            NumberType,
                            NumberType
                        ],
                        rgba
                    ],
                    rgba: [
                        ColorType,
                        [
                            NumberType,
                            NumberType,
                            NumberType,
                            NumberType
                        ],
                        rgba
                    ],
                    length: {
                        type: NumberType,
                        overloads: [
                            [
                                [StringType],
                                length
                            ],
                            [
                                [array(ValueType)],
                                length
                            ]
                        ]
                    },
                    has: {
                        type: BooleanType,
                        overloads: [
                            [
                                [StringType],
                                function (e, r) {
                                    return has(r[0].evaluate(e), e.properties());
                                }
                            ],
                            [
                                [
                                    StringType,
                                    ObjectType
                                ],
                                function (e, r) {
                                    var t = r[0], a = r[1];
                                    return has(t.evaluate(e), a.evaluate(e));
                                }
                            ]
                        ]
                    },
                    get: {
                        type: ValueType,
                        overloads: [
                            [
                                [StringType],
                                function (e, r) {
                                    return get(r[0].evaluate(e), e.properties());
                                }
                            ],
                            [
                                [
                                    StringType,
                                    ObjectType
                                ],
                                function (e, r) {
                                    var t = r[0], a = r[1];
                                    return get(t.evaluate(e), a.evaluate(e));
                                }
                            ]
                        ]
                    },
                    properties: [
                        ObjectType,
                        [],
                        function (e) {
                            return e.properties();
                        }
                    ],
                    'geometry-type': [
                        StringType,
                        [],
                        function (e) {
                            return e.geometryType();
                        }
                    ],
                    id: [
                        ValueType,
                        [],
                        function (e) {
                            return e.id();
                        }
                    ],
                    zoom: [
                        NumberType,
                        [],
                        function (e) {
                            return e.globals.zoom;
                        }
                    ],
                    'heatmap-density': [
                        NumberType,
                        [],
                        function (e) {
                            return e.globals.heatmapDensity || 0;
                        }
                    ],
                    '+': [
                        NumberType,
                        varargs(NumberType),
                        function (e, r) {
                            for (var t = 0, a = 0, n = r; a < n.length; a += 1) {
                                t += n[a].evaluate(e);
                            }
                            return t;
                        }
                    ],
                    '*': [
                        NumberType,
                        varargs(NumberType),
                        function (e, r) {
                            for (var t = 1, a = 0, n = r; a < n.length; a += 1) {
                                t *= n[a].evaluate(e);
                            }
                            return t;
                        }
                    ],
                    '-': {
                        type: NumberType,
                        overloads: [
                            [
                                [
                                    NumberType,
                                    NumberType
                                ],
                                function (e, r) {
                                    var t = r[0], a = r[1];
                                    return t.evaluate(e) - a.evaluate(e);
                                }
                            ],
                            [
                                [NumberType],
                                function (e, r) {
                                    return -r[0].evaluate(e);
                                }
                            ]
                        ]
                    },
                    '/': [
                        NumberType,
                        [
                            NumberType,
                            NumberType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1];
                            return t.evaluate(e) / a.evaluate(e);
                        }
                    ],
                    '%': [
                        NumberType,
                        [
                            NumberType,
                            NumberType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1];
                            return t.evaluate(e) % a.evaluate(e);
                        }
                    ],
                    ln2: [
                        NumberType,
                        [],
                        function () {
                            return Math.LN2;
                        }
                    ],
                    pi: [
                        NumberType,
                        [],
                        function () {
                            return Math.PI;
                        }
                    ],
                    e: [
                        NumberType,
                        [],
                        function () {
                            return Math.E;
                        }
                    ],
                    '^': [
                        NumberType,
                        [
                            NumberType,
                            NumberType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1];
                            return Math.pow(t.evaluate(e), a.evaluate(e));
                        }
                    ],
                    sqrt: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.sqrt(t.evaluate(e));
                        }
                    ],
                    log10: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.log10(t.evaluate(e));
                        }
                    ],
                    ln: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.log(t.evaluate(e));
                        }
                    ],
                    log2: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.log2(t.evaluate(e));
                        }
                    ],
                    sin: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.sin(t.evaluate(e));
                        }
                    ],
                    cos: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.cos(t.evaluate(e));
                        }
                    ],
                    tan: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.tan(t.evaluate(e));
                        }
                    ],
                    asin: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.asin(t.evaluate(e));
                        }
                    ],
                    acos: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.acos(t.evaluate(e));
                        }
                    ],
                    atan: [
                        NumberType,
                        [NumberType],
                        function (e, r) {
                            var t = r[0];
                            return Math.atan(t.evaluate(e));
                        }
                    ],
                    min: [
                        NumberType,
                        varargs(NumberType),
                        function (e, r) {
                            return Math.min.apply(Math, r.map(function (r) {
                                return r.evaluate(e);
                            }));
                        }
                    ],
                    max: [
                        NumberType,
                        varargs(NumberType),
                        function (e, r) {
                            return Math.max.apply(Math, r.map(function (r) {
                                return r.evaluate(e);
                            }));
                        }
                    ],
                    'filter-==': [
                        BooleanType,
                        [
                            StringType,
                            ValueType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1];
                            return e.properties()[t.value] === a.value;
                        }
                    ],
                    'filter-id-==': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0];
                            return e.id() === t.value;
                        }
                    ],
                    'filter-type-==': [
                        BooleanType,
                        [StringType],
                        function (e, r) {
                            var t = r[0];
                            return e.geometryType() === t.value;
                        }
                    ],
                    'filter-<': [
                        BooleanType,
                        [
                            StringType,
                            ValueType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1], n = e.properties()[t.value], u = a.value;
                            return typeof n == typeof u && n < u;
                        }
                    ],
                    'filter-id-<': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0], a = e.id(), n = t.value;
                            return typeof a == typeof n && a < n;
                        }
                    ],
                    'filter->': [
                        BooleanType,
                        [
                            StringType,
                            ValueType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1], n = e.properties()[t.value], u = a.value;
                            return typeof n == typeof u && n > u;
                        }
                    ],
                    'filter-id->': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0], a = e.id(), n = t.value;
                            return typeof a == typeof n && a > n;
                        }
                    ],
                    'filter-<=': [
                        BooleanType,
                        [
                            StringType,
                            ValueType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1], n = e.properties()[t.value], u = a.value;
                            return typeof n == typeof u && n <= u;
                        }
                    ],
                    'filter-id-<=': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0], a = e.id(), n = t.value;
                            return typeof a == typeof n && a <= n;
                        }
                    ],
                    'filter->=': [
                        BooleanType,
                        [
                            StringType,
                            ValueType
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1], n = e.properties()[t.value], u = a.value;
                            return typeof n == typeof u && n >= u;
                        }
                    ],
                    'filter-id->=': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            var t = r[0], a = e.id(), n = t.value;
                            return typeof a == typeof n && a >= n;
                        }
                    ],
                    'filter-has': [
                        BooleanType,
                        [ValueType],
                        function (e, r) {
                            return r[0].value in e.properties();
                        }
                    ],
                    'filter-has-id': [
                        BooleanType,
                        [],
                        function (e) {
                            return null !== e.id();
                        }
                    ],
                    'filter-type-in': [
                        BooleanType,
                        [array(StringType)],
                        function (e, r) {
                            return r[0].value.indexOf(e.geometryType()) >= 0;
                        }
                    ],
                    'filter-id-in': [
                        BooleanType,
                        [array(ValueType)],
                        function (e, r) {
                            return r[0].value.indexOf(e.id()) >= 0;
                        }
                    ],
                    'filter-in-small': [
                        BooleanType,
                        [
                            StringType,
                            array(ValueType)
                        ],
                        function (e, r) {
                            var t = r[0];
                            return r[1].value.indexOf(e.properties()[t.value]) >= 0;
                        }
                    ],
                    'filter-in-large': [
                        BooleanType,
                        [
                            StringType,
                            array(ValueType)
                        ],
                        function (e, r) {
                            var t = r[0], a = r[1];
                            return binarySearch(e.properties()[t.value], a.value, 0, a.value.length - 1);
                        }
                    ],
                    '>': {
                        type: BooleanType,
                        overloads: [
                            [
                                [
                                    NumberType,
                                    NumberType
                                ],
                                gt
                            ],
                            [
                                [
                                    StringType,
                                    StringType
                                ],
                                gt
                            ]
                        ]
                    },
                    '<': {
                        type: BooleanType,
                        overloads: [
                            [
                                [
                                    NumberType,
                                    NumberType
                                ],
                                lt
                            ],
                            [
                                [
                                    StringType,
                                    StringType
                                ],
                                lt
                            ]
                        ]
                    },
                    '>=': {
                        type: BooleanType,
                        overloads: [
                            [
                                [
                                    NumberType,
                                    NumberType
                                ],
                                gteq
                            ],
                            [
                                [
                                    StringType,
                                    StringType
                                ],
                                gteq
                            ]
                        ]
                    },
                    '<=': {
                        type: BooleanType,
                        overloads: [
                            [
                                [
                                    NumberType,
                                    NumberType
                                ],
                                lteq
                            ],
                            [
                                [
                                    StringType,
                                    StringType
                                ],
                                lteq
                            ]
                        ]
                    },
                    all: {
                        type: BooleanType,
                        overloads: [
                            [
                                [
                                    BooleanType,
                                    BooleanType
                                ],
                                function (e, r) {
                                    var t = r[0], a = r[1];
                                    return t.evaluate(e) && a.evaluate(e);
                                }
                            ],
                            [
                                varargs(BooleanType),
                                function (e, r) {
                                    for (var t = 0, a = r; t < a.length; t += 1) {
                                        if (!a[t].evaluate(e)) {
                                            return !1;
                                        }
                                    }
                                    return !0;
                                }
                            ]
                        ]
                    },
                    any: {
                        type: BooleanType,
                        overloads: [
                            [
                                [
                                    BooleanType,
                                    BooleanType
                                ],
                                function (e, r) {
                                    var t = r[0], a = r[1];
                                    return t.evaluate(e) || a.evaluate(e);
                                }
                            ],
                            [
                                varargs(BooleanType),
                                function (e, r) {
                                    for (var t = 0, a = r; t < a.length; t += 1) {
                                        if (a[t].evaluate(e)) {
                                            return !0;
                                        }
                                    }
                                    return !1;
                                }
                            ]
                        ]
                    },
                    '!': [
                        BooleanType,
                        [BooleanType],
                        function (e, r) {
                            return !r[0].evaluate(e);
                        }
                    ],
                    upcase: [
                        StringType,
                        [StringType],
                        function (e, r) {
                            return r[0].evaluate(e).toUpperCase();
                        }
                    ],
                    downcase: [
                        StringType,
                        [StringType],
                        function (e, r) {
                            return r[0].evaluate(e).toLowerCase();
                        }
                    ],
                    concat: [
                        StringType,
                        varargs(StringType),
                        function (e, r) {
                            return r.map(function (r) {
                                return r.evaluate(e);
                            }).join('');
                        }
                    ]
                }), module.exports = expressions;
            },
            {
                '../compound_expression': 123,
                '../runtime_error': 143,
                '../types': 146,
                '../values': 147,
                './array': 124,
                './assertion': 125,
                './at': 126,
                './case': 127,
                './coalesce': 128,
                './coercion': 129,
                './equals': 130,
                './interpolate': 132,
                './let': 133,
                './literal': 134,
                './match': 135,
                './step': 136,
                './var': 137
            }
        ],
        132: [
            function (_dereq_, module, exports) {
                'use strict';
                function exponentialInterpolation(e, t, r, n) {
                    var i = n - r, o = e - r;
                    return 0 === i ? 0 : 1 === t ? o / i : (Math.pow(t, o) - 1) / (Math.pow(t, i) - 1);
                }
                var UnitBezier = _dereq_('@mapbox/unitbezier'), interpolate = _dereq_('../../util/interpolate'), ref = _dereq_('../types'), toString = ref.toString, NumberType = ref.NumberType, ref$1 = _dereq_('../stops'), findStopLessThanOrEqualTo = ref$1.findStopLessThanOrEqualTo, Interpolate = function (e, t, r, n) {
                        var i = this;
                        this.type = e, this.interpolation = t, this.input = r, this.labels = [], this.outputs = [];
                        for (var o = 0, a = n; o < a.length; o += 1) {
                            var u = a[o], p = u[0], l = u[1];
                            i.labels.push(p), i.outputs.push(l);
                        }
                    };
                Interpolate.interpolationFactor = function (e, t, r, n) {
                    var i = 0;
                    if ('exponential' === e.name) {
                        i = exponentialInterpolation(t, e.base, r, n);
                    } else if ('linear' === e.name) {
                        i = exponentialInterpolation(t, 1, r, n);
                    } else if ('cubic-bezier' === e.name) {
                        var o = e.controlPoints, a = new UnitBezier(o[0], o[1], o[2], o[3]);
                        i = a.solve(exponentialInterpolation(t, 1, r, n));
                    }
                    return i;
                }, Interpolate.parse = function (e, t) {
                    var r = e[1], n = e[2], i = e.slice(3);
                    if (!Array.isArray(r) || 0 === r.length) {
                        return t.error('Expected an interpolation type expression.', 1);
                    }
                    if ('linear' === r[0]) {
                        r = { name: 'linear' };
                    } else if ('exponential' === r[0]) {
                        var o = r[1];
                        if ('number' != typeof o) {
                            return t.error('Exponential interpolation requires a numeric base.', 1, 1);
                        }
                        r = {
                            name: 'exponential',
                            base: o
                        };
                    } else {
                        if ('cubic-bezier' !== r[0]) {
                            return t.error('Unknown interpolation type ' + String(r[0]), 1, 0);
                        }
                        var a = r.slice(1);
                        if (4 !== a.length || a.some(function (e) {
                                return 'number' != typeof e || e < 0 || e > 1;
                            })) {
                            return t.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);
                        }
                        r = {
                            name: 'cubic-bezier',
                            controlPoints: a
                        };
                    }
                    if (e.length - 1 < 4) {
                        return t.error('Expected at least 4 arguments, but found only ' + (e.length - 1) + '.');
                    }
                    if ((e.length - 1) % 2 != 0) {
                        return t.error('Expected an even number of arguments.');
                    }
                    if (!(n = t.parse(n, 2, NumberType))) {
                        return null;
                    }
                    var u = [], p = null;
                    t.expectedType && 'value' !== t.expectedType.kind && (p = t.expectedType);
                    for (var l = 0; l < i.length; l += 2) {
                        var s = i[l], f = i[l + 1], c = l + 3, h = l + 4;
                        if ('number' != typeof s) {
                            return t.error('Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values.', c);
                        }
                        if (u.length && u[u.length - 1][0] >= s) {
                            return t.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.', c);
                        }
                        var v = t.parse(f, h, p);
                        if (!v) {
                            return null;
                        }
                        p = p || v.type, u.push([
                            s,
                            v
                        ]);
                    }
                    return 'number' === p.kind || 'color' === p.kind || 'array' === p.kind && 'number' === p.itemType.kind && 'number' == typeof p.N ? new Interpolate(p, r, n, u) : t.error('Type ' + toString(p) + ' is not interpolatable.');
                }, Interpolate.prototype.evaluate = function (e) {
                    var t = this.labels, r = this.outputs;
                    if (1 === t.length) {
                        return r[0].evaluate(e);
                    }
                    var n = this.input.evaluate(e);
                    if (n <= t[0]) {
                        return r[0].evaluate(e);
                    }
                    var i = t.length;
                    if (n >= t[i - 1]) {
                        return r[i - 1].evaluate(e);
                    }
                    var o = findStopLessThanOrEqualTo(t, n), a = t[o], u = t[o + 1], p = Interpolate.interpolationFactor(this.interpolation, n, a, u), l = r[o].evaluate(e), s = r[o + 1].evaluate(e);
                    return interpolate[this.type.kind.toLowerCase()](l, s, p);
                }, Interpolate.prototype.eachChild = function (e) {
                    var t = this;
                    e(this.input);
                    for (var r = 0, n = t.outputs; r < n.length; r += 1) {
                        e(n[r]);
                    }
                }, Interpolate.prototype.possibleOutputs = function () {
                    return (e = []).concat.apply(e, this.outputs.map(function (e) {
                        return e.possibleOutputs();
                    }));
                    var e;
                }, module.exports = Interpolate;
            },
            {
                '../../util/interpolate': 158,
                '../stops': 145,
                '../types': 146,
                '@mapbox/unitbezier': 7
            }
        ],
        133: [
            function (_dereq_, module, exports) {
                'use strict';
                var Let = function (t, e) {
                    this.type = e.type, this.bindings = [].concat(t), this.result = e;
                };
                Let.prototype.evaluate = function (t) {
                    t.pushScope(this.bindings);
                    var e = this.result.evaluate(t);
                    return t.popScope(), e;
                }, Let.prototype.eachChild = function (t) {
                    for (var e = this, r = 0, n = e.bindings; r < n.length; r += 1) {
                        t(n[r][1]);
                    }
                    t(this.result);
                }, Let.parse = function (t, e) {
                    if (t.length < 4) {
                        return e.error('Expected at least 3 arguments, but found ' + (t.length - 1) + ' instead.');
                    }
                    for (var r = [], n = 1; n < t.length - 1; n += 2) {
                        var s = t[n];
                        if ('string' != typeof s) {
                            return e.error('Expected string, but found ' + typeof s + ' instead.', n);
                        }
                        if (/[^a-zA-Z0-9_]/.test(s)) {
                            return e.error('Variable names must contain only alphanumeric characters or \'_\'.', n);
                        }
                        var i = e.parse(t[n + 1], n + 1);
                        if (!i) {
                            return null;
                        }
                        r.push([
                            s,
                            i
                        ]);
                    }
                    var u = e.parse(t[t.length - 1], t.length - 1, void 0, r);
                    return u ? new Let(r, u) : null;
                }, Let.prototype.possibleOutputs = function () {
                    return this.result.possibleOutputs();
                }, module.exports = Let;
            },
            {}
        ],
        134: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../values'), isValue = ref.isValue, typeOf = ref.typeOf, Literal = function (e, r) {
                        this.type = e, this.value = r;
                    };
                Literal.parse = function (e, r) {
                    if (2 !== e.length) {
                        return r.error('\'literal\' expression requires exactly one argument, but found ' + (e.length - 1) + ' instead.');
                    }
                    if (!isValue(e[1])) {
                        return r.error('invalid value');
                    }
                    var t = e[1], i = typeOf(t), a = r.expectedType;
                    return 'array' !== i.kind || 0 !== i.N || !a || 'array' !== a.kind || 'number' == typeof a.N && 0 !== a.N || (i = a), new Literal(i, t);
                }, Literal.prototype.evaluate = function () {
                    return this.value;
                }, Literal.prototype.eachChild = function () {
                }, Literal.prototype.possibleOutputs = function () {
                    return [this.value];
                }, module.exports = Literal;
            },
            { '../values': 147 }
        ],
        135: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../values'), typeOf = ref.typeOf, Match = function (e, t, r, n, u, s) {
                        this.inputType = e, this.type = t, this.input = r, this.cases = n, this.outputs = u, this.otherwise = s;
                    };
                Match.parse = function (e, t) {
                    if (e.length < 5) {
                        return t.error('Expected at least 4 arguments, but found only ' + (e.length - 1) + '.');
                    }
                    if (e.length % 2 != 1) {
                        return t.error('Expected an even number of arguments.');
                    }
                    var r, n;
                    t.expectedType && 'value' !== t.expectedType.kind && (n = t.expectedType);
                    for (var u = {}, s = [], a = 2; a < e.length - 1; a += 2) {
                        var i = e[a], o = e[a + 1];
                        Array.isArray(i) || (i = [i]);
                        var p = t.concat(a);
                        if (0 === i.length) {
                            return p.error('Expected at least one branch label.');
                        }
                        for (var h = 0, l = i; h < l.length; h += 1) {
                            var c = l[h];
                            if ('number' != typeof c && 'string' != typeof c) {
                                return p.error('Branch labels must be numbers or strings.');
                            }
                            if ('number' == typeof c && Math.abs(c) > Number.MAX_SAFE_INTEGER) {
                                return p.error('Branch labels must be integers no larger than ' + Number.MAX_SAFE_INTEGER + '.');
                            }
                            if ('number' == typeof c && Math.floor(c) !== c) {
                                return p.error('Numeric branch labels must be integer values.');
                            }
                            if (r) {
                                if (p.checkSubtype(r, typeOf(c))) {
                                    return null;
                                }
                            } else {
                                r = typeOf(c);
                            }
                            if (void 0 !== u[String(c)]) {
                                return p.error('Branch labels must be unique.');
                            }
                            u[String(c)] = s.length;
                        }
                        var f = t.parse(o, a, n);
                        if (!f) {
                            return null;
                        }
                        n = n || f.type, s.push(f);
                    }
                    var b = t.parse(e[1], 1, r);
                    if (!b) {
                        return null;
                    }
                    var y = t.parse(e[e.length - 1], e.length - 1, n);
                    return y ? new Match(r, n, b, u, s, y) : null;
                }, Match.prototype.evaluate = function (e) {
                    var t = this.input.evaluate(e);
                    return (this.outputs[this.cases[t]] || this.otherwise).evaluate(e);
                }, Match.prototype.eachChild = function (e) {
                    e(this.input), this.outputs.forEach(e), e(this.otherwise);
                }, Match.prototype.possibleOutputs = function () {
                    return (e = []).concat.apply(e, this.outputs.map(function (e) {
                        return e.possibleOutputs();
                    })).concat(this.otherwise.possibleOutputs());
                    var e;
                }, module.exports = Match;
            },
            { '../values': 147 }
        ],
        136: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../types'), NumberType = ref.NumberType, ref$1 = _dereq_('../stops'), findStopLessThanOrEqualTo = ref$1.findStopLessThanOrEqualTo, Step = function (e, t, r) {
                        var u = this;
                        this.type = e, this.input = t, this.labels = [], this.outputs = [];
                        for (var n = 0, s = r; n < s.length; n += 1) {
                            var p = s[n], a = p[0], i = p[1];
                            u.labels.push(a), u.outputs.push(i);
                        }
                    };
                Step.parse = function (e, t) {
                    var r = e[1], u = e.slice(2);
                    if (e.length - 1 < 4) {
                        return t.error('Expected at least 4 arguments, but found only ' + (e.length - 1) + '.');
                    }
                    if ((e.length - 1) % 2 != 0) {
                        return t.error('Expected an even number of arguments.');
                    }
                    if (!(r = t.parse(r, 1, NumberType))) {
                        return null;
                    }
                    var n = [], s = null;
                    t.expectedType && 'value' !== t.expectedType.kind && (s = t.expectedType), u.unshift(-1 / 0);
                    for (var p = 0; p < u.length; p += 2) {
                        var a = u[p], i = u[p + 1], o = p + 1, l = p + 2;
                        if ('number' != typeof a) {
                            return t.error('Input/output pairs for "step" expressions must be defined using literal numeric values (not computed expressions) for the input values.', o);
                        }
                        if (n.length && n[n.length - 1][0] >= a) {
                            return t.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.', o);
                        }
                        var f = t.parse(i, l, s);
                        if (!f) {
                            return null;
                        }
                        s = s || f.type, n.push([
                            a,
                            f
                        ]);
                    }
                    return new Step(s, r, n);
                }, Step.prototype.evaluate = function (e) {
                    var t = this.labels, r = this.outputs;
                    if (1 === t.length) {
                        return r[0].evaluate(e);
                    }
                    var u = this.input.evaluate(e);
                    if (u <= t[0]) {
                        return r[0].evaluate(e);
                    }
                    var n = t.length;
                    return u >= t[n - 1] ? r[n - 1].evaluate(e) : r[findStopLessThanOrEqualTo(t, u)].evaluate(e);
                }, Step.prototype.eachChild = function (e) {
                    var t = this;
                    e(this.input);
                    for (var r = 0, u = t.outputs; r < u.length; r += 1) {
                        e(u[r]);
                    }
                }, Step.prototype.possibleOutputs = function () {
                    return (e = []).concat.apply(e, this.outputs.map(function (e) {
                        return e.possibleOutputs();
                    }));
                    var e;
                }, module.exports = Step;
            },
            {
                '../stops': 145,
                '../types': 146
            }
        ],
        137: [
            function (_dereq_, module, exports) {
                'use strict';
                var Var = function (e, r) {
                    this.type = r, this.name = e;
                };
                Var.parse = function (e, r) {
                    if (2 !== e.length || 'string' != typeof e[1]) {
                        return r.error('\'var\' expression requires exactly one string literal argument.');
                    }
                    var t = e[1];
                    return r.scope.has(t) ? new Var(t, r.scope.get(t).type) : r.error('Unknown variable "' + t + '". Make sure "' + t + '" has been bound in an enclosing "let" expression before using it.', 1);
                }, Var.prototype.evaluate = function (e) {
                    return e.scope.get(this.name).evaluate(e);
                }, Var.prototype.eachChild = function () {
                }, Var.prototype.possibleOutputs = function () {
                    return [void 0];
                }, module.exports = Var;
            },
            {}
        ],
        138: [
            function (_dereq_, module, exports) {
                'use strict';
                var Scope = _dereq_('./scope'), ref = _dereq_('./values'), Color = ref.Color, geometryTypes = [
                        'Unknown',
                        'Point',
                        'LineString',
                        'Polygon'
                    ], EvaluationContext = function () {
                        this.scope = new Scope(), this._parseColorCache = {};
                    };
                EvaluationContext.prototype.id = function () {
                    return this.feature && 'id' in this.feature ? this.feature.id : null;
                }, EvaluationContext.prototype.geometryType = function () {
                    return this.feature ? 'number' == typeof this.feature.type ? geometryTypes[this.feature.type] : this.feature.type : null;
                }, EvaluationContext.prototype.properties = function () {
                    return this.feature && this.feature.properties || {};
                }, EvaluationContext.prototype.pushScope = function (t) {
                    this.scope = this.scope.concat(t);
                }, EvaluationContext.prototype.popScope = function () {
                    this.scope = this.scope.parent;
                }, EvaluationContext.prototype.parseColor = function (t) {
                    var e = this._parseColorCache[t];
                    return e || (e = this._parseColorCache[t] = Color.parse(t)), e;
                }, module.exports = EvaluationContext;
            },
            {
                './scope': 144,
                './values': 147
            }
        ],
        139: [
            function (_dereq_, module, exports) {
                'use strict';
                function isExpression(e) {
                    return Array.isArray(e) && e.length > 0 && 'string' == typeof e[0] && e[0] in definitions;
                }
                function createExpression(e, r, n) {
                    void 0 === n && (n = {});
                    var t = new ParsingContext(definitions, [], getExpectedType(r)), o = t.parse(e);
                    return o ? success(!1 === n.handleErrors ? new StyleExpression(o) : new StyleExpressionWithErrorHandling(o, r)) : error(t.errors);
                }
                function createPropertyExpression(e, r, n) {
                    if (void 0 === n && (n = {}), e = createExpression(e, r, n), 'error' === e.result) {
                        return e;
                    }
                    var t = e.value.expression, o = isConstant.isFeatureConstant(t);
                    if (!o && !r['property-function']) {
                        return error([new ParsingError('', 'property expressions not supported')]);
                    }
                    var i = isConstant.isGlobalPropertyConstant(t, ['zoom']);
                    if (!i && !1 === r['zoom-function']) {
                        return error([new ParsingError('', 'zoom expressions not supported')]);
                    }
                    var s = findZoomCurve(t);
                    return s || i ? s instanceof ParsingError ? error([s]) : s instanceof Interpolate && 'piecewise-constant' === r.function ? error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]) : success(s ? o ? new ZoomDependentExpression('camera', e.value, s) : new ZoomDependentExpression('composite', e.value, s) : o ? new ZoomConstantExpression('constant', e.value) : new ZoomConstantExpression('source', e.value)) : error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);
                }
                function normalizePropertyExpression(e, r) {
                    if (isFunction(e)) {
                        return new StylePropertyFunction(e, r);
                    }
                    if (isExpression(e)) {
                        var n = createPropertyExpression(e, r);
                        if ('error' === n.result) {
                            throw new Error(n.value.map(function (e) {
                                return e.key + ': ' + e.message;
                            }).join(', '));
                        }
                        return n.value;
                    }
                    var t = e;
                    return 'string' == typeof e && 'color' === r.type && (t = Color.parse(e)), {
                        kind: 'constant',
                        evaluate: function () {
                            return t;
                        }
                    };
                }
                function findZoomCurve(e) {
                    var r = null;
                    if (e instanceof Let) {
                        r = findZoomCurve(e.result);
                    } else if (e instanceof Coalesce) {
                        for (var n = 0, t = e.args; n < t.length; n += 1) {
                            var o = t[n];
                            if (r = findZoomCurve(o)) {
                                break;
                            }
                        }
                    } else {
                        (e instanceof Step || e instanceof Interpolate) && e.input instanceof CompoundExpression && 'zoom' === e.input.name && (r = e);
                    }
                    return r instanceof ParsingError ? r : (e.eachChild(function (e) {
                        var n = findZoomCurve(e);
                        n instanceof ParsingError ? r = n : !r && n ? r = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.') : r && n && r !== n && (r = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'));
                    }), r);
                }
                function getExpectedType(e) {
                    var r = {
                        color: ColorType,
                        string: StringType,
                        number: NumberType,
                        enum: StringType,
                        boolean: BooleanType
                    };
                    return 'array' === e.type ? array(r[e.value] || ValueType, e.length) : r[e.type] || null;
                }
                function getDefaultValue(e) {
                    return 'color' === e.type && isFunction(e.default) ? new Color(0, 0, 0, 0) : 'color' === e.type ? Color.parse(e.default) || null : void 0 === e.default ? null : e.default;
                }
                var extend = _dereq_('../util/extend'), ParsingError = _dereq_('./parsing_error'), ParsingContext = _dereq_('./parsing_context'), EvaluationContext = _dereq_('./evaluation_context'), ref = _dereq_('./compound_expression'), CompoundExpression = ref.CompoundExpression, Step = _dereq_('./definitions/step'), Interpolate = _dereq_('./definitions/interpolate'), Coalesce = _dereq_('./definitions/coalesce'), Let = _dereq_('./definitions/let'), definitions = _dereq_('./definitions'), isConstant = _dereq_('./is_constant'), RuntimeError = _dereq_('./runtime_error'), ref$1 = _dereq_('../util/result'), success = ref$1.success, error = ref$1.error, StyleExpression = function (e) {
                        this.expression = e;
                    };
                StyleExpression.prototype.evaluate = function (e, r) {
                    return this._evaluator || (this._evaluator = new EvaluationContext()), this._evaluator.globals = e, this._evaluator.feature = r, this.expression.evaluate(this._evaluator);
                };
                var StyleExpressionWithErrorHandling = function (e) {
                        function r(r, n) {
                            e.call(this, r), this._warningHistory = {}, this._defaultValue = getDefaultValue(n), 'enum' === n.type && (this._enumValues = n.values);
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r.prototype.evaluate = function (e, r) {
                            this._evaluator || (this._evaluator = new EvaluationContext()), this._evaluator.globals = e, this._evaluator.feature = r;
                            try {
                                var n = this.expression.evaluate(this._evaluator);
                                if (null === n || void 0 === n) {
                                    return this._defaultValue;
                                }
                                if (this._enumValues && !(n in this._enumValues)) {
                                    throw new RuntimeError('Expected value to be one of ' + Object.keys(this._enumValues).map(function (e) {
                                        return JSON.stringify(e);
                                    }).join(', ') + ', but found ' + JSON.stringify(n) + ' instead.');
                                }
                                return n;
                            } catch (e) {
                                return this._warningHistory[e.message] || (this._warningHistory[e.message] = !0, 'undefined' != typeof console && console.warn(e.message)), this._defaultValue;
                            }
                        }, r;
                    }(StyleExpression), ZoomConstantExpression = function (e, r) {
                        this.kind = e, this._styleExpression = r;
                    };
                ZoomConstantExpression.prototype.evaluate = function (e, r) {
                    return this._styleExpression.evaluate(e, r);
                };
                var ZoomDependentExpression = function (e, r, n) {
                    this.kind = e, this.zoomStops = n.labels, this._styleExpression = r, n instanceof Interpolate && (this._interpolationType = n.interpolation);
                };
                ZoomDependentExpression.prototype.evaluate = function (e, r) {
                    return this._styleExpression.evaluate(e, r);
                }, ZoomDependentExpression.prototype.interpolationFactor = function (e, r, n) {
                    return this._interpolationType ? Interpolate.interpolationFactor(this._interpolationType, e, r, n) : 0;
                };
                var ref$2 = _dereq_('../function'), isFunction = ref$2.isFunction, createFunction = ref$2.createFunction, ref$3 = _dereq_('./values'), Color = ref$3.Color, StylePropertyFunction = function (e, r) {
                        this._parameters = e, this._specification = r, extend(this, createFunction(this._parameters, this._specification));
                    };
                StylePropertyFunction.deserialize = function (e) {
                    return new StylePropertyFunction(e._parameters, e._specification);
                }, StylePropertyFunction.serialize = function (e) {
                    return {
                        _parameters: e._parameters,
                        _specification: e._specification
                    };
                }, module.exports = {
                    StyleExpression: StyleExpression,
                    StyleExpressionWithErrorHandling: StyleExpressionWithErrorHandling,
                    isExpression: isExpression,
                    createExpression: createExpression,
                    createPropertyExpression: createPropertyExpression,
                    normalizePropertyExpression: normalizePropertyExpression,
                    ZoomConstantExpression: ZoomConstantExpression,
                    ZoomDependentExpression: ZoomDependentExpression,
                    StylePropertyFunction: StylePropertyFunction
                };
                var ref$4 = _dereq_('./types'), ColorType = ref$4.ColorType, StringType = ref$4.StringType, NumberType = ref$4.NumberType, BooleanType = ref$4.BooleanType, ValueType = ref$4.ValueType, array = ref$4.array;
            },
            {
                '../function': 149,
                '../util/extend': 156,
                '../util/result': 160,
                './compound_expression': 123,
                './definitions': 131,
                './definitions/coalesce': 128,
                './definitions/interpolate': 132,
                './definitions/let': 133,
                './definitions/step': 136,
                './evaluation_context': 138,
                './is_constant': 140,
                './parsing_context': 141,
                './parsing_error': 142,
                './runtime_error': 143,
                './types': 146,
                './values': 147
            }
        ],
        140: [
            function (_dereq_, module, exports) {
                'use strict';
                function isFeatureConstant(n) {
                    if (n instanceof CompoundExpression) {
                        if ('get' === n.name && 1 === n.args.length) {
                            return !1;
                        }
                        if ('has' === n.name && 1 === n.args.length) {
                            return !1;
                        }
                        if ('properties' === n.name || 'geometry-type' === n.name || 'id' === n.name) {
                            return !1;
                        }
                        if (/^filter-/.test(n.name)) {
                            return !1;
                        }
                    }
                    var e = !0;
                    return n.eachChild(function (n) {
                        e && !isFeatureConstant(n) && (e = !1);
                    }), e;
                }
                function isGlobalPropertyConstant(n, e) {
                    if (n instanceof CompoundExpression && e.indexOf(n.name) >= 0) {
                        return !1;
                    }
                    var t = !0;
                    return n.eachChild(function (n) {
                        t && !isGlobalPropertyConstant(n, e) && (t = !1);
                    }), t;
                }
                var ref = _dereq_('./compound_expression'), CompoundExpression = ref.CompoundExpression;
                module.exports = {
                    isFeatureConstant: isFeatureConstant,
                    isGlobalPropertyConstant: isGlobalPropertyConstant
                };
            },
            { './compound_expression': 123 }
        ],
        141: [
            function (_dereq_, module, exports) {
                'use strict';
                function isConstant(e) {
                    var r = _dereq_('./compound_expression'), t = r.CompoundExpression, n = _dereq_('./is_constant'), i = n.isGlobalPropertyConstant, o = n.isFeatureConstant;
                    if (e instanceof _dereq_('./definitions/var')) {
                        return !1;
                    }
                    if (e instanceof t && 'error' === e.name) {
                        return !1;
                    }
                    var a = !0;
                    return e.eachChild(function (e) {
                        e instanceof Literal || (a = !1);
                    }), !!a && (o(e) && i(e, [
                        'zoom',
                        'heatmap-density'
                    ]));
                }
                var Scope = _dereq_('./scope'), ref = _dereq_('./types'), checkSubtype = ref.checkSubtype, ParsingError = _dereq_('./parsing_error'), Literal = _dereq_('./definitions/literal'), Assertion = _dereq_('./definitions/assertion'), ArrayAssertion = _dereq_('./definitions/array'), Coercion = _dereq_('./definitions/coercion'), ParsingContext = function (e, r, t, n, i) {
                        void 0 === r && (r = []), void 0 === n && (n = new Scope()), void 0 === i && (i = []), this.registry = e, this.path = r, this.key = r.map(function (e) {
                            return '[' + e + ']';
                        }).join(''), this.scope = n, this.errors = i, this.expectedType = t;
                    };
                ParsingContext.prototype.parse = function (e, r, t, n, i) {
                    void 0 === i && (i = {});
                    var o = this;
                    if (r && (o = o.concat(r, t, n)), null !== e && 'string' != typeof e && 'boolean' != typeof e && 'number' != typeof e || (e = [
                            'literal',
                            e
                        ]), Array.isArray(e)) {
                        if (0 === e.length) {
                            return o.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');
                        }
                        var a = e[0];
                        if ('string' != typeof a) {
                            return o.error('Expression name must be a string, but found ' + typeof a + ' instead. If you wanted a literal array, use ["literal", [...]].', 0), null;
                        }
                        var s = o.registry[a];
                        if (s) {
                            var u = s.parse(e, o);
                            if (!u) {
                                return null;
                            }
                            if (o.expectedType) {
                                var p = o.expectedType, l = u.type;
                                if ('string' !== p.kind && 'number' !== p.kind && 'boolean' !== p.kind || 'value' !== l.kind) {
                                    if ('array' === p.kind && 'value' === l.kind) {
                                        i.omitTypeAnnotations || (u = new ArrayAssertion(p, u));
                                    } else if ('color' !== p.kind || 'value' !== l.kind && 'string' !== l.kind) {
                                        if (o.checkSubtype(o.expectedType, u.type)) {
                                            return null;
                                        }
                                    } else {
                                        i.omitTypeAnnotations || (u = new Coercion(p, [u]));
                                    }
                                } else {
                                    i.omitTypeAnnotations || (u = new Assertion(p, [u]));
                                }
                            }
                            if (!(u instanceof Literal) && isConstant(u)) {
                                var c = new (_dereq_('./evaluation_context'))();
                                try {
                                    u = new Literal(u.type, u.evaluate(c));
                                } catch (e) {
                                    return o.error(e.message), null;
                                }
                            }
                            return u;
                        }
                        return o.error('Unknown expression "' + a + '". If you wanted a literal array, use ["literal", [...]].', 0);
                    }
                    return void 0 === e ? o.error('\'undefined\' value invalid. Use null instead.') : 'object' == typeof e ? o.error('Bare objects invalid. Use ["literal", {...}] instead.') : o.error('Expected an array, but found ' + typeof e + ' instead.');
                }, ParsingContext.prototype.concat = function (e, r, t) {
                    var n = 'number' == typeof e ? this.path.concat(e) : this.path, i = t ? this.scope.concat(t) : this.scope;
                    return new ParsingContext(this.registry, n, r || null, i, this.errors);
                }, ParsingContext.prototype.error = function (e) {
                    var arguments$1 = arguments;
                    for (var r = [], t = arguments.length - 1; t-- > 0;) {
                        r[t] = arguments$1[t + 1];
                    }
                    var n = '' + this.key + r.map(function (e) {
                        return '[' + e + ']';
                    }).join('');
                    this.errors.push(new ParsingError(n, e));
                }, ParsingContext.prototype.checkSubtype = function (e, r) {
                    var t = checkSubtype(e, r);
                    return t && this.error(t), t;
                }, module.exports = ParsingContext;
            },
            {
                './compound_expression': 123,
                './definitions/array': 124,
                './definitions/assertion': 125,
                './definitions/coercion': 129,
                './definitions/literal': 134,
                './definitions/var': 137,
                './evaluation_context': 138,
                './is_constant': 140,
                './parsing_error': 142,
                './scope': 144,
                './types': 146
            }
        ],
        142: [
            function (_dereq_, module, exports) {
                'use strict';
                var ParsingError = function (r) {
                    function t(t, o) {
                        r.call(this, o), this.message = o, this.key = t;
                    }
                    return r && (t.__proto__ = r), t.prototype = Object.create(r && r.prototype), t.prototype.constructor = t, t;
                }(Error);
                module.exports = ParsingError;
            },
            {}
        ],
        143: [
            function (_dereq_, module, exports) {
                'use strict';
                var RuntimeError = function (r) {
                    this.name = 'ExpressionEvaluationError', this.message = r;
                };
                RuntimeError.prototype.toJSON = function () {
                    return this.message;
                }, module.exports = RuntimeError;
            },
            {}
        ],
        144: [
            function (_dereq_, module, exports) {
                'use strict';
                var Scope = function (t, n) {
                    var i = this;
                    void 0 === n && (n = []), this.parent = t, this.bindings = {};
                    for (var e = 0, r = n; e < r.length; e += 1) {
                        var o = r[e], s = o[0], p = o[1];
                        i.bindings[s] = p;
                    }
                };
                Scope.prototype.concat = function (t) {
                    return new Scope(this, t);
                }, Scope.prototype.get = function (t) {
                    if (this.bindings[t]) {
                        return this.bindings[t];
                    }
                    if (this.parent) {
                        return this.parent.get(t);
                    }
                    throw new Error(t + ' not found in scope.');
                }, Scope.prototype.has = function (t) {
                    return !!this.bindings[t] || !!this.parent && this.parent.has(t);
                }, module.exports = Scope;
            },
            {}
        ],
        145: [
            function (_dereq_, module, exports) {
                'use strict';
                function findStopLessThanOrEqualTo(r, e) {
                    for (var n, t, o = r.length, u = 0, i = o - 1, a = 0; u <= i;) {
                        if (a = Math.floor((u + i) / 2), n = r[a], t = r[a + 1], e === n || e > n && e < t) {
                            return a;
                        }
                        if (n < e) {
                            u = a + 1;
                        } else {
                            if (!(n > e)) {
                                throw new RuntimeError('Input is not a number.');
                            }
                            i = a - 1;
                        }
                    }
                    return Math.max(a - 1, 0);
                }
                var RuntimeError = _dereq_('./runtime_error');
                module.exports = { findStopLessThanOrEqualTo: findStopLessThanOrEqualTo };
            },
            { './runtime_error': 143 }
        ],
        146: [
            function (_dereq_, module, exports) {
                'use strict';
                function array(e, r) {
                    return {
                        kind: 'array',
                        itemType: e,
                        N: r
                    };
                }
                function toString(e) {
                    if ('array' === e.kind) {
                        var r = toString(e.itemType);
                        return 'number' == typeof e.N ? 'array<' + r + ', ' + e.N + '>' : 'value' === e.itemType.kind ? 'array' : 'array<' + r + '>';
                    }
                    return e.kind;
                }
                function checkSubtype(e, r) {
                    if ('error' === r.kind) {
                        return null;
                    }
                    if ('array' === e.kind) {
                        if ('array' === r.kind && !checkSubtype(e.itemType, r.itemType) && ('number' != typeof e.N || e.N === r.N)) {
                            return null;
                        }
                    } else {
                        if (e.kind === r.kind) {
                            return null;
                        }
                        if ('value' === e.kind) {
                            for (var n = 0, y = valueMemberTypes; n < y.length; n += 1) {
                                var t = y[n];
                                if (!checkSubtype(t, r)) {
                                    return null;
                                }
                            }
                        }
                    }
                    return 'Expected ' + toString(e) + ' but found ' + toString(r) + ' instead.';
                }
                var NullType = { kind: 'null' }, NumberType = { kind: 'number' }, StringType = { kind: 'string' }, BooleanType = { kind: 'boolean' }, ColorType = { kind: 'color' }, ObjectType = { kind: 'object' }, ValueType = { kind: 'value' }, ErrorType = { kind: 'error' }, valueMemberTypes = [
                        NullType,
                        NumberType,
                        StringType,
                        BooleanType,
                        ColorType,
                        ObjectType,
                        array(ValueType)
                    ];
                module.exports = {
                    NullType: NullType,
                    NumberType: NumberType,
                    StringType: StringType,
                    BooleanType: BooleanType,
                    ColorType: ColorType,
                    ObjectType: ObjectType,
                    ValueType: ValueType,
                    array: array,
                    ErrorType: ErrorType,
                    toString: toString,
                    checkSubtype: checkSubtype
                };
            },
            {}
        ],
        147: [
            function (_dereq_, module, exports) {
                'use strict';
                function validateRGBA(e, r, t, n) {
                    if (!('number' == typeof e && e >= 0 && e <= 255 && 'number' == typeof r && r >= 0 && r <= 255 && 'number' == typeof t && t >= 0 && t <= 255)) {
                        return 'Invalid rgba value [' + ('number' == typeof n ? [
                            e,
                            r,
                            t,
                            n
                        ] : [
                            e,
                            r,
                            t
                        ]).join(', ') + ']: \'r\', \'g\', and \'b\' must be between 0 and 255.';
                    }
                    return void 0 === n || 'number' == typeof n && n >= 0 && n <= 1 ? null : 'Invalid rgba value [' + [
                        e,
                        r,
                        t,
                        n
                    ].join(', ') + ']: \'a\' must be between 0 and 1.';
                }
                function isValue(e) {
                    if (null === e) {
                        return !0;
                    }
                    if ('string' == typeof e) {
                        return !0;
                    }
                    if ('boolean' == typeof e) {
                        return !0;
                    }
                    if ('number' == typeof e) {
                        return !0;
                    }
                    if (e instanceof Color) {
                        return !0;
                    }
                    if (Array.isArray(e)) {
                        for (var r = 0, t = e; r < t.length; r += 1) {
                            if (!isValue(t[r])) {
                                return !1;
                            }
                        }
                        return !0;
                    }
                    if ('object' == typeof e) {
                        for (var n in e) {
                            if (!isValue(e[n])) {
                                return !1;
                            }
                        }
                        return !0;
                    }
                    return !1;
                }
                function typeOf(e) {
                    if (null === e) {
                        return NullType;
                    }
                    if ('string' == typeof e) {
                        return StringType;
                    }
                    if ('boolean' == typeof e) {
                        return BooleanType;
                    }
                    if ('number' == typeof e) {
                        return NumberType;
                    }
                    if (e instanceof Color) {
                        return ColorType;
                    }
                    if (Array.isArray(e)) {
                        for (var r, t = e.length, n = 0, u = e; n < u.length; n += 1) {
                            var o = u[n], f = typeOf(o);
                            if (r) {
                                if (r === f) {
                                    continue;
                                }
                                r = ValueType;
                                break;
                            }
                            r = f;
                        }
                        return array(r || ValueType, t);
                    }
                    return ObjectType;
                }
                var Color = _dereq_('../util/color'), ref = _dereq_('./types'), NullType = ref.NullType, NumberType = ref.NumberType, StringType = ref.StringType, BooleanType = ref.BooleanType, ColorType = ref.ColorType, ObjectType = ref.ObjectType, ValueType = ref.ValueType, array = ref.array;
                module.exports = {
                    Color: Color,
                    validateRGBA: validateRGBA,
                    isValue: isValue,
                    typeOf: typeOf
                };
            },
            {
                '../util/color': 153,
                './types': 146
            }
        ],
        148: [
            function (_dereq_, module, exports) {
                'use strict';
                function isExpressionFilter(e) {
                    if (!Array.isArray(e) || 0 === e.length) {
                        return !1;
                    }
                    switch (e[0]) {
                    case 'has':
                        return e.length >= 2 && '$id' !== e[1] && '$type' !== e[1];
                    case 'in':
                    case '!in':
                    case '!has':
                    case 'none':
                        return !1;
                    case '==':
                    case '!=':
                    case '>':
                    case '>=':
                    case '<':
                    case '<=':
                        return 3 === e.length && (Array.isArray(e[1]) || Array.isArray(e[2]));
                    case 'any':
                    case 'all':
                        for (var r = 0, t = e.slice(1); r < t.length; r += 1) {
                            var n = t[r];
                            if (!isExpressionFilter(n) && 'boolean' != typeof n) {
                                return !1;
                            }
                        }
                        return !0;
                    default:
                        return !0;
                    }
                }
                function createFilter(e) {
                    if (!e) {
                        return function () {
                            return !0;
                        };
                    }
                    isExpressionFilter(e) || (e = convertFilter(e));
                    var r = createExpression(e, filterSpec);
                    if ('error' === r.result) {
                        throw new Error(r.value.map(function (e) {
                            return e.key + ': ' + e.message;
                        }).join(', '));
                    }
                    return function (e, t) {
                        return r.value.evaluate(e, t);
                    };
                }
                function compare(e, r) {
                    return e < r ? -1 : e > r ? 1 : 0;
                }
                function convertFilter(e) {
                    if (!e) {
                        return !0;
                    }
                    var r = e[0];
                    return e.length <= 1 ? 'any' !== r : '==' === r ? convertComparisonOp(e[1], e[2], '==') : '!=' === r ? convertNegation(convertComparisonOp(e[1], e[2], '==')) : '<' === r || '>' === r || '<=' === r || '>=' === r ? convertComparisonOp(e[1], e[2], r) : 'any' === r ? convertDisjunctionOp(e.slice(1)) : 'all' === r ? ['all'].concat(e.slice(1).map(convertFilter)) : 'none' === r ? ['all'].concat(e.slice(1).map(convertFilter).map(convertNegation)) : 'in' === r ? convertInOp(e[1], e.slice(2)) : '!in' === r ? convertNegation(convertInOp(e[1], e.slice(2))) : 'has' === r ? convertHasOp(e[1]) : '!has' !== r || convertNegation(convertHasOp(e[1]));
                }
                function convertComparisonOp(e, r, t) {
                    switch (e) {
                    case '$type':
                        return [
                            'filter-type-' + t,
                            r
                        ];
                    case '$id':
                        return [
                            'filter-id-' + t,
                            r
                        ];
                    default:
                        return [
                            'filter-' + t,
                            e,
                            r
                        ];
                    }
                }
                function convertDisjunctionOp(e) {
                    return ['any'].concat(e.map(convertFilter));
                }
                function convertInOp(e, r) {
                    if (0 === r.length) {
                        return !1;
                    }
                    switch (e) {
                    case '$type':
                        return [
                            'filter-type-in',
                            [
                                'literal',
                                r
                            ]
                        ];
                    case '$id':
                        return [
                            'filter-id-in',
                            [
                                'literal',
                                r
                            ]
                        ];
                    default:
                        return r.length > 200 && !r.some(function (e) {
                            return typeof e != typeof r[0];
                        }) ? [
                            'filter-in-large',
                            e,
                            [
                                'literal',
                                r.sort(compare)
                            ]
                        ] : [
                            'filter-in-small',
                            e,
                            [
                                'literal',
                                r
                            ]
                        ];
                    }
                }
                function convertHasOp(e) {
                    switch (e) {
                    case '$type':
                        return !0;
                    case '$id':
                        return ['filter-has-id'];
                    default:
                        return [
                            'filter-has',
                            e
                        ];
                    }
                }
                function convertNegation(e) {
                    return [
                        '!',
                        e
                    ];
                }
                var ref = _dereq_('../expression'), createExpression = ref.createExpression;
                module.exports = createFilter, module.exports.isExpressionFilter = isExpressionFilter;
                var filterSpec = {
                    type: 'boolean',
                    default: !1,
                    function: !0,
                    'property-function': !0,
                    'zoom-function': !0
                };
            },
            { '../expression': 139 }
        ],
        149: [
            function (_dereq_, module, exports) {
                'use strict';
                function isFunction(e) {
                    return 'object' == typeof e && null !== e && !Array.isArray(e);
                }
                function identityFunction(e) {
                    return e;
                }
                function createFunction(e, t) {
                    var o = 'color' === t.type, r = e.stops && 'object' == typeof e.stops[0][0], n = r || void 0 !== e.property, a = r || !n, i = e.type || ('interpolated' === t.function ? 'exponential' : 'interval');
                    if (o && (e = extend({}, e), e.stops && (e.stops = e.stops.map(function (e) {
                            return [
                                e[0],
                                Color.parse(e[1])
                            ];
                        })), e.default ? e.default = Color.parse(e.default) : e.default = Color.parse(t.default)), e.colorSpace && 'rgb' !== e.colorSpace && !colorSpaces[e.colorSpace]) {
                        throw new Error('Unknown color space: ' + e.colorSpace);
                    }
                    var u, p, l;
                    if ('exponential' === i) {
                        u = evaluateExponentialFunction;
                    } else if ('interval' === i) {
                        u = evaluateIntervalFunction;
                    } else if ('categorical' === i) {
                        u = evaluateCategoricalFunction, p = Object.create(null);
                        for (var s = 0, c = e.stops; s < c.length; s += 1) {
                            var f = c[s];
                            p[f[0]] = f[1];
                        }
                        l = typeof e.stops[0][0];
                    } else {
                        if ('identity' !== i) {
                            throw new Error('Unknown function type "' + i + '"');
                        }
                        u = evaluateIdentityFunction;
                    }
                    if (r) {
                        for (var v = {}, d = [], y = 0; y < e.stops.length; y++) {
                            var F = e.stops[y], h = F[0].zoom;
                            void 0 === v[h] && (v[h] = {
                                zoom: h,
                                type: e.type,
                                property: e.property,
                                default: e.default,
                                stops: []
                            }, d.push(h)), v[h].stops.push([
                                F[0].value,
                                F[1]
                            ]);
                        }
                        for (var m = [], g = 0, b = d; g < b.length; g += 1) {
                            var S = b[g];
                            m.push([
                                v[S].zoom,
                                createFunction(v[S], t)
                            ]);
                        }
                        return {
                            kind: 'composite',
                            interpolationFactor: Interpolate.interpolationFactor.bind(void 0, { name: 'linear' }),
                            zoomStops: m.map(function (e) {
                                return e[0];
                            }),
                            evaluate: function (o, r) {
                                var n = o.zoom;
                                return evaluateExponentialFunction({
                                    stops: m,
                                    base: e.base
                                }, t, n).evaluate(n, r);
                            }
                        };
                    }
                    return a ? {
                        kind: 'camera',
                        interpolationFactor: 'exponential' === i ? Interpolate.interpolationFactor.bind(void 0, {
                            name: 'exponential',
                            base: void 0 !== e.base ? e.base : 1
                        }) : function () {
                            return 0;
                        },
                        zoomStops: e.stops.map(function (e) {
                            return e[0];
                        }),
                        evaluate: function (o) {
                            var r = o.zoom;
                            return u(e, t, r, p, l);
                        }
                    } : {
                        kind: 'source',
                        evaluate: function (o, r) {
                            var n = r && r.properties ? r.properties[e.property] : void 0;
                            return void 0 === n ? coalesce(e.default, t.default) : u(e, t, n, p, l);
                        }
                    };
                }
                function coalesce(e, t, o) {
                    return void 0 !== e ? e : void 0 !== t ? t : void 0 !== o ? o : void 0;
                }
                function evaluateCategoricalFunction(e, t, o, r, n) {
                    return coalesce(typeof o === n ? r[o] : void 0, e.default, t.default);
                }
                function evaluateIntervalFunction(e, t, o) {
                    if ('number' !== getType(o)) {
                        return coalesce(e.default, t.default);
                    }
                    var r = e.stops.length;
                    if (1 === r) {
                        return e.stops[0][1];
                    }
                    if (o <= e.stops[0][0]) {
                        return e.stops[0][1];
                    }
                    if (o >= e.stops[r - 1][0]) {
                        return e.stops[r - 1][1];
                    }
                    var n = findStopLessThanOrEqualTo(e.stops, o);
                    return e.stops[n][1];
                }
                function evaluateExponentialFunction(e, t, o) {
                    var r = void 0 !== e.base ? e.base : 1;
                    if ('number' !== getType(o)) {
                        return coalesce(e.default, t.default);
                    }
                    var n = e.stops.length;
                    if (1 === n) {
                        return e.stops[0][1];
                    }
                    if (o <= e.stops[0][0]) {
                        return e.stops[0][1];
                    }
                    if (o >= e.stops[n - 1][0]) {
                        return e.stops[n - 1][1];
                    }
                    var a = findStopLessThanOrEqualTo(e.stops, o), i = interpolationFactor(o, r, e.stops[a][0], e.stops[a + 1][0]), u = e.stops[a][1], p = e.stops[a + 1][1], l = interpolate[t.type] || identityFunction;
                    if (e.colorSpace && 'rgb' !== e.colorSpace) {
                        var s = colorSpaces[e.colorSpace];
                        l = function (e, t) {
                            return s.reverse(s.interpolate(s.forward(e), s.forward(t), i));
                        };
                    }
                    return 'function' == typeof u.evaluate ? {
                        evaluate: function () {
                            var arguments$1 = arguments;
                            for (var e = [], t = arguments.length; t--;) {
                                e[t] = arguments$1[t];
                            }
                            var o = u.evaluate.apply(void 0, e), r = p.evaluate.apply(void 0, e);
                            if (void 0 !== o && void 0 !== r) {
                                return l(o, r, i);
                            }
                        }
                    } : l(u, p, i);
                }
                function evaluateIdentityFunction(e, t, o) {
                    return 'color' === t.type ? o = Color.parse(o) : getType(o) === t.type || 'enum' === t.type && t.values[o] || (o = void 0), coalesce(o, e.default, t.default);
                }
                function findStopLessThanOrEqualTo(e, t) {
                    for (var o, r, n = e.length, a = 0, i = n - 1, u = 0; a <= i;) {
                        if (u = Math.floor((a + i) / 2), o = e[u][0], r = e[u + 1][0], t === o || t > o && t < r) {
                            return u;
                        }
                        o < t ? a = u + 1 : o > t && (i = u - 1);
                    }
                    return Math.max(u - 1, 0);
                }
                function interpolationFactor(e, t, o, r) {
                    var n = r - o, a = e - o;
                    return 0 === n ? 0 : 1 === t ? a / n : (Math.pow(t, a) - 1) / (Math.pow(t, n) - 1);
                }
                var colorSpaces = _dereq_('../util/color_spaces'), Color = _dereq_('../util/color'), extend = _dereq_('../util/extend'), getType = _dereq_('../util/get_type'), interpolate = _dereq_('../util/interpolate'), Interpolate = _dereq_('../expression/definitions/interpolate');
                module.exports = {
                    createFunction: createFunction,
                    isFunction: isFunction
                };
            },
            {
                '../expression/definitions/interpolate': 132,
                '../util/color': 153,
                '../util/color_spaces': 154,
                '../util/extend': 156,
                '../util/get_type': 157,
                '../util/interpolate': 158
            }
        ],
        150: [
            function (_dereq_, module, exports) {
                'use strict';
                function stringify(r) {
                    var t = typeof r;
                    if ('number' === t || 'boolean' === t || 'string' === t || void 0 === r || null === r) {
                        return JSON.stringify(r);
                    }
                    if (Array.isArray(r)) {
                        for (var e = '[', i = 0, n = r; i < n.length; i += 1) {
                            e += stringify(n[i]) + ',';
                        }
                        return e + ']';
                    }
                    for (var o = Object.keys(r).sort(), f = '{', u = 0; u < o.length; u++) {
                        f += JSON.stringify(o[u]) + ':' + stringify(r[o[u]]) + ',';
                    }
                    return f + '}';
                }
                function getKey(r) {
                    for (var t = '', e = 0, i = refProperties; e < i.length; e += 1) {
                        t += '/' + stringify(r[i[e]]);
                    }
                    return t;
                }
                function groupByLayout(r) {
                    for (var t = {}, e = 0; e < r.length; e++) {
                        var i = getKey(r[e]), n = t[i];
                        n || (n = t[i] = []), n.push(r[e]);
                    }
                    var o = [];
                    for (var f in t) {
                        o.push(t[f]);
                    }
                    return o;
                }
                var refProperties = _dereq_('./util/ref_properties');
                module.exports = groupByLayout;
            },
            { './util/ref_properties': 159 }
        ],
        151: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = _dereq_('./v8.json');
            },
            { './v8.json': 152 }
        ],
        152: [
            function (_dereq_, module, exports) {
                module.exports = {
                    '$version': 8,
                    '$root': {
                        'version': {
                            'required': true,
                            'type': 'enum',
                            'values': [8]
                        },
                        'name': { 'type': 'string' },
                        'metadata': { 'type': '*' },
                        'center': {
                            'type': 'array',
                            'value': 'number'
                        },
                        'zoom': { 'type': 'number' },
                        'bearing': {
                            'type': 'number',
                            'default': 0,
                            'period': 360,
                            'units': 'degrees'
                        },
                        'pitch': {
                            'type': 'number',
                            'default': 0,
                            'units': 'degrees'
                        },
                        'light': { 'type': 'light' },
                        'sources': {
                            'required': true,
                            'type': 'sources'
                        },
                        'sprite': { 'type': 'string' },
                        'glyphs': { 'type': 'string' },
                        'transition': { 'type': 'transition' },
                        'layers': {
                            'required': true,
                            'type': 'array',
                            'value': 'layer'
                        }
                    },
                    'sources': { '*': { 'type': 'source' } },
                    'source': [
                        'source_vector',
                        'source_raster',
                        'source_raster_dem',
                        'source_geojson',
                        'source_video',
                        'source_image',
                        'source_canvas'
                    ],
                    'source_vector': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'vector': {} }
                        },
                        'url': { 'type': 'string' },
                        'tiles': {
                            'type': 'array',
                            'value': 'string'
                        },
                        'bounds': {
                            'type': 'array',
                            'value': 'number',
                            'length': 4,
                            'default': [
                                -180,
                                -85.0511,
                                180,
                                85.0511
                            ]
                        },
                        'minzoom': {
                            'type': 'number',
                            'default': 0
                        },
                        'maxzoom': {
                            'type': 'number',
                            'default': 22
                        },
                        'attribution': { 'type': 'string' },
                        '*': { 'type': '*' }
                    },
                    'source_raster': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'raster': {} }
                        },
                        'url': { 'type': 'string' },
                        'tiles': {
                            'type': 'array',
                            'value': 'string'
                        },
                        'bounds': {
                            'type': 'array',
                            'value': 'number',
                            'length': 4,
                            'default': [
                                -180,
                                -85.0511,
                                180,
                                85.0511
                            ]
                        },
                        'minzoom': {
                            'type': 'number',
                            'default': 0
                        },
                        'maxzoom': {
                            'type': 'number',
                            'default': 22
                        },
                        'tileSize': {
                            'type': 'number',
                            'default': 512,
                            'units': 'pixels'
                        },
                        'scheme': {
                            'type': 'enum',
                            'values': {
                                'xyz': {},
                                'tms': {}
                            },
                            'default': 'xyz'
                        },
                        'attribution': { 'type': 'string' },
                        '*': { 'type': '*' }
                    },
                    'source_raster_dem': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'raster-dem': {} }
                        },
                        'url': { 'type': 'string' },
                        'tiles': {
                            'type': 'array',
                            'value': 'string'
                        },
                        'bounds': {
                            'type': 'array',
                            'value': 'number',
                            'length': 4,
                            'default': [
                                -180,
                                -85.0511,
                                180,
                                85.0511
                            ]
                        },
                        'minzoom': {
                            'type': 'number',
                            'default': 0
                        },
                        'maxzoom': {
                            'type': 'number',
                            'default': 22
                        },
                        'tileSize': {
                            'type': 'number',
                            'default': 512,
                            'units': 'pixels'
                        },
                        'attribution': { 'type': 'string' },
                        '*': { 'type': '*' }
                    },
                    'source_geojson': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'geojson': {} }
                        },
                        'data': { 'type': '*' },
                        'maxzoom': {
                            'type': 'number',
                            'default': 18
                        },
                        'buffer': {
                            'type': 'number',
                            'default': 128,
                            'maximum': 512,
                            'minimum': 0
                        },
                        'tolerance': {
                            'type': 'number',
                            'default': 0.375
                        },
                        'cluster': {
                            'type': 'boolean',
                            'default': false
                        },
                        'clusterRadius': {
                            'type': 'number',
                            'default': 50,
                            'minimum': 0
                        },
                        'clusterMaxZoom': { 'type': 'number' }
                    },
                    'source_video': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'video': {} }
                        },
                        'urls': {
                            'required': true,
                            'type': 'array',
                            'value': 'string'
                        },
                        'coordinates': {
                            'required': true,
                            'type': 'array',
                            'length': 4,
                            'value': {
                                'type': 'array',
                                'length': 2,
                                'value': 'number'
                            }
                        }
                    },
                    'source_image': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'image': {} }
                        },
                        'url': {
                            'required': true,
                            'type': 'string'
                        },
                        'coordinates': {
                            'required': true,
                            'type': 'array',
                            'length': 4,
                            'value': {
                                'type': 'array',
                                'length': 2,
                                'value': 'number'
                            }
                        }
                    },
                    'source_canvas': {
                        'type': {
                            'required': true,
                            'type': 'enum',
                            'values': { 'canvas': {} }
                        },
                        'coordinates': {
                            'required': true,
                            'type': 'array',
                            'length': 4,
                            'value': {
                                'type': 'array',
                                'length': 2,
                                'value': 'number'
                            }
                        },
                        'animate': {
                            'type': 'boolean',
                            'default': 'true'
                        },
                        'canvas': {
                            'type': 'string',
                            'required': true
                        }
                    },
                    'layer': {
                        'id': {
                            'type': 'string',
                            'required': true
                        },
                        'type': {
                            'type': 'enum',
                            'values': {
                                'fill': {},
                                'line': {},
                                'symbol': {},
                                'circle': {},
                                'heatmap': {},
                                'fill-extrusion': {},
                                'raster': {},
                                'hillshade': {},
                                'background': {}
                            },
                            'required': true
                        },
                        'metadata': { 'type': '*' },
                        'source': { 'type': 'string' },
                        'source-layer': { 'type': 'string' },
                        'minzoom': {
                            'type': 'number',
                            'minimum': 0,
                            'maximum': 24
                        },
                        'maxzoom': {
                            'type': 'number',
                            'minimum': 0,
                            'maximum': 24
                        },
                        'filter': { 'type': 'filter' },
                        'layout': { 'type': 'layout' },
                        'paint': { 'type': 'paint' }
                    },
                    'layout': [
                        'layout_fill',
                        'layout_line',
                        'layout_circle',
                        'layout_heatmap',
                        'layout_fill-extrusion',
                        'layout_symbol',
                        'layout_raster',
                        'layout_hillshade',
                        'layout_background'
                    ],
                    'layout_background': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_fill': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_circle': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_heatmap': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_fill-extrusion': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_line': {
                        'line-cap': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'butt': {},
                                'round': {},
                                'square': {}
                            },
                            'default': 'butt'
                        },
                        'line-join': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'values': {
                                'bevel': {},
                                'round': {},
                                'miter': {}
                            },
                            'default': 'miter'
                        },
                        'line-miter-limit': {
                            'type': 'number',
                            'default': 2,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'requires': [{ 'line-join': 'miter' }]
                        },
                        'line-round-limit': {
                            'type': 'number',
                            'default': 1.05,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'requires': [{ 'line-join': 'round' }]
                        },
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_symbol': {
                        'symbol-placement': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'point': {},
                                'line': {}
                            },
                            'default': 'point'
                        },
                        'symbol-spacing': {
                            'type': 'number',
                            'default': 250,
                            'minimum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'units': 'pixels',
                            'requires': [{ 'symbol-placement': 'line' }]
                        },
                        'symbol-avoid-edges': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false
                        },
                        'icon-allow-overlap': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': ['icon-image']
                        },
                        'icon-ignore-placement': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': ['icon-image']
                        },
                        'icon-optional': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': [
                                'icon-image',
                                'text-field'
                            ]
                        },
                        'icon-rotation-alignment': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {},
                                'auto': {}
                            },
                            'default': 'auto',
                            'requires': ['icon-image']
                        },
                        'icon-size': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'units': 'factor of the original icon size',
                            'requires': ['icon-image']
                        },
                        'icon-text-fit': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'none': {},
                                'width': {},
                                'height': {},
                                'both': {}
                            },
                            'default': 'none',
                            'requires': [
                                'icon-image',
                                'text-field'
                            ]
                        },
                        'icon-text-fit-padding': {
                            'type': 'array',
                            'value': 'number',
                            'length': 4,
                            'default': [
                                0,
                                0,
                                0,
                                0
                            ],
                            'units': 'pixels',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'requires': [
                                'icon-image',
                                'text-field',
                                {
                                    'icon-text-fit': [
                                        'both',
                                        'width',
                                        'height'
                                    ]
                                }
                            ]
                        },
                        'icon-image': {
                            'type': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'tokens': true
                        },
                        'icon-rotate': {
                            'type': 'number',
                            'default': 0,
                            'period': 360,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'units': 'degrees',
                            'requires': ['icon-image']
                        },
                        'icon-padding': {
                            'type': 'number',
                            'default': 2,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'units': 'pixels',
                            'requires': ['icon-image']
                        },
                        'icon-keep-upright': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': [
                                'icon-image',
                                { 'icon-rotation-alignment': 'map' },
                                { 'symbol-placement': 'line' }
                            ]
                        },
                        'icon-offset': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'requires': ['icon-image']
                        },
                        'icon-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'values': {
                                'center': {},
                                'left': {},
                                'right': {},
                                'top': {},
                                'bottom': {},
                                'top-left': {},
                                'top-right': {},
                                'bottom-left': {},
                                'bottom-right': {}
                            },
                            'default': 'center',
                            'requires': ['icon-image']
                        },
                        'icon-pitch-alignment': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {},
                                'auto': {}
                            },
                            'default': 'auto',
                            'requires': ['icon-image']
                        },
                        'text-pitch-alignment': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {},
                                'auto': {}
                            },
                            'default': 'auto',
                            'requires': ['text-field']
                        },
                        'text-rotation-alignment': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {},
                                'auto': {}
                            },
                            'default': 'auto',
                            'requires': ['text-field']
                        },
                        'text-field': {
                            'type': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'default': '',
                            'tokens': true
                        },
                        'text-font': {
                            'type': 'array',
                            'value': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'default': [
                                'Open Sans Regular',
                                'Arial Unicode MS Regular'
                            ],
                            'requires': ['text-field']
                        },
                        'text-size': {
                            'type': 'number',
                            'default': 16,
                            'minimum': 0,
                            'units': 'pixels',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'requires': ['text-field']
                        },
                        'text-max-width': {
                            'type': 'number',
                            'default': 10,
                            'minimum': 0,
                            'units': 'ems',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'requires': ['text-field']
                        },
                        'text-line-height': {
                            'type': 'number',
                            'default': 1.2,
                            'units': 'ems',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'requires': ['text-field']
                        },
                        'text-letter-spacing': {
                            'type': 'number',
                            'default': 0,
                            'units': 'ems',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'requires': ['text-field']
                        },
                        'text-justify': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'values': {
                                'left': {},
                                'center': {},
                                'right': {}
                            },
                            'default': 'center',
                            'requires': ['text-field']
                        },
                        'text-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'values': {
                                'center': {},
                                'left': {},
                                'right': {},
                                'top': {},
                                'bottom': {},
                                'top-left': {},
                                'top-right': {},
                                'bottom-left': {},
                                'bottom-right': {}
                            },
                            'default': 'center',
                            'requires': ['text-field']
                        },
                        'text-max-angle': {
                            'type': 'number',
                            'default': 45,
                            'units': 'degrees',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'requires': [
                                'text-field',
                                { 'symbol-placement': 'line' }
                            ]
                        },
                        'text-rotate': {
                            'type': 'number',
                            'default': 0,
                            'period': 360,
                            'units': 'degrees',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'requires': ['text-field']
                        },
                        'text-padding': {
                            'type': 'number',
                            'default': 2,
                            'minimum': 0,
                            'units': 'pixels',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'requires': ['text-field']
                        },
                        'text-keep-upright': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': true,
                            'requires': [
                                'text-field',
                                { 'text-rotation-alignment': 'map' },
                                { 'symbol-placement': 'line' }
                            ]
                        },
                        'text-transform': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'property-function': true,
                            'values': {
                                'none': {},
                                'uppercase': {},
                                'lowercase': {}
                            },
                            'default': 'none',
                            'requires': ['text-field']
                        },
                        'text-offset': {
                            'type': 'array',
                            'value': 'number',
                            'units': 'ems',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'requires': ['text-field']
                        },
                        'text-allow-overlap': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': ['text-field']
                        },
                        'text-ignore-placement': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': ['text-field']
                        },
                        'text-optional': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': false,
                            'requires': [
                                'text-field',
                                'icon-image'
                            ]
                        },
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_raster': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'layout_hillshade': {
                        'visibility': {
                            'type': 'enum',
                            'values': {
                                'visible': {},
                                'none': {}
                            },
                            'default': 'visible'
                        }
                    },
                    'filter': {
                        'type': 'array',
                        'value': '*'
                    },
                    'filter_operator': {
                        'type': 'enum',
                        'values': {
                            '==': {},
                            '!=': {},
                            '>': {},
                            '>=': {},
                            '<': {},
                            '<=': {},
                            'in': {},
                            '!in': {},
                            'all': {},
                            'any': {},
                            'none': {},
                            'has': {},
                            '!has': {}
                        }
                    },
                    'geometry_type': {
                        'type': 'enum',
                        'values': {
                            'Point': {},
                            'LineString': {},
                            'Polygon': {}
                        }
                    },
                    'function': {
                        'expression': { 'type': 'expression' },
                        'stops': {
                            'type': 'array',
                            'value': 'function_stop'
                        },
                        'base': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0
                        },
                        'property': {
                            'type': 'string',
                            'default': '$zoom'
                        },
                        'type': {
                            'type': 'enum',
                            'values': {
                                'identity': {},
                                'exponential': {},
                                'interval': {},
                                'categorical': {}
                            },
                            'default': 'exponential'
                        },
                        'colorSpace': {
                            'type': 'enum',
                            'values': {
                                'rgb': {},
                                'lab': {},
                                'hcl': {}
                            },
                            'default': 'rgb'
                        },
                        'default': {
                            'type': '*',
                            'required': false
                        }
                    },
                    'function_stop': {
                        'type': 'array',
                        'minimum': 0,
                        'maximum': 22,
                        'value': [
                            'number',
                            'color'
                        ],
                        'length': 2
                    },
                    'expression': {
                        'type': 'array',
                        'value': '*',
                        'minimum': 1
                    },
                    'expression_name': {
                        'type': 'enum',
                        'values': {
                            'let': { 'group': 'Variable binding' },
                            'var': { 'group': 'Variable binding' },
                            'literal': { 'group': 'Types' },
                            'array': { 'group': 'Types' },
                            'at': { 'group': 'Lookup' },
                            'case': { 'group': 'Decision' },
                            'match': { 'group': 'Decision' },
                            'coalesce': { 'group': 'Decision' },
                            'step': { 'group': 'Ramps, scales, curves' },
                            'interpolate': { 'group': 'Ramps, scales, curves' },
                            'ln2': { 'group': 'Math' },
                            'pi': { 'group': 'Math' },
                            'e': { 'group': 'Math' },
                            'typeof': { 'group': 'Types' },
                            'string': { 'group': 'Types' },
                            'number': { 'group': 'Types' },
                            'boolean': { 'group': 'Types' },
                            'object': { 'group': 'Types' },
                            'to-string': { 'group': 'Types' },
                            'to-number': { 'group': 'Types' },
                            'to-boolean': { 'group': 'Types' },
                            'to-rgba': { 'group': 'Color' },
                            'to-color': { 'group': 'Types' },
                            'rgb': { 'group': 'Color' },
                            'rgba': { 'group': 'Color' },
                            'get': { 'group': 'Lookup' },
                            'has': { 'group': 'Lookup' },
                            'length': { 'group': 'Lookup' },
                            'properties': { 'group': 'Feature data' },
                            'geometry-type': { 'group': 'Feature data' },
                            'id': { 'group': 'Feature data' },
                            'zoom': { 'group': 'Zoom' },
                            'heatmap-density': { 'group': 'Heatmap' },
                            '+': { 'group': 'Math' },
                            '*': { 'group': 'Math' },
                            '-': { 'group': 'Math' },
                            '/': { 'group': 'Math' },
                            '%': { 'group': 'Math' },
                            '^': { 'group': 'Math' },
                            'sqrt': { 'group': 'Math' },
                            'log10': { 'group': 'Math' },
                            'ln': { 'group': 'Math' },
                            'log2': { 'group': 'Math' },
                            'sin': { 'group': 'Math' },
                            'cos': { 'group': 'Math' },
                            'tan': { 'group': 'Math' },
                            'asin': { 'group': 'Math' },
                            'acos': { 'group': 'Math' },
                            'atan': { 'group': 'Math' },
                            'min': { 'group': 'Math' },
                            'max': { 'group': 'Math' },
                            '==': { 'group': 'Decision' },
                            '!=': { 'group': 'Decision' },
                            '>': { 'group': 'Decision' },
                            '<': { 'group': 'Decision' },
                            '>=': { 'group': 'Decision' },
                            '<=': { 'group': 'Decision' },
                            'all': { 'group': 'Decision' },
                            'any': { 'group': 'Decision' },
                            '!': { 'group': 'Decision' },
                            'upcase': { 'group': 'String' },
                            'downcase': { 'group': 'String' },
                            'concat': { 'group': 'String' }
                        }
                    },
                    'light': {
                        'anchor': {
                            'type': 'enum',
                            'default': 'viewport',
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'transition': false,
                            'zoom-function': true,
                            'property-function': false,
                            'function': 'piecewise-constant'
                        },
                        'position': {
                            'type': 'array',
                            'default': [
                                1.15,
                                210,
                                30
                            ],
                            'length': 3,
                            'value': 'number',
                            'transition': true,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': false
                        },
                        'color': {
                            'type': 'color',
                            'default': '#ffffff',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': false,
                            'transition': true
                        },
                        'intensity': {
                            'type': 'number',
                            'default': 0.5,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': false,
                            'transition': true
                        }
                    },
                    'paint': [
                        'paint_fill',
                        'paint_line',
                        'paint_circle',
                        'paint_heatmap',
                        'paint_fill-extrusion',
                        'paint_symbol',
                        'paint_raster',
                        'paint_hillshade',
                        'paint_background'
                    ],
                    'paint_fill': {
                        'fill-antialias': {
                            'type': 'boolean',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'default': true
                        },
                        'fill-opacity': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'transition': true
                        },
                        'fill-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': [{ '!': 'fill-pattern' }]
                        },
                        'fill-outline-color': {
                            'type': 'color',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': [
                                { '!': 'fill-pattern' },
                                { 'fill-antialias': true }
                            ]
                        },
                        'fill-translate': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'fill-translate-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map',
                            'requires': ['fill-translate']
                        },
                        'fill-pattern': {
                            'type': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'transition': true
                        }
                    },
                    'paint_fill-extrusion': {
                        'fill-extrusion-opacity': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': false,
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'transition': true
                        },
                        'fill-extrusion-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': [{ '!': 'fill-extrusion-pattern' }]
                        },
                        'fill-extrusion-translate': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'fill-extrusion-translate-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map',
                            'requires': ['fill-extrusion-translate']
                        },
                        'fill-extrusion-pattern': {
                            'type': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'transition': true
                        },
                        'fill-extrusion-height': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'default': 0,
                            'minimum': 0,
                            'units': 'meters',
                            'transition': true
                        },
                        'fill-extrusion-base': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'default': 0,
                            'minimum': 0,
                            'units': 'meters',
                            'transition': true,
                            'requires': ['fill-extrusion-height']
                        }
                    },
                    'paint_line': {
                        'line-opacity': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'transition': true
                        },
                        'line-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': [{ '!': 'line-pattern' }]
                        },
                        'line-translate': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'line-translate-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map',
                            'requires': ['line-translate']
                        },
                        'line-width': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'line-gap-width': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'line-offset': {
                            'type': 'number',
                            'default': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'line-blur': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'line-dasharray': {
                            'type': 'array',
                            'value': 'number',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'minimum': 0,
                            'transition': true,
                            'units': 'line widths',
                            'requires': [{ '!': 'line-pattern' }]
                        },
                        'line-pattern': {
                            'type': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'transition': true
                        }
                    },
                    'paint_circle': {
                        'circle-radius': {
                            'type': 'number',
                            'default': 5,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'circle-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true
                        },
                        'circle-blur': {
                            'type': 'number',
                            'default': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true
                        },
                        'circle-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true
                        },
                        'circle-translate': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'circle-translate-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map',
                            'requires': ['circle-translate']
                        },
                        'circle-pitch-scale': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map'
                        },
                        'circle-pitch-alignment': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'viewport'
                        },
                        'circle-stroke-width': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'circle-stroke-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true
                        },
                        'circle-stroke-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true
                        }
                    },
                    'paint_heatmap': {
                        'heatmap-radius': {
                            'type': 'number',
                            'default': 30,
                            'minimum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels'
                        },
                        'heatmap-weight': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': false
                        },
                        'heatmap-intensity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': false,
                            'transition': true
                        },
                        'heatmap-color': {
                            'type': 'color',
                            'default': [
                                'interpolate',
                                ['linear'],
                                ['heatmap-density'],
                                0,
                                'rgba(0, 0, 255, 0)',
                                0.1,
                                'royalblue',
                                0.3,
                                'cyan',
                                0.5,
                                'lime',
                                0.7,
                                'yellow',
                                1,
                                'red'
                            ],
                            'function': 'interpolated',
                            'zoom-function': false,
                            'property-function': false,
                            'transition': false
                        },
                        'heatmap-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': false,
                            'transition': true
                        }
                    },
                    'paint_symbol': {
                        'icon-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': ['icon-image']
                        },
                        'icon-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': ['icon-image']
                        },
                        'icon-halo-color': {
                            'type': 'color',
                            'default': 'rgba(0, 0, 0, 0)',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': ['icon-image']
                        },
                        'icon-halo-width': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels',
                            'requires': ['icon-image']
                        },
                        'icon-halo-blur': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels',
                            'requires': ['icon-image']
                        },
                        'icon-translate': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'pixels',
                            'requires': ['icon-image']
                        },
                        'icon-translate-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map',
                            'requires': [
                                'icon-image',
                                'icon-translate'
                            ]
                        },
                        'text-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': ['text-field']
                        },
                        'text-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': ['text-field']
                        },
                        'text-halo-color': {
                            'type': 'color',
                            'default': 'rgba(0, 0, 0, 0)',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'requires': ['text-field']
                        },
                        'text-halo-width': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels',
                            'requires': ['text-field']
                        },
                        'text-halo-blur': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'property-function': true,
                            'transition': true,
                            'units': 'pixels',
                            'requires': ['text-field']
                        },
                        'text-translate': {
                            'type': 'array',
                            'value': 'number',
                            'length': 2,
                            'default': [
                                0,
                                0
                            ],
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'pixels',
                            'requires': ['text-field']
                        },
                        'text-translate-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'map',
                            'requires': [
                                'text-field',
                                'text-translate'
                            ]
                        }
                    },
                    'paint_raster': {
                        'raster-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        },
                        'raster-hue-rotate': {
                            'type': 'number',
                            'default': 0,
                            'period': 360,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'units': 'degrees'
                        },
                        'raster-brightness-min': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'default': 0,
                            'minimum': 0,
                            'maximum': 1,
                            'transition': true
                        },
                        'raster-brightness-max': {
                            'type': 'number',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'transition': true
                        },
                        'raster-saturation': {
                            'type': 'number',
                            'default': 0,
                            'minimum': -1,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        },
                        'raster-contrast': {
                            'type': 'number',
                            'default': 0,
                            'minimum': -1,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        },
                        'raster-fade-duration': {
                            'type': 'number',
                            'default': 300,
                            'minimum': 0,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': false,
                            'units': 'milliseconds'
                        }
                    },
                    'paint_hillshade': {
                        'hillshade-illumination-direction': {
                            'type': 'number',
                            'default': 335,
                            'minimum': 0,
                            'maximum': 359,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': false
                        },
                        'hillshade-illumination-anchor': {
                            'type': 'enum',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'values': {
                                'map': {},
                                'viewport': {}
                            },
                            'default': 'viewport'
                        },
                        'hillshade-exaggeration': {
                            'type': 'number',
                            'default': 0.5,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        },
                        'hillshade-shadow-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        },
                        'hillshade-highlight-color': {
                            'type': 'color',
                            'default': '#FFFFFF',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        },
                        'hillshade-accent-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        }
                    },
                    'paint_background': {
                        'background-color': {
                            'type': 'color',
                            'default': '#000000',
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true,
                            'requires': [{ '!': 'background-pattern' }]
                        },
                        'background-pattern': {
                            'type': 'string',
                            'function': 'piecewise-constant',
                            'zoom-function': true,
                            'transition': true
                        },
                        'background-opacity': {
                            'type': 'number',
                            'default': 1,
                            'minimum': 0,
                            'maximum': 1,
                            'function': 'interpolated',
                            'zoom-function': true,
                            'transition': true
                        }
                    },
                    'transition': {
                        'duration': {
                            'type': 'number',
                            'default': 300,
                            'minimum': 0,
                            'units': 'milliseconds'
                        },
                        'delay': {
                            'type': 'number',
                            'default': 0,
                            'minimum': 0,
                            'units': 'milliseconds'
                        }
                    }
                };
            },
            {}
        ],
        153: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('csscolorparser'), parseCSSColor = ref.parseCSSColor, Color = function (r, o, t, e) {
                        void 0 === e && (e = 1), this.r = r, this.g = o, this.b = t, this.a = e;
                    };
                Color.parse = function (r) {
                    if (r) {
                        if (r instanceof Color) {
                            return r;
                        }
                        if ('string' == typeof r) {
                            var o = parseCSSColor(r);
                            if (o) {
                                return new Color(o[0] / 255 * o[3], o[1] / 255 * o[3], o[2] / 255 * o[3], o[3]);
                            }
                        }
                    }
                }, Color.prototype.toString = function () {
                    var r = this, o = function (o) {
                            return Math.round(255 * o / r.a);
                        };
                    return 'rgba(' + [
                        this.r,
                        this.g,
                        this.b
                    ].map(o).concat(this.a).join(',') + ')';
                }, Color.black = new Color(0, 0, 0, 1), Color.white = new Color(1, 1, 1, 1), Color.transparent = new Color(0, 0, 0, 0), module.exports = Color;
            },
            { 'csscolorparser': 13 }
        ],
        154: [
            function (_dereq_, module, exports) {
                'use strict';
                function xyz2lab(a) {
                    return a > t3 ? Math.pow(a, 1 / 3) : a / t2 + t0;
                }
                function lab2xyz(a) {
                    return a > t1 ? a * a * a : t2 * (a - t0);
                }
                function xyz2rgb(a) {
                    return 255 * (a <= 0.0031308 ? 12.92 * a : 1.055 * Math.pow(a, 1 / 2.4) - 0.055);
                }
                function rgb2xyz(a) {
                    return a /= 255, a <= 0.04045 ? a / 12.92 : Math.pow((a + 0.055) / 1.055, 2.4);
                }
                function rgbToLab(a) {
                    var r = rgb2xyz(a.r), t = rgb2xyz(a.g), e = rgb2xyz(a.b), n = xyz2lab((0.4124564 * r + 0.3575761 * t + 0.1804375 * e) / Xn), l = xyz2lab((0.2126729 * r + 0.7151522 * t + 0.072175 * e) / Yn);
                    return {
                        l: 116 * l - 16,
                        a: 500 * (n - l),
                        b: 200 * (l - xyz2lab((0.0193339 * r + 0.119192 * t + 0.9503041 * e) / Zn)),
                        alpha: a.a
                    };
                }
                function labToRgb(a) {
                    var r = (a.l + 16) / 116, t = isNaN(a.a) ? r : r + a.a / 500, e = isNaN(a.b) ? r : r - a.b / 200;
                    return r = Yn * lab2xyz(r), t = Xn * lab2xyz(t), e = Zn * lab2xyz(e), new Color(xyz2rgb(3.2404542 * t - 1.5371385 * r - 0.4985314 * e), xyz2rgb(-0.969266 * t + 1.8760108 * r + 0.041556 * e), xyz2rgb(0.0556434 * t - 0.2040259 * r + 1.0572252 * e), a.alpha);
                }
                function interpolateLab(a, r, t) {
                    return {
                        l: interpolateNumber(a.l, r.l, t),
                        a: interpolateNumber(a.a, r.a, t),
                        b: interpolateNumber(a.b, r.b, t),
                        alpha: interpolateNumber(a.alpha, r.alpha, t)
                    };
                }
                function rgbToHcl(a) {
                    var r = rgbToLab(a), t = r.l, e = r.a, n = r.b, l = Math.atan2(n, e) * rad2deg;
                    return {
                        h: l < 0 ? l + 360 : l,
                        c: Math.sqrt(e * e + n * n),
                        l: t,
                        alpha: a.a
                    };
                }
                function hclToRgb(a) {
                    var r = a.h * deg2rad, t = a.c;
                    return labToRgb({
                        l: a.l,
                        a: Math.cos(r) * t,
                        b: Math.sin(r) * t,
                        alpha: a.alpha
                    });
                }
                function interpolateHue(a, r, t) {
                    var e = r - a;
                    return a + t * (e > 180 || e < -180 ? e - 360 * Math.round(e / 360) : e);
                }
                function interpolateHcl(a, r, t) {
                    return {
                        h: interpolateHue(a.h, r.h, t),
                        c: interpolateNumber(a.c, r.c, t),
                        l: interpolateNumber(a.l, r.l, t),
                        alpha: interpolateNumber(a.alpha, r.alpha, t)
                    };
                }
                var Color = _dereq_('./color'), interpolateNumber = _dereq_('./interpolate').number, Xn = 0.95047, Yn = 1, Zn = 1.08883, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1, deg2rad = Math.PI / 180, rad2deg = 180 / Math.PI;
                module.exports = {
                    lab: {
                        forward: rgbToLab,
                        reverse: labToRgb,
                        interpolate: interpolateLab
                    },
                    hcl: {
                        forward: rgbToHcl,
                        reverse: hclToRgb,
                        interpolate: interpolateHcl
                    }
                };
            },
            {
                './color': 153,
                './interpolate': 158
            }
        ],
        155: [
            function (_dereq_, module, exports) {
                'use strict';
                function deepEqual(e, r) {
                    if (Array.isArray(e)) {
                        if (!Array.isArray(r) || e.length !== r.length) {
                            return !1;
                        }
                        for (var t = 0; t < e.length; t++) {
                            if (!deepEqual(e[t], r[t])) {
                                return !1;
                            }
                        }
                        return !0;
                    }
                    if ('object' == typeof e && null !== e && null !== r) {
                        if ('object' != typeof r) {
                            return !1;
                        }
                        if (Object.keys(e).length !== Object.keys(r).length) {
                            return !1;
                        }
                        for (var n in e) {
                            if (!deepEqual(e[n], r[n])) {
                                return !1;
                            }
                        }
                        return !0;
                    }
                    return e === r;
                }
                module.exports = deepEqual;
            },
            {}
        ],
        156: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = function (r) {
                    var arguments$1 = arguments;
                    for (var t = [], e = arguments.length - 1; e-- > 0;) {
                        t[e] = arguments$1[e + 1];
                    }
                    for (var n = 0, o = t; n < o.length; n += 1) {
                        var a = o[n];
                        for (var f in a) {
                            r[f] = a[f];
                        }
                    }
                    return r;
                };
            },
            {}
        ],
        157: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = function (n) {
                    return n instanceof Number ? 'number' : n instanceof String ? 'string' : n instanceof Boolean ? 'boolean' : Array.isArray(n) ? 'array' : null === n ? 'null' : typeof n;
                };
            },
            {}
        ],
        158: [
            function (_dereq_, module, exports) {
                'use strict';
                function number(r, n, u) {
                    return r * (1 - u) + n * u;
                }
                function color(r, n, u) {
                    return new Color(number(r.r, n.r, u), number(r.g, n.g, u), number(r.b, n.b, u), number(r.a, n.a, u));
                }
                function array(r, n, u) {
                    return r.map(function (r, e) {
                        return number(r, n[e], u);
                    });
                }
                var Color = _dereq_('./color');
                module.exports = {
                    number: number,
                    color: color,
                    array: array
                };
            },
            { './color': 153 }
        ],
        159: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = [
                    'type',
                    'source',
                    'source-layer',
                    'minzoom',
                    'maxzoom',
                    'filter',
                    'layout'
                ];
            },
            {}
        ],
        160: [
            function (_dereq_, module, exports) {
                'use strict';
                function success(r) {
                    return {
                        result: 'success',
                        value: r
                    };
                }
                function error(r) {
                    return {
                        result: 'error',
                        value: r
                    };
                }
                module.exports = {
                    success: success,
                    error: error
                };
            },
            {}
        ],
        161: [
            function (_dereq_, module, exports) {
                'use strict';
                function unbundle(e) {
                    return e instanceof Number || e instanceof String || e instanceof Boolean ? e.valueOf() : e;
                }
                function deepUnbundle(e) {
                    return Array.isArray(e) ? e.map(deepUnbundle) : unbundle(e);
                }
                module.exports = unbundle, module.exports.deep = deepUnbundle;
            },
            {}
        ],
        162: [
            function (_dereq_, module, exports) {
                'use strict';
                var extend = _dereq_('../util/extend'), unbundle = _dereq_('../util/unbundle_jsonlint'), ref = _dereq_('../expression'), isExpression = ref.isExpression, ref$1 = _dereq_('../function'), isFunction = ref$1.isFunction;
                module.exports = function (e) {
                    var r = _dereq_('./validate_function'), i = _dereq_('./validate_expression'), t = _dereq_('./validate_object'), n = {
                            '*': function () {
                                return [];
                            },
                            array: _dereq_('./validate_array'),
                            boolean: _dereq_('./validate_boolean'),
                            number: _dereq_('./validate_number'),
                            color: _dereq_('./validate_color'),
                            constants: _dereq_('./validate_constants'),
                            enum: _dereq_('./validate_enum'),
                            filter: _dereq_('./validate_filter'),
                            function: _dereq_('./validate_function'),
                            layer: _dereq_('./validate_layer'),
                            object: _dereq_('./validate_object'),
                            source: _dereq_('./validate_source'),
                            light: _dereq_('./validate_light'),
                            string: _dereq_('./validate_string')
                        }, u = e.value, a = e.valueSpec, l = e.styleSpec;
                    return a.function && isFunction(unbundle(u)) ? r(e) : a.function && isExpression(unbundle.deep(u)) ? i(e) : a.type && n[a.type] ? n[a.type](e) : t(extend({}, e, { valueSpec: a.type ? l[a.type] : a }));
                };
            },
            {
                '../expression': 139,
                '../function': 149,
                '../util/extend': 156,
                '../util/unbundle_jsonlint': 161,
                './validate_array': 163,
                './validate_boolean': 164,
                './validate_color': 165,
                './validate_constants': 166,
                './validate_enum': 167,
                './validate_expression': 168,
                './validate_filter': 169,
                './validate_function': 170,
                './validate_layer': 172,
                './validate_light': 174,
                './validate_number': 175,
                './validate_object': 176,
                './validate_source': 179,
                './validate_string': 180
            }
        ],
        163: [
            function (_dereq_, module, exports) {
                'use strict';
                var getType = _dereq_('../util/get_type'), validate = _dereq_('./validate'), ValidationError = _dereq_('../error/validation_error');
                module.exports = function (e) {
                    var r = e.value, t = e.valueSpec, a = e.style, n = e.styleSpec, l = e.key, i = e.arrayElementValidator || validate;
                    if ('array' !== getType(r)) {
                        return [new ValidationError(l, r, 'array expected, ' + getType(r) + ' found')];
                    }
                    if (t.length && r.length !== t.length) {
                        return [new ValidationError(l, r, 'array length ' + t.length + ' expected, length ' + r.length + ' found')];
                    }
                    if (t['min-length'] && r.length < t['min-length']) {
                        return [new ValidationError(l, r, 'array length at least ' + t['min-length'] + ' expected, length ' + r.length + ' found')];
                    }
                    var o = { type: t.value };
                    n.$version < 7 && (o.function = t.function), 'object' === getType(t.value) && (o = t.value);
                    for (var u = [], g = 0; g < r.length; g++) {
                        u = u.concat(i({
                            array: r,
                            arrayIndex: g,
                            value: r[g],
                            valueSpec: o,
                            style: a,
                            styleSpec: n,
                            key: l + '[' + g + ']'
                        }));
                    }
                    return u;
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157,
                './validate': 162
            }
        ],
        164: [
            function (_dereq_, module, exports) {
                'use strict';
                var getType = _dereq_('../util/get_type'), ValidationError = _dereq_('../error/validation_error');
                module.exports = function (e) {
                    var r = e.value, o = e.key, t = getType(r);
                    return 'boolean' !== t ? [new ValidationError(o, r, 'boolean expected, ' + t + ' found')] : [];
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157
            }
        ],
        165: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), getType = _dereq_('../util/get_type'), parseCSSColor = _dereq_('csscolorparser').parseCSSColor;
                module.exports = function (r) {
                    var e = r.key, o = r.value, t = getType(o);
                    return 'string' !== t ? [new ValidationError(e, o, 'color expected, ' + t + ' found')] : null === parseCSSColor(o) ? [new ValidationError(e, o, 'color expected, "' + o + '" found')] : [];
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157,
                'csscolorparser': 13
            }
        ],
        166: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error');
                module.exports = function (r) {
                    var e = r.key, a = r.value;
                    return a ? [new ValidationError(e, a, 'constants have been deprecated as of v8')] : [];
                };
            },
            { '../error/validation_error': 122 }
        ],
        167: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), unbundle = _dereq_('../util/unbundle_jsonlint');
                module.exports = function (e) {
                    var r = e.key, n = e.value, u = e.valueSpec, i = [];
                    return Array.isArray(u.values) ? -1 === u.values.indexOf(unbundle(n)) && i.push(new ValidationError(r, n, 'expected one of [' + u.values.join(', ') + '], ' + JSON.stringify(n) + ' found')) : -1 === Object.keys(u.values).indexOf(unbundle(n)) && i.push(new ValidationError(r, n, 'expected one of [' + Object.keys(u.values).join(', ') + '], ' + JSON.stringify(n) + ' found')), i;
                };
            },
            {
                '../error/validation_error': 122,
                '../util/unbundle_jsonlint': 161
            }
        ],
        168: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), ref = _dereq_('../expression'), createExpression = ref.createExpression, createPropertyExpression = ref.createPropertyExpression, unbundle = _dereq_('../util/unbundle_jsonlint');
                module.exports = function (e) {
                    var r = ('property' === e.expressionContext ? createPropertyExpression : createExpression)(unbundle.deep(e.value), e.valueSpec);
                    return 'error' === r.result ? r.value.map(function (r) {
                        return new ValidationError('' + e.key + r.key, e.value, r.message);
                    }) : 'property' === e.expressionContext && 'text-font' === e.propertyKey && -1 !== r.value._styleExpression.expression.possibleOutputs().indexOf(void 0) ? [new ValidationError(e.key, e.value, 'Invalid data expression for "text-font". Output values must be contained as literals within the expression.')] : [];
                };
            },
            {
                '../error/validation_error': 122,
                '../expression': 139,
                '../util/unbundle_jsonlint': 161
            }
        ],
        169: [
            function (_dereq_, module, exports) {
                'use strict';
                function validateNonExpressionFilter(e) {
                    var r = e.value, t = e.key;
                    if ('array' !== getType(r)) {
                        return [new ValidationError(t, r, 'array expected, ' + getType(r) + ' found')];
                    }
                    var a, n = e.styleSpec, i = [];
                    if (r.length < 1) {
                        return [new ValidationError(t, r, 'filter array must have at least 1 element')];
                    }
                    switch (i = i.concat(validateEnum({
                            key: t + '[0]',
                            value: r[0],
                            valueSpec: n.filter_operator,
                            style: e.style,
                            styleSpec: e.styleSpec
                        })), unbundle(r[0])) {
                    case '<':
                    case '<=':
                    case '>':
                    case '>=':
                        r.length >= 2 && '$type' === unbundle(r[1]) && i.push(new ValidationError(t, r, '"$type" cannot be use with operator "' + r[0] + '"'));
                    case '==':
                    case '!=':
                        3 !== r.length && i.push(new ValidationError(t, r, 'filter array for operator "' + r[0] + '" must have 3 elements'));
                    case 'in':
                    case '!in':
                        r.length >= 2 && 'string' !== (a = getType(r[1])) && i.push(new ValidationError(t + '[1]', r[1], 'string expected, ' + a + ' found'));
                        for (var l = 2; l < r.length; l++) {
                            a = getType(r[l]), '$type' === unbundle(r[1]) ? i = i.concat(validateEnum({
                                key: t + '[' + l + ']',
                                value: r[l],
                                valueSpec: n.geometry_type,
                                style: e.style,
                                styleSpec: e.styleSpec
                            })) : 'string' !== a && 'number' !== a && 'boolean' !== a && i.push(new ValidationError(t + '[' + l + ']', r[l], 'string, number, or boolean expected, ' + a + ' found'));
                        }
                        break;
                    case 'any':
                    case 'all':
                    case 'none':
                        for (var s = 1; s < r.length; s++) {
                            i = i.concat(validateNonExpressionFilter({
                                key: t + '[' + s + ']',
                                value: r[s],
                                style: e.style,
                                styleSpec: e.styleSpec
                            }));
                        }
                        break;
                    case 'has':
                    case '!has':
                        a = getType(r[1]), 2 !== r.length ? i.push(new ValidationError(t, r, 'filter array for "' + r[0] + '" operator must have 2 elements')) : 'string' !== a && i.push(new ValidationError(t + '[1]', r[1], 'string expected, ' + a + ' found'));
                    }
                    return i;
                }
                var ValidationError = _dereq_('../error/validation_error'), validateExpression = _dereq_('./validate_expression'), validateEnum = _dereq_('./validate_enum'), getType = _dereq_('../util/get_type'), unbundle = _dereq_('../util/unbundle_jsonlint'), extend = _dereq_('../util/extend'), ref = _dereq_('../feature_filter'), isExpressionFilter = ref.isExpressionFilter;
                module.exports = function (e) {
                    return isExpressionFilter(unbundle.deep(e.value)) ? validateExpression(extend({}, e, {
                        expressionContext: 'filter',
                        valueSpec: { value: 'boolean' }
                    })) : validateNonExpressionFilter(e);
                };
            },
            {
                '../error/validation_error': 122,
                '../feature_filter': 148,
                '../util/extend': 156,
                '../util/get_type': 157,
                '../util/unbundle_jsonlint': 161,
                './validate_enum': 167,
                './validate_expression': 168
            }
        ],
        170: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), getType = _dereq_('../util/get_type'), validate = _dereq_('./validate'), validateObject = _dereq_('./validate_object'), validateArray = _dereq_('./validate_array'), validateNumber = _dereq_('./validate_number'), unbundle = _dereq_('../util/unbundle_jsonlint');
                module.exports = function (e) {
                    function t(e) {
                        if ('identity' === p) {
                            return [new ValidationError(e.key, e.value, 'identity function may not have a "stops" property')];
                        }
                        var t = [], a = e.value;
                        return t = t.concat(validateArray({
                            key: e.key,
                            value: a,
                            valueSpec: e.valueSpec,
                            style: e.style,
                            styleSpec: e.styleSpec,
                            arrayElementValidator: r
                        })), 'array' === getType(a) && 0 === a.length && t.push(new ValidationError(e.key, a, 'array must have at least one stop')), t;
                    }
                    function r(e) {
                        var t = [], r = e.value, o = e.key;
                        if ('array' !== getType(r)) {
                            return [new ValidationError(o, r, 'array expected, ' + getType(r) + ' found')];
                        }
                        if (2 !== r.length) {
                            return [new ValidationError(o, r, 'array length 2 expected, length ' + r.length + ' found')];
                        }
                        if (d) {
                            if ('object' !== getType(r[0])) {
                                return [new ValidationError(o, r, 'object expected, ' + getType(r[0]) + ' found')];
                            }
                            if (void 0 === r[0].zoom) {
                                return [new ValidationError(o, r, 'object stop key must have zoom')];
                            }
                            if (void 0 === r[0].value) {
                                return [new ValidationError(o, r, 'object stop key must have value')];
                            }
                            if (l && l > unbundle(r[0].zoom)) {
                                return [new ValidationError(o, r[0].zoom, 'stop zoom values must appear in ascending order')];
                            }
                            unbundle(r[0].zoom) !== l && (l = unbundle(r[0].zoom), i = void 0, s = {}), t = t.concat(validateObject({
                                key: o + '[0]',
                                value: r[0],
                                valueSpec: { zoom: {} },
                                style: e.style,
                                styleSpec: e.styleSpec,
                                objectElementValidators: {
                                    zoom: validateNumber,
                                    value: a
                                }
                            }));
                        } else {
                            t = t.concat(a({
                                key: o + '[0]',
                                value: r[0],
                                valueSpec: {},
                                style: e.style,
                                styleSpec: e.styleSpec
                            }, r));
                        }
                        return t.concat(validate({
                            key: o + '[1]',
                            value: r[1],
                            valueSpec: u,
                            style: e.style,
                            styleSpec: e.styleSpec
                        }));
                    }
                    function a(e, t) {
                        var r = getType(e.value), a = unbundle(e.value), o = null !== e.value ? e.value : t;
                        if (n) {
                            if (r !== n) {
                                return [new ValidationError(e.key, o, r + ' stop domain type must match previous stop domain type ' + n)];
                            }
                        } else {
                            n = r;
                        }
                        if ('number' !== r && 'string' !== r && 'boolean' !== r) {
                            return [new ValidationError(e.key, o, 'stop domain value must be a number, string, or boolean')];
                        }
                        if ('number' !== r && 'categorical' !== p) {
                            var l = 'number expected, ' + r + ' found';
                            return u['property-function'] && void 0 === p && (l += '\nIf you intended to use a categorical function, specify `"type": "categorical"`.'), [new ValidationError(e.key, o, l)];
                        }
                        return 'categorical' !== p || 'number' !== r || isFinite(a) && Math.floor(a) === a ? 'categorical' !== p && 'number' === r && void 0 !== i && a < i ? [new ValidationError(e.key, o, 'stop domain values must appear in ascending order')] : (i = a, 'categorical' === p && a in s ? [new ValidationError(e.key, o, 'stop domain values must be unique')] : (s[a] = !0, [])) : [new ValidationError(e.key, o, 'integer expected, found ' + a)];
                    }
                    function o(e) {
                        return validate({
                            key: e.key,
                            value: e.value,
                            valueSpec: u,
                            style: e.style,
                            styleSpec: e.styleSpec
                        });
                    }
                    var n, i, l, u = e.valueSpec, p = unbundle(e.value.type), s = {}, y = 'categorical' !== p && void 0 === e.value.property, c = !y, d = 'array' === getType(e.value.stops) && 'array' === getType(e.value.stops[0]) && 'object' === getType(e.value.stops[0][0]), v = validateObject({
                            key: e.key,
                            value: e.value,
                            valueSpec: e.styleSpec.function,
                            style: e.style,
                            styleSpec: e.styleSpec,
                            objectElementValidators: {
                                stops: t,
                                default: o
                            }
                        });
                    return 'identity' === p && y && v.push(new ValidationError(e.key, e.value, 'missing required property "property"')), 'identity' === p || e.value.stops || v.push(new ValidationError(e.key, e.value, 'missing required property "stops"')), 'exponential' === p && 'piecewise-constant' === e.valueSpec.function && v.push(new ValidationError(e.key, e.value, 'exponential functions not supported')), e.styleSpec.$version >= 8 && (c && !e.valueSpec['property-function'] ? v.push(new ValidationError(e.key, e.value, 'property functions not supported')) : y && !e.valueSpec['zoom-function'] && 'heatmap-color' !== e.objectKey && v.push(new ValidationError(e.key, e.value, 'zoom functions not supported'))), 'categorical' !== p && !d || void 0 !== e.value.property || v.push(new ValidationError(e.key, e.value, '"property" property is required')), v;
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157,
                '../util/unbundle_jsonlint': 161,
                './validate': 162,
                './validate_array': 163,
                './validate_number': 175,
                './validate_object': 176
            }
        ],
        171: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), validateString = _dereq_('./validate_string');
                module.exports = function (r) {
                    var e = r.value, t = r.key, a = validateString(r);
                    return a.length ? a : (-1 === e.indexOf('{fontstack}') && a.push(new ValidationError(t, e, '"glyphs" url must include a "{fontstack}" token')), -1 === e.indexOf('{range}') && a.push(new ValidationError(t, e, '"glyphs" url must include a "{range}" token')), a);
                };
            },
            {
                '../error/validation_error': 122,
                './validate_string': 180
            }
        ],
        172: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), unbundle = _dereq_('../util/unbundle_jsonlint'), validateObject = _dereq_('./validate_object'), validateFilter = _dereq_('./validate_filter'), validatePaintProperty = _dereq_('./validate_paint_property'), validateLayoutProperty = _dereq_('./validate_layout_property'), validateSpec = _dereq_('./validate'), extend = _dereq_('../util/extend');
                module.exports = function (e) {
                    var r = [], t = e.value, a = e.key, l = e.style, i = e.styleSpec;
                    t.type || t.ref || r.push(new ValidationError(a, t, 'either "type" or "ref" is required'));
                    var u = unbundle(t.type), n = unbundle(t.ref);
                    if (t.id) {
                        for (var o = unbundle(t.id), s = 0; s < e.arrayIndex; s++) {
                            var y = l.layers[s];
                            unbundle(y.id) === o && r.push(new ValidationError(a, t.id, 'duplicate layer id "' + t.id + '", previously used at line ' + y.id.__line__));
                        }
                    }
                    if ('ref' in t) {
                        [
                            'type',
                            'source',
                            'source-layer',
                            'filter',
                            'layout'
                        ].forEach(function (e) {
                            e in t && r.push(new ValidationError(a, t[e], '"' + e + '" is prohibited for ref layers'));
                        });
                        var d;
                        l.layers.forEach(function (e) {
                            unbundle(e.id) === n && (d = e);
                        }), d ? d.ref ? r.push(new ValidationError(a, t.ref, 'ref cannot reference another ref layer')) : u = unbundle(d.type) : r.push(new ValidationError(a, t.ref, 'ref layer "' + n + '" not found'));
                    } else if ('background' !== u) {
                        if (t.source) {
                            var c = l.sources && l.sources[t.source], p = c && unbundle(c.type);
                            c ? 'vector' === p && 'raster' === u ? r.push(new ValidationError(a, t.source, 'layer "' + t.id + '" requires a raster source')) : 'raster' === p && 'raster' !== u ? r.push(new ValidationError(a, t.source, 'layer "' + t.id + '" requires a vector source')) : 'vector' !== p || t['source-layer'] ? 'raster-dem' === p && 'hillshade' !== u && r.push(new ValidationError(a, t.source, 'raster-dem source can only be used with layer type \'hillshade\'.')) : r.push(new ValidationError(a, t, 'layer "' + t.id + '" must specify a "source-layer"')) : r.push(new ValidationError(a, t.source, 'source "' + t.source + '" not found'));
                        } else {
                            r.push(new ValidationError(a, t, 'missing required property "source"'));
                        }
                    }
                    return r = r.concat(validateObject({
                        key: a,
                        value: t,
                        valueSpec: i.layer,
                        style: e.style,
                        styleSpec: e.styleSpec,
                        objectElementValidators: {
                            '*': function () {
                                return [];
                            },
                            type: function () {
                                return validateSpec({
                                    key: a + '.type',
                                    value: t.type,
                                    valueSpec: i.layer.type,
                                    style: e.style,
                                    styleSpec: e.styleSpec,
                                    object: t,
                                    objectKey: 'type'
                                });
                            },
                            filter: validateFilter,
                            layout: function (e) {
                                return validateObject({
                                    layer: t,
                                    key: e.key,
                                    value: e.value,
                                    style: e.style,
                                    styleSpec: e.styleSpec,
                                    objectElementValidators: {
                                        '*': function (e) {
                                            return validateLayoutProperty(extend({ layerType: u }, e));
                                        }
                                    }
                                });
                            },
                            paint: function (e) {
                                return validateObject({
                                    layer: t,
                                    key: e.key,
                                    value: e.value,
                                    style: e.style,
                                    styleSpec: e.styleSpec,
                                    objectElementValidators: {
                                        '*': function (e) {
                                            return validatePaintProperty(extend({ layerType: u }, e));
                                        }
                                    }
                                });
                            }
                        }
                    }));
                };
            },
            {
                '../error/validation_error': 122,
                '../util/extend': 156,
                '../util/unbundle_jsonlint': 161,
                './validate': 162,
                './validate_filter': 169,
                './validate_layout_property': 173,
                './validate_object': 176,
                './validate_paint_property': 177
            }
        ],
        173: [
            function (_dereq_, module, exports) {
                'use strict';
                var validateProperty = _dereq_('./validate_property');
                module.exports = function (r) {
                    return validateProperty(r, 'layout');
                };
            },
            { './validate_property': 178 }
        ],
        174: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), getType = _dereq_('../util/get_type'), validate = _dereq_('./validate');
                module.exports = function (e) {
                    var t = e.value, r = e.styleSpec, a = r.light, i = e.style, n = [], o = getType(t);
                    if (void 0 === t) {
                        return n;
                    }
                    if ('object' !== o) {
                        return n = n.concat([new ValidationError('light', t, 'object expected, ' + o + ' found')]);
                    }
                    for (var l in t) {
                        var c = l.match(/^(.*)-transition$/);
                        n = c && a[c[1]] && a[c[1]].transition ? n.concat(validate({
                            key: l,
                            value: t[l],
                            valueSpec: r.transition,
                            style: i,
                            styleSpec: r
                        })) : a[l] ? n.concat(validate({
                            key: l,
                            value: t[l],
                            valueSpec: a[l],
                            style: i,
                            styleSpec: r
                        })) : n.concat([new ValidationError(l, t[l], 'unknown property "' + l + '"')]);
                    }
                    return n;
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157,
                './validate': 162
            }
        ],
        175: [
            function (_dereq_, module, exports) {
                'use strict';
                var getType = _dereq_('../util/get_type'), ValidationError = _dereq_('../error/validation_error');
                module.exports = function (e) {
                    var r = e.key, i = e.value, m = e.valueSpec, a = getType(i);
                    return 'number' !== a ? [new ValidationError(r, i, 'number expected, ' + a + ' found')] : 'minimum' in m && i < m.minimum ? [new ValidationError(r, i, i + ' is less than the minimum value ' + m.minimum)] : 'maximum' in m && i > m.maximum ? [new ValidationError(r, i, i + ' is greater than the maximum value ' + m.maximum)] : [];
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157
            }
        ],
        176: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), getType = _dereq_('../util/get_type'), validateSpec = _dereq_('./validate');
                module.exports = function (e) {
                    var r = e.key, t = e.value, i = e.valueSpec || {}, a = e.objectElementValidators || {}, o = e.style, l = e.styleSpec, n = [], u = getType(t);
                    if ('object' !== u) {
                        return [new ValidationError(r, t, 'object expected, ' + u + ' found')];
                    }
                    for (var d in t) {
                        var p = d.split('.')[0], c = i[p] || i['*'], v = void 0;
                        if (a[p]) {
                            v = a[p];
                        } else if (i[p]) {
                            v = validateSpec;
                        } else if (a['*']) {
                            v = a['*'];
                        } else {
                            if (!i['*']) {
                                n.push(new ValidationError(r, t[d], 'unknown property "' + d + '"'));
                                continue;
                            }
                            v = validateSpec;
                        }
                        n = n.concat(v({
                            key: (r ? r + '.' : r) + d,
                            value: t[d],
                            valueSpec: c,
                            style: o,
                            styleSpec: l,
                            object: t,
                            objectKey: d
                        }, t));
                    }
                    for (var s in i) {
                        a[s] || i[s].required && void 0 === i[s].default && void 0 === t[s] && n.push(new ValidationError(r, t, 'missing required property "' + s + '"'));
                    }
                    return n;
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157,
                './validate': 162
            }
        ],
        177: [
            function (_dereq_, module, exports) {
                'use strict';
                var validateProperty = _dereq_('./validate_property');
                module.exports = function (r) {
                    return validateProperty(r, 'paint');
                };
            },
            { './validate_property': 178 }
        ],
        178: [
            function (_dereq_, module, exports) {
                'use strict';
                var validate = _dereq_('./validate'), ValidationError = _dereq_('../error/validation_error'), getType = _dereq_('../util/get_type'), ref = _dereq_('../function'), isFunction = ref.isFunction, unbundle = _dereq_('../util/unbundle_jsonlint');
                module.exports = function (e, t) {
                    var r = e.key, n = e.style, i = e.styleSpec, o = e.value, a = e.objectKey, u = i[t + '_' + e.layerType];
                    if (!u) {
                        return [];
                    }
                    var p = a.match(/^(.*)-transition$/);
                    if ('paint' === t && p && u[p[1]] && u[p[1]].transition) {
                        return validate({
                            key: r,
                            value: o,
                            valueSpec: i.transition,
                            style: n,
                            styleSpec: i
                        });
                    }
                    var l = e.valueSpec || u[a];
                    if (!l) {
                        return [new ValidationError(r, o, 'unknown property "' + a + '"')];
                    }
                    var y;
                    if ('string' === getType(o) && l['property-function'] && !l.tokens && (y = /^{([^}]+)}$/.exec(o))) {
                        return [new ValidationError(r, o, '"' + a + '" does not support interpolation syntax\nUse an identity property function instead: `{ "type": "identity", "property": ' + JSON.stringify(y[1]) + ' }`.')];
                    }
                    var s = [];
                    return 'symbol' === e.layerType && ('text-field' === a && n && !n.glyphs && s.push(new ValidationError(r, o, 'use of "text-field" requires a style "glyphs" property')), 'text-font' === a && isFunction(unbundle.deep(o)) && 'identity' === unbundle(o.type) && s.push(new ValidationError(r, o, '"text-font" does not support identity functions'))), s.concat(validate({
                        key: e.key,
                        value: o,
                        valueSpec: l,
                        style: n,
                        styleSpec: i,
                        expressionContext: 'property',
                        propertyKey: a
                    }));
                };
            },
            {
                '../error/validation_error': 122,
                '../function': 149,
                '../util/get_type': 157,
                '../util/unbundle_jsonlint': 161,
                './validate': 162
            }
        ],
        179: [
            function (_dereq_, module, exports) {
                'use strict';
                var ValidationError = _dereq_('../error/validation_error'), unbundle = _dereq_('../util/unbundle_jsonlint'), validateObject = _dereq_('./validate_object'), validateEnum = _dereq_('./validate_enum');
                module.exports = function (e) {
                    var a = e.value, r = e.key, t = e.styleSpec, l = e.style;
                    if (!a.type) {
                        return [new ValidationError(r, a, '"type" is required')];
                    }
                    var u = unbundle(a.type), s = [];
                    switch (u) {
                    case 'vector':
                    case 'raster':
                    case 'raster-dem':
                        if (s = s.concat(validateObject({
                                key: r,
                                value: a,
                                valueSpec: t['source_' + u.replace('-', '_')],
                                style: e.style,
                                styleSpec: t
                            })), 'url' in a) {
                            for (var c in a) {
                                [
                                    'type',
                                    'url',
                                    'tileSize'
                                ].indexOf(c) < 0 && s.push(new ValidationError(r + '.' + c, a[c], 'a source with a "url" property may not include a "' + c + '" property'));
                            }
                        }
                        return s;
                    case 'geojson':
                        return validateObject({
                            key: r,
                            value: a,
                            valueSpec: t.source_geojson,
                            style: l,
                            styleSpec: t
                        });
                    case 'video':
                        return validateObject({
                            key: r,
                            value: a,
                            valueSpec: t.source_video,
                            style: l,
                            styleSpec: t
                        });
                    case 'image':
                        return validateObject({
                            key: r,
                            value: a,
                            valueSpec: t.source_image,
                            style: l,
                            styleSpec: t
                        });
                    case 'canvas':
                        return validateObject({
                            key: r,
                            value: a,
                            valueSpec: t.source_canvas,
                            style: l,
                            styleSpec: t
                        });
                    default:
                        return validateEnum({
                            key: r + '.type',
                            value: a.type,
                            valueSpec: {
                                values: [
                                    'vector',
                                    'raster',
                                    'raster-dem',
                                    'geojson',
                                    'video',
                                    'image',
                                    'canvas'
                                ]
                            },
                            style: l,
                            styleSpec: t
                        });
                    }
                };
            },
            {
                '../error/validation_error': 122,
                '../util/unbundle_jsonlint': 161,
                './validate_enum': 167,
                './validate_object': 176
            }
        ],
        180: [
            function (_dereq_, module, exports) {
                'use strict';
                var getType = _dereq_('../util/get_type'), ValidationError = _dereq_('../error/validation_error');
                module.exports = function (r) {
                    var e = r.value, t = r.key, i = getType(e);
                    return 'string' !== i ? [new ValidationError(t, e, 'string expected, ' + i + ' found')] : [];
                };
            },
            {
                '../error/validation_error': 122,
                '../util/get_type': 157
            }
        ],
        181: [
            function (_dereq_, module, exports) {
                'use strict';
                function validateStyleMin(e, a) {
                    a = a || latestStyleSpec;
                    var t = [];
                    return t = t.concat(validate({
                        key: '',
                        value: e,
                        valueSpec: a.$root,
                        styleSpec: a,
                        style: e,
                        objectElementValidators: {
                            glyphs: validateGlyphsURL,
                            '*': function () {
                                return [];
                            }
                        }
                    })), e.constants && (t = t.concat(validateConstants({
                        key: 'constants',
                        value: e.constants,
                        style: e,
                        styleSpec: a
                    }))), sortErrors(t);
                }
                function sortErrors(e) {
                    return [].concat(e).sort(function (e, a) {
                        return e.line - a.line;
                    });
                }
                function wrapCleanErrors(e) {
                    return function () {
                        return sortErrors(e.apply(this, arguments));
                    };
                }
                var validateConstants = _dereq_('./validate/validate_constants'), validate = _dereq_('./validate/validate'), latestStyleSpec = _dereq_('./reference/latest'), validateGlyphsURL = _dereq_('./validate/validate_glyphs_url');
                validateStyleMin.source = wrapCleanErrors(_dereq_('./validate/validate_source')), validateStyleMin.light = wrapCleanErrors(_dereq_('./validate/validate_light')), validateStyleMin.layer = wrapCleanErrors(_dereq_('./validate/validate_layer')), validateStyleMin.filter = wrapCleanErrors(_dereq_('./validate/validate_filter')), validateStyleMin.paintProperty = wrapCleanErrors(_dereq_('./validate/validate_paint_property')), validateStyleMin.layoutProperty = wrapCleanErrors(_dereq_('./validate/validate_layout_property')), module.exports = validateStyleMin;
            },
            {
                './reference/latest': 151,
                './validate/validate': 162,
                './validate/validate_constants': 166,
                './validate/validate_filter': 169,
                './validate/validate_glyphs_url': 171,
                './validate/validate_layer': 172,
                './validate/validate_layout_property': 173,
                './validate/validate_light': 174,
                './validate/validate_paint_property': 177,
                './validate/validate_source': 179
            }
        ],
        182: [
            function (_dereq_, module, exports) {
                'use strict';
                var ZoomHistory = _dereq_('./zoom_history'), EvaluationParameters = function (t, o) {
                        this.zoom = t, o ? (this.now = o.now, this.fadeDuration = o.fadeDuration, this.zoomHistory = o.zoomHistory, this.transition = o.transition) : (this.now = 0, this.fadeDuration = 0, this.zoomHistory = new ZoomHistory(), this.transition = {});
                    };
                EvaluationParameters.prototype.crossFadingFactor = function () {
                    return 0 === this.fadeDuration ? 1 : Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1);
                }, module.exports = EvaluationParameters;
            },
            { './zoom_history': 212 }
        ],
        183: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../style-spec/reference/latest'), util = _dereq_('../util/util'), Evented = _dereq_('../util/evented'), validateStyle = _dereq_('./validate_style'), ref = _dereq_('../util/util'), sphericalToCartesian = ref.sphericalToCartesian, Color = _dereq_('../style-spec/util/color'), interpolate = _dereq_('../style-spec/util/interpolate'), ref$1 = _dereq_('./properties'), Properties = ref$1.Properties, Transitionable = ref$1.Transitionable, Transitioning = ref$1.Transitioning, PossiblyEvaluated = ref$1.PossiblyEvaluated, DataConstantProperty = ref$1.DataConstantProperty, LightPositionProperty = function () {
                        this.specification = styleSpec.light.position;
                    };
                LightPositionProperty.prototype.possiblyEvaluate = function (t, e) {
                    return sphericalToCartesian(t.expression.evaluate(e));
                }, LightPositionProperty.prototype.interpolate = function (t, e, i) {
                    return {
                        x: interpolate.number(t.x, e.x, i),
                        y: interpolate.number(t.y, e.y, i),
                        z: interpolate.number(t.z, e.z, i)
                    };
                };
                var properties = new Properties({
                        anchor: new DataConstantProperty(styleSpec.light.anchor),
                        position: new LightPositionProperty(),
                        color: new DataConstantProperty(styleSpec.light.color),
                        intensity: new DataConstantProperty(styleSpec.light.intensity)
                    }), TRANSITION_SUFFIX = '-transition', Light = function (t) {
                        function e(e) {
                            t.call(this), this._transitionable = new Transitionable(properties), this.setLight(e), this._transitioning = this._transitionable.untransitioned();
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.getLight = function () {
                            return this._transitionable.serialize();
                        }, e.prototype.setLight = function (t) {
                            var e = this;
                            if (!this._validate(validateStyle.light, t)) {
                                for (var i in t) {
                                    var r = t[i];
                                    util.endsWith(i, TRANSITION_SUFFIX) ? e._transitionable.setTransition(i.slice(0, -TRANSITION_SUFFIX.length), r) : e._transitionable.setValue(i, r);
                                }
                            }
                        }, e.prototype.updateTransitions = function (t) {
                            this._transitioning = this._transitionable.transitioned(t, this._transitioning);
                        }, e.prototype.hasTransition = function () {
                            return this._transitioning.hasTransition();
                        }, e.prototype.recalculate = function (t) {
                            this.properties = this._transitioning.possiblyEvaluate(t);
                        }, e.prototype._validate = function (t, e) {
                            return validateStyle.emitErrors(this, t.call(validateStyle, util.extend({
                                value: e,
                                style: {
                                    glyphs: !0,
                                    sprite: !0
                                },
                                styleSpec: styleSpec
                            })));
                        }, e;
                    }(Evented);
                module.exports = Light;
            },
            {
                '../style-spec/reference/latest': 151,
                '../style-spec/util/color': 153,
                '../style-spec/util/interpolate': 158,
                '../util/evented': 260,
                '../util/util': 275,
                './properties': 188,
                './validate_style': 211
            }
        ],
        184: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/mapbox'), normalizeGlyphsURL = ref.normalizeGlyphsURL, ajax = _dereq_('../util/ajax'), parseGlyphPBF = _dereq_('./parse_glyph_pbf');
                module.exports = function (e, r, a, l, p) {
                    var i = 256 * r, s = i + 255, t = l(normalizeGlyphsURL(a).replace('{fontstack}', e).replace('{range}', i + '-' + s), ajax.ResourceType.Glyphs);
                    ajax.getArrayBuffer(t, function (e, r) {
                        if (e) {
                            p(e);
                        } else if (r) {
                            for (var a = {}, l = 0, i = parseGlyphPBF(r.data); l < i.length; l += 1) {
                                var s = i[l];
                                a[s.id] = s;
                            }
                            p(null, a);
                        }
                    });
                };
            },
            {
                '../util/ajax': 251,
                '../util/mapbox': 267,
                './parse_glyph_pbf': 186
            }
        ],
        185: [
            function (_dereq_, module, exports) {
                'use strict';
                var ajax = _dereq_('../util/ajax'), browser = _dereq_('../util/browser'), ref = _dereq_('../util/mapbox'), normalizeSpriteURL = ref.normalizeSpriteURL, ref$1 = _dereq_('../util/image'), RGBAImage = ref$1.RGBAImage;
                module.exports = function (e, i, r) {
                    function a() {
                        if (n) {
                            r(n);
                        } else if (t && o) {
                            var e = browser.getImageData(o), i = {};
                            for (var a in t) {
                                var u = t[a], g = u.width, l = u.height, x = u.x, m = u.y, p = u.sdf, f = u.pixelRatio, s = new RGBAImage({
                                        width: g,
                                        height: l
                                    });
                                RGBAImage.copy(e, s, {
                                    x: x,
                                    y: m
                                }, {
                                    x: 0,
                                    y: 0
                                }, {
                                    width: g,
                                    height: l
                                }), i[a] = {
                                    data: s,
                                    pixelRatio: f,
                                    sdf: p
                                };
                            }
                            r(null, i);
                        }
                    }
                    var t, o, n, u = browser.devicePixelRatio > 1 ? '@2x' : '';
                    ajax.getJSON(i(normalizeSpriteURL(e, u, '.json'), ajax.ResourceType.SpriteJSON), function (e, i) {
                        n || (n = e, t = i, a());
                    }), ajax.getImage(i(normalizeSpriteURL(e, u, '.png'), ajax.ResourceType.SpriteImage), function (e, i) {
                        n || (n = e, o = i, a());
                    });
                };
            },
            {
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/image': 263,
                '../util/mapbox': 267
            }
        ],
        186: [
            function (_dereq_, module, exports) {
                'use strict';
                function readFontstacks(e, a, r) {
                    1 === e && r.readMessage(readFontstack, a);
                }
                function readFontstack(e, a, r) {
                    if (3 === e) {
                        var t = r.readMessage(readGlyph, {}), d = t.id, i = t.bitmap, n = t.width, o = t.height, h = t.left, s = t.top, p = t.advance;
                        a.push({
                            id: d,
                            bitmap: new AlphaImage({
                                width: n + 2 * border,
                                height: o + 2 * border
                            }, i),
                            metrics: {
                                width: n,
                                height: o,
                                left: h,
                                top: s,
                                advance: p
                            }
                        });
                    }
                }
                function readGlyph(e, a, r) {
                    1 === e ? a.id = r.readVarint() : 2 === e ? a.bitmap = r.readBytes() : 3 === e ? a.width = r.readVarint() : 4 === e ? a.height = r.readVarint() : 5 === e ? a.left = r.readSVarint() : 6 === e ? a.top = r.readSVarint() : 7 === e && (a.advance = r.readVarint());
                }
                var ref = _dereq_('../util/image'), AlphaImage = ref.AlphaImage, Protobuf = _dereq_('pbf'), border = 3;
                module.exports = function (e) {
                    return new Protobuf(e).readFields(readFontstacks, []);
                }, module.exports.GLYPH_PBF_BORDER = border;
            },
            {
                '../util/image': 263,
                'pbf': 30
            }
        ],
        187: [
            function (_dereq_, module, exports) {
                'use strict';
                var browser = _dereq_('../util/browser'), Placement = _dereq_('../symbol/placement'), LayerPlacement = function () {
                        this._currentTileIndex = 0, this._seenCrossTileIDs = {};
                    };
                LayerPlacement.prototype.continuePlacement = function (e, n, t, r, o) {
                    for (var l = this; this._currentTileIndex < e.length;) {
                        var s = e[l._currentTileIndex];
                        if (n.placeLayerTile(r, s, t, l._seenCrossTileIDs), l._currentTileIndex++, o()) {
                            return !0;
                        }
                    }
                };
                var PauseablePlacement = function (e, n, t, r, o) {
                    this.placement = new Placement(e, o), this._currentPlacementIndex = n.length - 1, this._forceFullPlacement = t, this._showCollisionBoxes = r, this._done = !1;
                };
                PauseablePlacement.prototype.isDone = function () {
                    return this._done;
                }, PauseablePlacement.prototype.continuePlacement = function (e, n, t) {
                    for (var r = this, o = browser.now(), l = function () {
                                var e = browser.now() - o;
                                return !r._forceFullPlacement && e > 2;
                            }; this._currentPlacementIndex >= 0;) {
                        var s = e[r._currentPlacementIndex], a = n[s], i = r.placement.collisionIndex.transform.zoom;
                        if ('symbol' === a.type && (!a.minzoom || a.minzoom <= i) && (!a.maxzoom || a.maxzoom > i)) {
                            r._inProgressLayer || (r._inProgressLayer = new LayerPlacement());
                            if (r._inProgressLayer.continuePlacement(t[a.source], r.placement, r._showCollisionBoxes, a, l)) {
                                return;
                            }
                            delete r._inProgressLayer;
                        }
                        r._currentPlacementIndex--;
                    }
                    this._done = !0;
                }, PauseablePlacement.prototype.commit = function (e, n) {
                    return this.placement.commit(e, n), this.placement;
                }, module.exports = PauseablePlacement;
            },
            {
                '../symbol/placement': 223,
                '../util/browser': 252
            }
        ],
        188: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/util'), clone = ref.clone, extend = ref.extend, easeCubicInOut = ref.easeCubicInOut, interpolate = _dereq_('../style-spec/util/interpolate'), ref$1 = _dereq_('../style-spec/expression'), normalizePropertyExpression = ref$1.normalizePropertyExpression, Color = _dereq_('../style-spec/util/color'), ref$2 = _dereq_('../util/web_worker_transfer'), register = ref$2.register, PropertyValue = function (t, e) {
                        this.property = t, this.value = e, this.expression = normalizePropertyExpression(void 0 === e ? t.specification.default : e, t.specification);
                    };
                PropertyValue.prototype.isDataDriven = function () {
                    return 'source' === this.expression.kind || 'composite' === this.expression.kind;
                }, PropertyValue.prototype.possiblyEvaluate = function (t) {
                    return this.property.possiblyEvaluate(this, t);
                };
                var TransitionablePropertyValue = function (t) {
                    this.property = t, this.value = new PropertyValue(t, void 0);
                };
                TransitionablePropertyValue.prototype.transitioned = function (t, e) {
                    return new TransitioningPropertyValue(this.property, this.value, e, extend({}, t.transition, this.transition), t.now);
                }, TransitionablePropertyValue.prototype.untransitioned = function () {
                    return new TransitioningPropertyValue(this.property, this.value, null, {}, 0);
                };
                var Transitionable = function (t) {
                    this._properties = t, this._values = Object.create(t.defaultTransitionablePropertyValues);
                };
                Transitionable.prototype.getValue = function (t) {
                    return clone(this._values[t].value.value);
                }, Transitionable.prototype.setValue = function (t, e) {
                    this._values.hasOwnProperty(t) || (this._values[t] = new TransitionablePropertyValue(this._values[t].property)), this._values[t].value = new PropertyValue(this._values[t].property, null === e ? void 0 : clone(e));
                }, Transitionable.prototype.getTransition = function (t) {
                    return clone(this._values[t].transition);
                }, Transitionable.prototype.setTransition = function (t, e) {
                    this._values.hasOwnProperty(t) || (this._values[t] = new TransitionablePropertyValue(this._values[t].property)), this._values[t].transition = clone(e) || void 0;
                }, Transitionable.prototype.serialize = function () {
                    for (var t = this, e = {}, r = 0, a = Object.keys(t._values); r < a.length; r += 1) {
                        var o = a[r], i = t.getValue(o);
                        void 0 !== i && (e[o] = i);
                        var n = t.getTransition(o);
                        void 0 !== n && (e[o + '-transition'] = n);
                    }
                    return e;
                }, Transitionable.prototype.transitioned = function (t, e) {
                    for (var r = this, a = new Transitioning(this._properties), o = 0, i = Object.keys(r._values); o < i.length; o += 1) {
                        var n = i[o];
                        a._values[n] = r._values[n].transitioned(t, e._values[n]);
                    }
                    return a;
                }, Transitionable.prototype.untransitioned = function () {
                    for (var t = this, e = new Transitioning(this._properties), r = 0, a = Object.keys(t._values); r < a.length; r += 1) {
                        var o = a[r];
                        e._values[o] = t._values[o].untransitioned();
                    }
                    return e;
                };
                var TransitioningPropertyValue = function (t, e, r, a, o) {
                    this.property = t, this.value = e, this.begin = o + a.delay || 0, this.end = this.begin + a.duration || 0, t.specification.transition && (a.delay || a.duration) && (this.prior = r);
                };
                TransitioningPropertyValue.prototype.possiblyEvaluate = function (t) {
                    var e = t.now || 0, r = this.value.possiblyEvaluate(t), a = this.prior;
                    if (a) {
                        if (e > this.end) {
                            return this.prior = null, r;
                        }
                        if (this.value.isDataDriven()) {
                            return this.prior = null, r;
                        }
                        if (e < this.begin) {
                            return a.possiblyEvaluate(t);
                        }
                        var o = (e - this.begin) / (this.end - this.begin);
                        return this.property.interpolate(a.possiblyEvaluate(t), r, easeCubicInOut(o));
                    }
                    return r;
                };
                var Transitioning = function (t) {
                    this._properties = t, this._values = Object.create(t.defaultTransitioningPropertyValues);
                };
                Transitioning.prototype.possiblyEvaluate = function (t) {
                    for (var e = this, r = new PossiblyEvaluated(this._properties), a = 0, o = Object.keys(e._values); a < o.length; a += 1) {
                        var i = o[a];
                        r._values[i] = e._values[i].possiblyEvaluate(t);
                    }
                    return r;
                }, Transitioning.prototype.hasTransition = function () {
                    for (var t = this, e = 0, r = Object.keys(t._values); e < r.length; e += 1) {
                        var a = r[e];
                        if (t._values[a].prior) {
                            return !0;
                        }
                    }
                    return !1;
                };
                var Layout = function (t) {
                    this._properties = t, this._values = Object.create(t.defaultPropertyValues);
                };
                Layout.prototype.getValue = function (t) {
                    return clone(this._values[t].value);
                }, Layout.prototype.setValue = function (t, e) {
                    this._values[t] = new PropertyValue(this._values[t].property, null === e ? void 0 : clone(e));
                }, Layout.prototype.serialize = function () {
                    for (var t = this, e = {}, r = 0, a = Object.keys(t._values); r < a.length; r += 1) {
                        var o = a[r], i = t.getValue(o);
                        void 0 !== i && (e[o] = i);
                    }
                    return e;
                }, Layout.prototype.possiblyEvaluate = function (t) {
                    for (var e = this, r = new PossiblyEvaluated(this._properties), a = 0, o = Object.keys(e._values); a < o.length; a += 1) {
                        var i = o[a];
                        r._values[i] = e._values[i].possiblyEvaluate(t);
                    }
                    return r;
                };
                var PossiblyEvaluatedPropertyValue = function (t, e, r) {
                    this.property = t, this.value = e, this.globals = r;
                };
                PossiblyEvaluatedPropertyValue.prototype.isConstant = function () {
                    return 'constant' === this.value.kind;
                }, PossiblyEvaluatedPropertyValue.prototype.constantOr = function (t) {
                    return 'constant' === this.value.kind ? this.value.value : t;
                }, PossiblyEvaluatedPropertyValue.prototype.evaluate = function (t) {
                    return this.property.evaluate(this.value, this.globals, t);
                };
                var PossiblyEvaluated = function (t) {
                    this._properties = t, this._values = Object.create(t.defaultPossiblyEvaluatedValues);
                };
                PossiblyEvaluated.prototype.get = function (t) {
                    return this._values[t];
                };
                var DataConstantProperty = function (t) {
                    this.specification = t;
                };
                DataConstantProperty.prototype.possiblyEvaluate = function (t, e) {
                    return t.expression.evaluate(e);
                }, DataConstantProperty.prototype.interpolate = function (t, e, r) {
                    var a = interpolate[this.specification.type];
                    return a ? a(t, e, r) : t;
                };
                var DataDrivenProperty = function (t) {
                    this.specification = t;
                };
                DataDrivenProperty.prototype.possiblyEvaluate = function (t, e) {
                    return 'constant' === t.expression.kind || 'camera' === t.expression.kind ? new PossiblyEvaluatedPropertyValue(this, {
                        kind: 'constant',
                        value: t.expression.evaluate(e)
                    }, e) : new PossiblyEvaluatedPropertyValue(this, t.expression, e);
                }, DataDrivenProperty.prototype.interpolate = function (t, e, r) {
                    if ('constant' !== t.value.kind || 'constant' !== e.value.kind) {
                        return t;
                    }
                    if (void 0 !== t.value.value && void 0 !== e.value.value) {
                        var a = interpolate[this.specification.type];
                        return a ? new PossiblyEvaluatedPropertyValue(this, {
                            kind: 'constant',
                            value: a(t.value.value, e.value.value, r)
                        }, t.globals) : t;
                    }
                }, DataDrivenProperty.prototype.evaluate = function (t, e, r) {
                    return 'constant' === t.kind ? t.value : t.evaluate(e, r);
                };
                var CrossFadedProperty = function (t) {
                    this.specification = t;
                };
                CrossFadedProperty.prototype.possiblyEvaluate = function (t, e) {
                    if (void 0 !== t.value) {
                        if ('constant' === t.expression.kind) {
                            var r = t.expression.evaluate(e);
                            return this._calculate(r, r, r, e);
                        }
                        return this._calculate(t.expression.evaluate({ zoom: e.zoom - 1 }), t.expression.evaluate({ zoom: e.zoom }), t.expression.evaluate({ zoom: e.zoom + 1 }), e);
                    }
                }, CrossFadedProperty.prototype._calculate = function (t, e, r, a) {
                    var o = a.zoom, i = o - Math.floor(o), n = a.crossFadingFactor();
                    return o > a.zoomHistory.lastIntegerZoom ? {
                        from: t,
                        to: e,
                        fromScale: 2,
                        toScale: 1,
                        t: i + (1 - i) * n
                    } : {
                        from: r,
                        to: e,
                        fromScale: 0.5,
                        toScale: 1,
                        t: 1 - (1 - n) * i
                    };
                }, CrossFadedProperty.prototype.interpolate = function (t) {
                    return t;
                };
                var HeatmapColorProperty = function (t) {
                    this.specification = t;
                };
                HeatmapColorProperty.prototype.possiblyEvaluate = function () {
                }, HeatmapColorProperty.prototype.interpolate = function () {
                };
                var Properties = function (t) {
                    var e = this;
                    this.properties = t, this.defaultPropertyValues = {}, this.defaultTransitionablePropertyValues = {}, this.defaultTransitioningPropertyValues = {}, this.defaultPossiblyEvaluatedValues = {};
                    for (var r in t) {
                        var a = t[r], o = e.defaultPropertyValues[r] = new PropertyValue(a, void 0), i = e.defaultTransitionablePropertyValues[r] = new TransitionablePropertyValue(a);
                        e.defaultTransitioningPropertyValues[r] = i.untransitioned(), e.defaultPossiblyEvaluatedValues[r] = o.possiblyEvaluate({});
                    }
                };
                register('DataDrivenProperty', DataDrivenProperty), register('DataConstantProperty', DataConstantProperty), register('CrossFadedProperty', CrossFadedProperty), register('HeatmapColorProperty', HeatmapColorProperty), module.exports = {
                    PropertyValue: PropertyValue,
                    Transitionable: Transitionable,
                    Transitioning: Transitioning,
                    Layout: Layout,
                    PossiblyEvaluatedPropertyValue: PossiblyEvaluatedPropertyValue,
                    PossiblyEvaluated: PossiblyEvaluated,
                    DataConstantProperty: DataConstantProperty,
                    DataDrivenProperty: DataDrivenProperty,
                    CrossFadedProperty: CrossFadedProperty,
                    HeatmapColorProperty: HeatmapColorProperty,
                    Properties: Properties
                };
            },
            {
                '../style-spec/expression': 139,
                '../style-spec/util/color': 153,
                '../style-spec/util/interpolate': 158,
                '../util/util': 275,
                '../util/web_worker_transfer': 278
            }
        ],
        189: [
            function (_dereq_, module, exports) {
                'use strict';
                function getMaximumPaintValue(t, a, e) {
                    var n = a.paint.get(t).value;
                    return 'constant' === n.kind ? n.value : e.programConfigurations.get(a.id).binders[t].statistics.max;
                }
                function translateDistance(t) {
                    return Math.sqrt(t[0] * t[0] + t[1] * t[1]);
                }
                function translate(t, a, e, n, r) {
                    if (!a[0] && !a[1]) {
                        return t;
                    }
                    var i = Point.convert(a);
                    'viewport' === e && i._rotate(-n);
                    for (var u = [], s = 0; s < t.length; s++) {
                        for (var o = t[s], l = [], m = 0; m < o.length; m++) {
                            l.push(o[m].sub(i._mult(r)));
                        }
                        u.push(l);
                    }
                    return u;
                }
                var Point = _dereq_('@mapbox/point-geometry');
                module.exports = {
                    getMaximumPaintValue: getMaximumPaintValue,
                    translateDistance: translateDistance,
                    translate: translate
                };
            },
            { '@mapbox/point-geometry': 4 }
        ],
        190: [
            function (_dereq_, module, exports) {
                'use strict';
                var Evented = _dereq_('../util/evented'), StyleLayer = _dereq_('./style_layer'), loadSprite = _dereq_('./load_sprite'), ImageManager = _dereq_('../render/image_manager'), GlyphManager = _dereq_('../render/glyph_manager'), Light = _dereq_('./light'), LineAtlas = _dereq_('../render/line_atlas'), util = _dereq_('../util/util'), ajax = _dereq_('../util/ajax'), mapbox = _dereq_('../util/mapbox'), browser = _dereq_('../util/browser'), Dispatcher = _dereq_('../util/dispatcher'), validateStyle = _dereq_('./validate_style'), getSourceType = _dereq_('../source/source').getType, setSourceType = _dereq_('../source/source').setType, QueryFeatures = _dereq_('../source/query_features'), SourceCache = _dereq_('../source/source_cache'), GeoJSONSource = _dereq_('../source/geojson_source'), styleSpec = _dereq_('../style-spec/reference/latest'), getWorkerPool = _dereq_('../util/global_worker_pool'), deref = _dereq_('../style-spec/deref'), diff = _dereq_('../style-spec/diff'), rtlTextPlugin = _dereq_('../source/rtl_text_plugin'), PauseablePlacement = _dereq_('./pauseable_placement'), ZoomHistory = _dereq_('./zoom_history'), CrossTileSymbolIndex = _dereq_('../symbol/cross_tile_symbol_index'), supportedDiffOperations = util.pick(diff.operations, [
                        'addLayer',
                        'removeLayer',
                        'setPaintProperty',
                        'setLayoutProperty',
                        'setFilter',
                        'addSource',
                        'removeSource',
                        'setLayerZoomRange',
                        'setLight',
                        'setTransition',
                        'setGeoJSONSourceData'
                    ]), ignoredDiffOperations = util.pick(diff.operations, [
                        'setCenter',
                        'setZoom',
                        'setBearing',
                        'setPitch'
                    ]), Style = function (e) {
                        function r(r, t) {
                            var a = this;
                            void 0 === t && (t = {}), e.call(this), this.map = r, this.dispatcher = new Dispatcher(getWorkerPool(), this), this.imageManager = new ImageManager(), this.glyphManager = new GlyphManager(r._transformRequest, t.localIdeographFontFamily), this.lineAtlas = new LineAtlas(256, 512), this.crossTileSymbolIndex = new CrossTileSymbolIndex(), this._layers = {}, this._order = [], this.sourceCaches = {}, this.zoomHistory = new ZoomHistory(), this._loaded = !1, this._resetUpdates();
                            var i = this;
                            this._rtlTextPluginCallback = rtlTextPlugin.registerForPluginAvailability(function (e) {
                                i.dispatcher.broadcast('loadRTLTextPlugin', e.pluginBlobURL, e.errorCallback);
                                for (var r in i.sourceCaches) {
                                    i.sourceCaches[r].reload();
                                }
                            }), this.on('data', function (e) {
                                if ('source' === e.dataType && 'metadata' === e.sourceDataType) {
                                    var r = a.sourceCaches[e.sourceId];
                                    if (r) {
                                        var t = r.getSource();
                                        if (t && t.vectorLayerIds) {
                                            for (var i in a._layers) {
                                                var s = a._layers[i];
                                                s.source === t.id && a._validateLayer(s);
                                            }
                                        }
                                    }
                                }
                            });
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r.prototype.loadURL = function (e, r) {
                            var t = this;
                            void 0 === r && (r = {}), this.fire('dataloading', { dataType: 'style' });
                            var a = 'boolean' == typeof r.validate ? r.validate : !mapbox.isMapboxURL(e);
                            e = mapbox.normalizeStyleURL(e, r.accessToken);
                            var i = this.map._transformRequest(e, ajax.ResourceType.Style);
                            ajax.getJSON(i, function (e, r) {
                                e ? t.fire('error', { error: e }) : r && t._load(r, a);
                            });
                        }, r.prototype.loadJSON = function (e, r) {
                            var t = this;
                            void 0 === r && (r = {}), this.fire('dataloading', { dataType: 'style' }), browser.frame(function () {
                                t._load(e, !1 !== r.validate);
                            });
                        }, r.prototype._load = function (e, r) {
                            var t = this;
                            if (!r || !validateStyle.emitErrors(this, validateStyle(e))) {
                                this._loaded = !0, this.stylesheet = e;
                                for (var a in e.sources) {
                                    t.addSource(a, e.sources[a], { validate: !1 });
                                }
                                e.sprite ? loadSprite(e.sprite, this.map._transformRequest, function (e, r) {
                                    if (e) {
                                        t.fire('error', e);
                                    } else if (r) {
                                        for (var a in r) {
                                            t.imageManager.addImage(a, r[a]);
                                        }
                                    }
                                    t.imageManager.setLoaded(!0), t.fire('data', { dataType: 'style' });
                                }) : this.imageManager.setLoaded(!0), this.glyphManager.setURL(e.glyphs);
                                var i = deref(this.stylesheet.layers);
                                this._order = i.map(function (e) {
                                    return e.id;
                                }), this._layers = {};
                                for (var s = 0, o = i; s < o.length; s += 1) {
                                    var n = o[s];
                                    n = StyleLayer.create(n), n.setEventedParent(t, { layer: { id: n.id } }), t._layers[n.id] = n;
                                }
                                this.dispatcher.broadcast('setLayers', this._serializeLayers(this._order)), this.light = new Light(this.stylesheet.light), this.fire('data', { dataType: 'style' }), this.fire('style.load');
                            }
                        }, r.prototype._validateLayer = function (e) {
                            var r = this.sourceCaches[e.source];
                            if (r) {
                                var t = e.sourceLayer;
                                if (t) {
                                    var a = r.getSource();
                                    ('geojson' === a.type || a.vectorLayerIds && -1 === a.vectorLayerIds.indexOf(t)) && this.fire('error', { error: new Error('Source layer "' + t + '" does not exist on source "' + a.id + '" as specified by style layer "' + e.id + '"') });
                                }
                            }
                        }, r.prototype.loaded = function () {
                            var e = this;
                            if (!this._loaded) {
                                return !1;
                            }
                            if (Object.keys(this._updatedSources).length) {
                                return !1;
                            }
                            for (var r in e.sourceCaches) {
                                if (!e.sourceCaches[r].loaded()) {
                                    return !1;
                                }
                            }
                            return !!this.imageManager.isLoaded();
                        }, r.prototype._serializeLayers = function (e) {
                            var r = this;
                            return e.map(function (e) {
                                return r._layers[e].serialize();
                            });
                        }, r.prototype.hasTransitions = function () {
                            var e = this;
                            if (this.light && this.light.hasTransition()) {
                                return !0;
                            }
                            for (var r in e.sourceCaches) {
                                if (e.sourceCaches[r].hasTransition()) {
                                    return !0;
                                }
                            }
                            for (var t in e._layers) {
                                if (e._layers[t].hasTransition()) {
                                    return !0;
                                }
                            }
                            return !1;
                        }, r.prototype._checkLoaded = function () {
                            if (!this._loaded) {
                                throw new Error('Style is not done loading');
                            }
                        }, r.prototype.update = function (e) {
                            var r = this;
                            if (this._loaded) {
                                if (this._changed) {
                                    var t = Object.keys(this._updatedLayers), a = Object.keys(this._removedLayers);
                                    (t.length || a.length) && this._updateWorkerLayers(t, a);
                                    for (var i in r._updatedSources) {
                                        var s = r._updatedSources[i];
                                        'reload' === s ? r._reloadSource(i) : 'clear' === s && r._clearSource(i);
                                    }
                                    for (var o in r._updatedPaintProps) {
                                        r._layers[o].updateTransitions(e);
                                    }
                                    this.light.updateTransitions(e), this._resetUpdates(), this.fire('data', { dataType: 'style' });
                                }
                                for (var n in r.sourceCaches) {
                                    r.sourceCaches[n].used = !1;
                                }
                                for (var l = 0, h = r._order; l < h.length; l += 1) {
                                    var u = h[l], d = r._layers[u];
                                    d.recalculate(e), !d.isHidden(e.zoom) && d.source && (r.sourceCaches[d.source].used = !0);
                                }
                                this.light.recalculate(e), this.z = e.zoom;
                            }
                        }, r.prototype._updateWorkerLayers = function (e, r) {
                            this.dispatcher.broadcast('updateLayers', {
                                layers: this._serializeLayers(e),
                                removedIds: r
                            });
                        }, r.prototype._resetUpdates = function () {
                            this._changed = !1, this._updatedLayers = {}, this._removedLayers = {}, this._updatedSources = {}, this._updatedPaintProps = {};
                        }, r.prototype.setState = function (e) {
                            var r = this;
                            if (this._checkLoaded(), validateStyle.emitErrors(this, validateStyle(e))) {
                                return !1;
                            }
                            e = util.clone(e), e.layers = deref(e.layers);
                            var t = diff(this.serialize(), e).filter(function (e) {
                                return !(e.command in ignoredDiffOperations);
                            });
                            if (0 === t.length) {
                                return !1;
                            }
                            var a = t.filter(function (e) {
                                return !(e.command in supportedDiffOperations);
                            });
                            if (a.length > 0) {
                                throw new Error('Unimplemented: ' + a.map(function (e) {
                                    return e.command;
                                }).join(', ') + '.');
                            }
                            return t.forEach(function (e) {
                                'setTransition' !== e.command && r[e.command].apply(r, e.args);
                            }), this.stylesheet = e, !0;
                        }, r.prototype.addImage = function (e, r) {
                            if (this.getImage(e)) {
                                return this.fire('error', { error: new Error('An image with this name already exists.') });
                            }
                            this.imageManager.addImage(e, r), this.fire('data', { dataType: 'style' });
                        }, r.prototype.getImage = function (e) {
                            return this.imageManager.getImage(e);
                        }, r.prototype.removeImage = function (e) {
                            if (!this.getImage(e)) {
                                return this.fire('error', { error: new Error('No image with this name exists.') });
                            }
                            this.imageManager.removeImage(e), this.fire('data', { dataType: 'style' });
                        }, r.prototype.addSource = function (e, r, t) {
                            var a = this;
                            if (this._checkLoaded(), void 0 !== this.sourceCaches[e]) {
                                throw new Error('There is already a source with this ID');
                            }
                            if (!r.type) {
                                throw new Error('The type property must be defined, but the only the following properties were given: ' + Object.keys(r).join(', ') + '.');
                            }
                            if (!([
                                    'vector',
                                    'raster',
                                    'geojson',
                                    'video',
                                    'image',
                                    'canvas'
                                ].indexOf(r.type) >= 0 && this._validate(validateStyle.source, 'sources.' + e, r, null, t))) {
                                this.map && this.map._collectResourceTiming && (r.collectResourceTiming = !0);
                                var i = this.sourceCaches[e] = new SourceCache(e, r, this.dispatcher);
                                i.style = this, i.setEventedParent(this, function () {
                                    return {
                                        isSourceLoaded: a.loaded(),
                                        source: i.serialize(),
                                        sourceId: e
                                    };
                                }), i.onAdd(this.map), this._changed = !0;
                            }
                        }, r.prototype.removeSource = function (e) {
                            var r = this;
                            if (this._checkLoaded(), void 0 === this.sourceCaches[e]) {
                                throw new Error('There is no source with this ID');
                            }
                            for (var t in r._layers) {
                                if (r._layers[t].source === e) {
                                    return r.fire('error', { error: new Error('Source "' + e + '" cannot be removed while layer "' + t + '" is using it.') });
                                }
                            }
                            var a = this.sourceCaches[e];
                            delete this.sourceCaches[e], delete this._updatedSources[e], a.fire('data', {
                                sourceDataType: 'metadata',
                                dataType: 'source',
                                sourceId: e
                            }), a.setEventedParent(null), a.clearTiles(), a.onRemove && a.onRemove(this.map), this._changed = !0;
                        }, r.prototype.setGeoJSONSourceData = function (e, r) {
                            this._checkLoaded(), this.sourceCaches[e].getSource().setData(r), this._changed = !0;
                        }, r.prototype.getSource = function (e) {
                            return this.sourceCaches[e] && this.sourceCaches[e].getSource();
                        }, r.prototype.addLayer = function (e, r, t) {
                            this._checkLoaded();
                            var a = e.id;
                            if ('object' == typeof e.source && (this.addSource(a, e.source), e = util.clone(e), e = util.extend(e, { source: a })), !this._validate(validateStyle.layer, 'layers.' + a, e, { arrayIndex: -1 }, t)) {
                                var i = StyleLayer.create(e);
                                this._validateLayer(i), i.setEventedParent(this, { layer: { id: a } });
                                var s = r ? this._order.indexOf(r) : this._order.length;
                                if (r && -1 === s) {
                                    return void this.fire('error', { error: new Error('Layer with id "' + r + '" does not exist on this map.') });
                                }
                                if (this._order.splice(s, 0, a), this._layerOrderChanged = !0, this._layers[a] = i, this._removedLayers[a] && i.source) {
                                    var o = this._removedLayers[a];
                                    delete this._removedLayers[a], o.type !== i.type ? this._updatedSources[i.source] = 'clear' : (this._updatedSources[i.source] = 'reload', this.sourceCaches[i.source].pause());
                                }
                                this._updateLayer(i);
                            }
                        }, r.prototype.moveLayer = function (e, r) {
                            if (this._checkLoaded(), this._changed = !0, !this._layers[e]) {
                                return void this.fire('error', { error: new Error('The layer \'' + e + '\' does not exist in the map\'s style and cannot be moved.') });
                            }
                            var t = this._order.indexOf(e);
                            this._order.splice(t, 1);
                            var a = r ? this._order.indexOf(r) : this._order.length;
                            if (r && -1 === a) {
                                return void this.fire('error', { error: new Error('Layer with id "' + r + '" does not exist on this map.') });
                            }
                            this._order.splice(a, 0, e), this._layerOrderChanged = !0;
                        }, r.prototype.removeLayer = function (e) {
                            this._checkLoaded();
                            var r = this._layers[e];
                            if (!r) {
                                return void this.fire('error', { error: new Error('The layer \'' + e + '\' does not exist in the map\'s style and cannot be removed.') });
                            }
                            r.setEventedParent(null);
                            var t = this._order.indexOf(e);
                            this._order.splice(t, 1), this._layerOrderChanged = !0, this._changed = !0, this._removedLayers[e] = r, delete this._layers[e], delete this._updatedLayers[e], delete this._updatedPaintProps[e];
                        }, r.prototype.getLayer = function (e) {
                            return this._layers[e];
                        }, r.prototype.setLayerZoomRange = function (e, r, t) {
                            this._checkLoaded();
                            var a = this.getLayer(e);
                            if (!a) {
                                return void this.fire('error', { error: new Error('The layer \'' + e + '\' does not exist in the map\'s style and cannot have zoom extent.') });
                            }
                            a.minzoom === r && a.maxzoom === t || (null != r && (a.minzoom = r), null != t && (a.maxzoom = t), this._updateLayer(a));
                        }, r.prototype.setFilter = function (e, r) {
                            this._checkLoaded();
                            var t = this.getLayer(e);
                            if (!t) {
                                return void this.fire('error', { error: new Error('The layer \'' + e + '\' does not exist in the map\'s style and cannot be filtered.') });
                            }
                            if (!util.deepEqual(t.filter, r)) {
                                return null === r || void 0 === r ? (t.filter = void 0, void this._updateLayer(t)) : void (this._validate(validateStyle.filter, 'layers.' + t.id + '.filter', r) || (t.filter = util.clone(r), this._updateLayer(t)));
                            }
                        }, r.prototype.getFilter = function (e) {
                            return util.clone(this.getLayer(e).filter);
                        }, r.prototype.setLayoutProperty = function (e, r, t) {
                            this._checkLoaded();
                            var a = this.getLayer(e);
                            if (!a) {
                                return void this.fire('error', { error: new Error('The layer \'' + e + '\' does not exist in the map\'s style and cannot be styled.') });
                            }
                            util.deepEqual(a.getLayoutProperty(r), t) || (a.setLayoutProperty(r, t), this._updateLayer(a));
                        }, r.prototype.getLayoutProperty = function (e, r) {
                            return this.getLayer(e).getLayoutProperty(r);
                        }, r.prototype.setPaintProperty = function (e, r, t) {
                            this._checkLoaded();
                            var a = this.getLayer(e);
                            if (!a) {
                                return void this.fire('error', { error: new Error('The layer \'' + e + '\' does not exist in the map\'s style and cannot be styled.') });
                            }
                            if (!util.deepEqual(a.getPaintProperty(r), t)) {
                                var i = a._transitionablePaint._values[r].value.isDataDriven();
                                a.setPaintProperty(r, t);
                                (a._transitionablePaint._values[r].value.isDataDriven() || i) && this._updateLayer(a), this._changed = !0, this._updatedPaintProps[e] = !0;
                            }
                        }, r.prototype.getPaintProperty = function (e, r) {
                            return this.getLayer(e).getPaintProperty(r);
                        }, r.prototype.getTransition = function () {
                            return util.extend({
                                duration: 300,
                                delay: 0
                            }, this.stylesheet && this.stylesheet.transition);
                        }, r.prototype.serialize = function () {
                            var e = this;
                            return util.filterObject({
                                version: this.stylesheet.version,
                                name: this.stylesheet.name,
                                metadata: this.stylesheet.metadata,
                                light: this.stylesheet.light,
                                center: this.stylesheet.center,
                                zoom: this.stylesheet.zoom,
                                bearing: this.stylesheet.bearing,
                                pitch: this.stylesheet.pitch,
                                sprite: this.stylesheet.sprite,
                                glyphs: this.stylesheet.glyphs,
                                transition: this.stylesheet.transition,
                                sources: util.mapObject(this.sourceCaches, function (e) {
                                    return e.serialize();
                                }),
                                layers: this._order.map(function (r) {
                                    return e._layers[r].serialize();
                                })
                            }, function (e) {
                                return void 0 !== e;
                            });
                        }, r.prototype._updateLayer = function (e) {
                            this._updatedLayers[e.id] = !0, e.source && !this._updatedSources[e.source] && (this._updatedSources[e.source] = 'reload', this.sourceCaches[e.source].pause()), this._changed = !0;
                        }, r.prototype._flattenRenderedFeatures = function (e) {
                            for (var r = this, t = [], a = this._order.length - 1; a >= 0; a--) {
                                for (var i = r._order[a], s = 0, o = e; s < o.length; s += 1) {
                                    var n = o[s], l = n[i];
                                    if (l) {
                                        for (var h = 0, u = l; h < u.length; h += 1) {
                                            var d = u[h];
                                            t.push(d);
                                        }
                                    }
                                }
                            }
                            return t;
                        }, r.prototype.queryRenderedFeatures = function (e, r, t, a) {
                            var i = this;
                            r && r.filter && this._validate(validateStyle.filter, 'queryRenderedFeatures.filter', r.filter);
                            var s = {};
                            if (r && r.layers) {
                                if (!Array.isArray(r.layers)) {
                                    return this.fire('error', { error: 'parameters.layers must be an Array.' }), [];
                                }
                                for (var o = 0, n = r.layers; o < n.length; o += 1) {
                                    var l = n[o], h = i._layers[l];
                                    if (!h) {
                                        return i.fire('error', { error: 'The layer \'' + l + '\' does not exist in the map\'s style and cannot be queried for features.' }), [];
                                    }
                                    s[h.source] = !0;
                                }
                            }
                            var u = [];
                            for (var d in i.sourceCaches) {
                                if (!r.layers || s[d]) {
                                    var c = QueryFeatures.rendered(i.sourceCaches[d], i._layers, e, r, t, a, i.placement ? i.placement.collisionIndex : null);
                                    u.push(c);
                                }
                            }
                            return this._flattenRenderedFeatures(u);
                        }, r.prototype.querySourceFeatures = function (e, r) {
                            r && r.filter && this._validate(validateStyle.filter, 'querySourceFeatures.filter', r.filter);
                            var t = this.sourceCaches[e];
                            return t ? QueryFeatures.source(t, r) : [];
                        }, r.prototype.addSourceType = function (e, r, t) {
                            return getSourceType(e) ? t(new Error('A source type called "' + e + '" already exists.')) : (setSourceType(e, r), r.workerSourceURL ? void this.dispatcher.broadcast('loadWorkerSource', {
                                name: e,
                                url: r.workerSourceURL
                            }, t) : t(null, null));
                        }, r.prototype.getLight = function () {
                            return this.light.getLight();
                        }, r.prototype.setLight = function (e) {
                            this._checkLoaded();
                            var r = this.light.getLight(), t = !1;
                            for (var a in e) {
                                if (!util.deepEqual(e[a], r[a])) {
                                    t = !0;
                                    break;
                                }
                            }
                            if (t) {
                                var i = {
                                    now: browser.now(),
                                    transition: util.extend({
                                        duration: 300,
                                        delay: 0
                                    }, this.stylesheet.transition)
                                };
                                this.light.setLight(e), this.light.updateTransitions(i);
                            }
                        }, r.prototype._validate = function (e, r, t, a, i) {
                            return (!i || !1 !== i.validate) && validateStyle.emitErrors(this, e.call(validateStyle, util.extend({
                                key: r,
                                style: this.serialize(),
                                value: t,
                                styleSpec: styleSpec
                            }, a)));
                        }, r.prototype._remove = function () {
                            var e = this;
                            rtlTextPlugin.evented.off('pluginAvailable', this._rtlTextPluginCallback);
                            for (var r in e.sourceCaches) {
                                e.sourceCaches[r].clearTiles();
                            }
                            this.dispatcher.remove();
                        }, r.prototype._clearSource = function (e) {
                            this.sourceCaches[e].clearTiles();
                        }, r.prototype._reloadSource = function (e) {
                            this.sourceCaches[e].resume(), this.sourceCaches[e].reload();
                        }, r.prototype._updateSources = function (e) {
                            var r = this;
                            for (var t in r.sourceCaches) {
                                r.sourceCaches[t].update(e);
                            }
                        }, r.prototype._generateCollisionBoxes = function () {
                            var e = this;
                            for (var r in e.sourceCaches) {
                                e._reloadSource(r);
                            }
                        }, r.prototype._updatePlacement = function (e, r, t) {
                            for (var a = this, i = !1, s = !1, o = {}, n = 0, l = a._order; n < l.length; n += 1) {
                                var h = l[n], u = a._layers[h];
                                if ('symbol' === u.type) {
                                    if (!o[u.source]) {
                                        var d = a.sourceCaches[u.source];
                                        o[u.source] = d.getRenderableIds().map(function (e) {
                                            return d.getTileByID(e);
                                        }).sort(function (e, r) {
                                            return r.tileID.overscaledZ - e.tileID.overscaledZ || (e.tileID.isLessThan(r.tileID) ? -1 : 1);
                                        });
                                    }
                                    var c = a.crossTileSymbolIndex.addLayer(u, o[u.source]);
                                    i = i || c;
                                }
                            }
                            this.crossTileSymbolIndex.pruneUnusedLayers(this._order);
                            var y = this._layerOrderChanged;
                            if ((y || !this.pauseablePlacement || this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now())) && (this.pauseablePlacement = new PauseablePlacement(e, this._order, y, r, t), this._layerOrderChanged = !1), this.pauseablePlacement.isDone() ? this.placement.setStale() : (this.pauseablePlacement.continuePlacement(this._order, this._layers, o), this.pauseablePlacement.isDone() && (this.placement = this.pauseablePlacement.commit(this.placement, browser.now()), s = !0), i && this.pauseablePlacement.placement.setStale()), s || i) {
                                for (var p = 0, f = a._order; p < f.length; p += 1) {
                                    var v = f[p], g = a._layers[v];
                                    'symbol' === g.type && a.placement.updateLayerOpacities(g, o[g.source]);
                                }
                            }
                            return !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now());
                        }, r.prototype.getImages = function (e, r, t) {
                            this.imageManager.getImages(r.icons, t);
                        }, r.prototype.getGlyphs = function (e, r, t) {
                            this.glyphManager.getGlyphs(r.stacks, t);
                        }, r;
                    }(Evented);
                module.exports = Style;
            },
            {
                '../render/glyph_manager': 86,
                '../render/image_manager': 88,
                '../render/line_atlas': 89,
                '../source/geojson_source': 99,
                '../source/query_features': 105,
                '../source/rtl_text_plugin': 109,
                '../source/source': 110,
                '../source/source_cache': 111,
                '../style-spec/deref': 120,
                '../style-spec/diff': 121,
                '../style-spec/reference/latest': 151,
                '../symbol/cross_tile_symbol_index': 218,
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/dispatcher': 258,
                '../util/evented': 260,
                '../util/global_worker_pool': 262,
                '../util/mapbox': 267,
                '../util/util': 275,
                './light': 183,
                './load_sprite': 185,
                './pauseable_placement': 187,
                './style_layer': 191,
                './validate_style': 211,
                './zoom_history': 212
            }
        ],
        191: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), styleSpec = _dereq_('../style-spec/reference/latest'), validateStyle = _dereq_('./validate_style'), Evented = _dereq_('../util/evented'), ref = _dereq_('./properties'), Layout = ref.Layout, Transitionable = ref.Transitionable, Transitioning = ref.Transitioning, Properties = ref.Properties, TRANSITION_SUFFIX = '-transition', StyleLayer = function (t) {
                        function e(e, i) {
                            var a = this;
                            t.call(this), this.id = e.id, this.metadata = e.metadata, this.type = e.type, this.minzoom = e.minzoom, this.maxzoom = e.maxzoom, this.visibility = 'visible', 'background' !== e.type && (this.source = e.source, this.sourceLayer = e['source-layer'], this.filter = e.filter), this._featureFilter = function () {
                                return !0;
                            }, i.layout && (this._unevaluatedLayout = new Layout(i.layout)), this._transitionablePaint = new Transitionable(i.paint);
                            for (var r in e.paint) {
                                a.setPaintProperty(r, e.paint[r], { validate: !1 });
                            }
                            for (var s in e.layout) {
                                a.setLayoutProperty(s, e.layout[s], { validate: !1 });
                            }
                            this._transitioningPaint = this._transitionablePaint.untransitioned();
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.getLayoutProperty = function (t) {
                            return 'visibility' === t ? this.visibility : this._unevaluatedLayout.getValue(t);
                        }, e.prototype.setLayoutProperty = function (t, e, i) {
                            if (null !== e && void 0 !== e) {
                                var a = 'layers.' + this.id + '.layout.' + t;
                                if (this._validate(validateStyle.layoutProperty, a, t, e, i)) {
                                    return;
                                }
                            }
                            if ('visibility' === t) {
                                return void (this.visibility = 'none' === e ? e : 'visible');
                            }
                            this._unevaluatedLayout.setValue(t, e);
                        }, e.prototype.getPaintProperty = function (t) {
                            return util.endsWith(t, TRANSITION_SUFFIX) ? this._transitionablePaint.getTransition(t.slice(0, -TRANSITION_SUFFIX.length)) : this._transitionablePaint.getValue(t);
                        }, e.prototype.setPaintProperty = function (t, e, i) {
                            if (null !== e && void 0 !== e) {
                                var a = 'layers.' + this.id + '.paint.' + t;
                                if (this._validate(validateStyle.paintProperty, a, t, e, i)) {
                                    return;
                                }
                            }
                            util.endsWith(t, TRANSITION_SUFFIX) ? this._transitionablePaint.setTransition(t.slice(0, -TRANSITION_SUFFIX.length), e || void 0) : this._transitionablePaint.setValue(t, e);
                        }, e.prototype.isHidden = function (t) {
                            return !!(this.minzoom && t < this.minzoom) || (!!(this.maxzoom && t >= this.maxzoom) || 'none' === this.visibility);
                        }, e.prototype.updateTransitions = function (t) {
                            this._transitioningPaint = this._transitionablePaint.transitioned(t, this._transitioningPaint);
                        }, e.prototype.hasTransition = function () {
                            return this._transitioningPaint.hasTransition();
                        }, e.prototype.recalculate = function (t) {
                            this._unevaluatedLayout && (this.layout = this._unevaluatedLayout.possiblyEvaluate(t)), this.paint = this._transitioningPaint.possiblyEvaluate(t);
                        }, e.prototype.serialize = function () {
                            var t = {
                                id: this.id,
                                type: this.type,
                                source: this.source,
                                'source-layer': this.sourceLayer,
                                metadata: this.metadata,
                                minzoom: this.minzoom,
                                maxzoom: this.maxzoom,
                                filter: this.filter,
                                layout: this._unevaluatedLayout && this._unevaluatedLayout.serialize(),
                                paint: this._transitionablePaint && this._transitionablePaint.serialize()
                            };
                            return 'none' === this.visibility && (t.layout = t.layout || {}, t.layout.visibility = 'none'), util.filterObject(t, function (t, e) {
                                return !(void 0 === t || 'layout' === e && !Object.keys(t).length || 'paint' === e && !Object.keys(t).length);
                            });
                        }, e.prototype._validate = function (t, e, i, a, r) {
                            return (!r || !1 !== r.validate) && validateStyle.emitErrors(this, t.call(validateStyle, {
                                key: e,
                                layerType: this.type,
                                objectKey: i,
                                value: a,
                                styleSpec: styleSpec,
                                style: {
                                    glyphs: !0,
                                    sprite: !0
                                }
                            }));
                        }, e.prototype.hasOffscreenPass = function () {
                            return !1;
                        }, e.prototype.resize = function () {
                        }, e;
                    }(Evented);
                module.exports = StyleLayer;
                var subclasses = {
                    circle: _dereq_('./style_layer/circle_style_layer'),
                    heatmap: _dereq_('./style_layer/heatmap_style_layer'),
                    hillshade: _dereq_('./style_layer/hillshade_style_layer'),
                    fill: _dereq_('./style_layer/fill_style_layer'),
                    'fill-extrusion': _dereq_('./style_layer/fill_extrusion_style_layer'),
                    line: _dereq_('./style_layer/line_style_layer'),
                    symbol: _dereq_('./style_layer/symbol_style_layer'),
                    background: _dereq_('./style_layer/background_style_layer'),
                    raster: _dereq_('./style_layer/raster_style_layer')
                };
                StyleLayer.create = function (t) {
                    return new subclasses[t.type](t);
                };
            },
            {
                '../style-spec/reference/latest': 151,
                '../util/evented': 260,
                '../util/util': 275,
                './properties': 188,
                './style_layer/background_style_layer': 192,
                './style_layer/circle_style_layer': 194,
                './style_layer/fill_extrusion_style_layer': 196,
                './style_layer/fill_style_layer': 198,
                './style_layer/heatmap_style_layer': 200,
                './style_layer/hillshade_style_layer': 202,
                './style_layer/line_style_layer': 204,
                './style_layer/raster_style_layer': 206,
                './style_layer/symbol_style_layer': 208,
                './validate_style': 211
            }
        ],
        192: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), properties = _dereq_('./background_style_layer_properties'), ref = _dereq_('../properties'), Transitionable = ref.Transitionable, Transitioning = ref.Transitioning, PossiblyEvaluated = ref.PossiblyEvaluated, BackgroundStyleLayer = function (e) {
                        function r(r) {
                            e.call(this, r, properties);
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r;
                    }(StyleLayer);
                module.exports = BackgroundStyleLayer;
            },
            {
                '../properties': 188,
                '../style_layer': 191,
                './background_style_layer_properties': 193
            }
        ],
        193: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'background-color': new DataConstantProperty(styleSpec.paint_background['background-color']),
                        'background-pattern': new CrossFadedProperty(styleSpec.paint_background['background-pattern']),
                        'background-opacity': new DataConstantProperty(styleSpec.paint_background['background-opacity'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        194: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), CircleBucket = _dereq_('../../data/bucket/circle_bucket'), ref = _dereq_('../../util/intersection_tests'), multiPolygonIntersectsBufferedMultiPoint = ref.multiPolygonIntersectsBufferedMultiPoint, ref$1 = _dereq_('../query_utils'), getMaximumPaintValue = ref$1.getMaximumPaintValue, translateDistance = ref$1.translateDistance, translate = ref$1.translate, properties = _dereq_('./circle_style_layer_properties'), ref$2 = _dereq_('../properties'), Transitionable = ref$2.Transitionable, Transitioning = ref$2.Transitioning, PossiblyEvaluated = ref$2.PossiblyEvaluated, CircleStyleLayer = function (e) {
                        function t(t) {
                            e.call(this, t, properties);
                        }
                        return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t.prototype.createBucket = function (e) {
                            return new CircleBucket(e);
                        }, t.prototype.queryRadius = function (e) {
                            var t = e;
                            return getMaximumPaintValue('circle-radius', this, t) + getMaximumPaintValue('circle-stroke-width', this, t) + translateDistance(this.paint.get('circle-translate'));
                        }, t.prototype.queryIntersectsFeature = function (e, t, r, i, a, n) {
                            var l = translate(e, this.paint.get('circle-translate'), this.paint.get('circle-translate-anchor'), a, n), s = this.paint.get('circle-radius').evaluate(t) * n, u = this.paint.get('circle-stroke-width').evaluate(t) * n;
                            return multiPolygonIntersectsBufferedMultiPoint(l, r, s + u);
                        }, t;
                    }(StyleLayer);
                module.exports = CircleStyleLayer;
            },
            {
                '../../data/bucket/circle_bucket': 42,
                '../../util/intersection_tests': 264,
                '../properties': 188,
                '../query_utils': 189,
                '../style_layer': 191,
                './circle_style_layer_properties': 195
            }
        ],
        195: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'circle-radius': new DataDrivenProperty(styleSpec.paint_circle['circle-radius']),
                        'circle-color': new DataDrivenProperty(styleSpec.paint_circle['circle-color']),
                        'circle-blur': new DataDrivenProperty(styleSpec.paint_circle['circle-blur']),
                        'circle-opacity': new DataDrivenProperty(styleSpec.paint_circle['circle-opacity']),
                        'circle-translate': new DataConstantProperty(styleSpec.paint_circle['circle-translate']),
                        'circle-translate-anchor': new DataConstantProperty(styleSpec.paint_circle['circle-translate-anchor']),
                        'circle-pitch-scale': new DataConstantProperty(styleSpec.paint_circle['circle-pitch-scale']),
                        'circle-pitch-alignment': new DataConstantProperty(styleSpec.paint_circle['circle-pitch-alignment']),
                        'circle-stroke-width': new DataDrivenProperty(styleSpec.paint_circle['circle-stroke-width']),
                        'circle-stroke-color': new DataDrivenProperty(styleSpec.paint_circle['circle-stroke-color']),
                        'circle-stroke-opacity': new DataDrivenProperty(styleSpec.paint_circle['circle-stroke-opacity'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        196: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), FillExtrusionBucket = _dereq_('../../data/bucket/fill_extrusion_bucket'), ref = _dereq_('../../util/intersection_tests'), multiPolygonIntersectsMultiPolygon = ref.multiPolygonIntersectsMultiPolygon, ref$1 = _dereq_('../query_utils'), translateDistance = ref$1.translateDistance, translate = ref$1.translate, properties = _dereq_('./fill_extrusion_style_layer_properties'), ref$2 = _dereq_('../properties'), Transitionable = ref$2.Transitionable, Transitioning = ref$2.Transitioning, PossiblyEvaluated = ref$2.PossiblyEvaluated, FillExtrusionStyleLayer = function (t) {
                        function e(e) {
                            t.call(this, e, properties);
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.createBucket = function (t) {
                            return new FillExtrusionBucket(t);
                        }, e.prototype.queryRadius = function () {
                            return translateDistance(this.paint.get('fill-extrusion-translate'));
                        }, e.prototype.queryIntersectsFeature = function (t, e, r, i, n, o) {
                            var s = translate(t, this.paint.get('fill-extrusion-translate'), this.paint.get('fill-extrusion-translate-anchor'), n, o);
                            return multiPolygonIntersectsMultiPolygon(s, r);
                        }, e.prototype.hasOffscreenPass = function () {
                            return 0 !== this.paint.get('fill-extrusion-opacity') && 'none' !== this.visibility;
                        }, e.prototype.resize = function () {
                            this.viewportFrame && (this.viewportFrame.destroy(), this.viewportFrame = null);
                        }, e;
                    }(StyleLayer);
                module.exports = FillExtrusionStyleLayer;
            },
            {
                '../../data/bucket/fill_extrusion_bucket': 46,
                '../../util/intersection_tests': 264,
                '../properties': 188,
                '../query_utils': 189,
                '../style_layer': 191,
                './fill_extrusion_style_layer_properties': 197
            }
        ],
        197: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'fill-extrusion-opacity': new DataConstantProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-opacity']),
                        'fill-extrusion-color': new DataDrivenProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-color']),
                        'fill-extrusion-translate': new DataConstantProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-translate']),
                        'fill-extrusion-translate-anchor': new DataConstantProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-translate-anchor']),
                        'fill-extrusion-pattern': new CrossFadedProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-pattern']),
                        'fill-extrusion-height': new DataDrivenProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-height']),
                        'fill-extrusion-base': new DataDrivenProperty(styleSpec['paint_fill-extrusion']['fill-extrusion-base'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        198: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), FillBucket = _dereq_('../../data/bucket/fill_bucket'), ref = _dereq_('../../util/intersection_tests'), multiPolygonIntersectsMultiPolygon = ref.multiPolygonIntersectsMultiPolygon, ref$1 = _dereq_('../query_utils'), translateDistance = ref$1.translateDistance, translate = ref$1.translate, properties = _dereq_('./fill_style_layer_properties'), ref$2 = _dereq_('../properties'), Transitionable = ref$2.Transitionable, Transitioning = ref$2.Transitioning, PossiblyEvaluated = ref$2.PossiblyEvaluated, FillStyleLayer = function (t) {
                        function e(e) {
                            t.call(this, e, properties);
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.recalculate = function (t) {
                            this.paint = this._transitioningPaint.possiblyEvaluate(t), void 0 === this._transitionablePaint.getValue('fill-outline-color') && (this.paint._values['fill-outline-color'] = this.paint._values['fill-color']);
                        }, e.prototype.createBucket = function (t) {
                            return new FillBucket(t);
                        }, e.prototype.queryRadius = function () {
                            return translateDistance(this.paint.get('fill-translate'));
                        }, e.prototype.queryIntersectsFeature = function (t, e, r, i, l, n) {
                            var a = translate(t, this.paint.get('fill-translate'), this.paint.get('fill-translate-anchor'), l, n);
                            return multiPolygonIntersectsMultiPolygon(a, r);
                        }, e;
                    }(StyleLayer);
                module.exports = FillStyleLayer;
            },
            {
                '../../data/bucket/fill_bucket': 44,
                '../../util/intersection_tests': 264,
                '../properties': 188,
                '../query_utils': 189,
                '../style_layer': 191,
                './fill_style_layer_properties': 199
            }
        ],
        199: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'fill-antialias': new DataConstantProperty(styleSpec.paint_fill['fill-antialias']),
                        'fill-opacity': new DataDrivenProperty(styleSpec.paint_fill['fill-opacity']),
                        'fill-color': new DataDrivenProperty(styleSpec.paint_fill['fill-color']),
                        'fill-outline-color': new DataDrivenProperty(styleSpec.paint_fill['fill-outline-color']),
                        'fill-translate': new DataConstantProperty(styleSpec.paint_fill['fill-translate']),
                        'fill-translate-anchor': new DataConstantProperty(styleSpec.paint_fill['fill-translate-anchor']),
                        'fill-pattern': new CrossFadedProperty(styleSpec.paint_fill['fill-pattern'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        200: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), HeatmapBucket = _dereq_('../../data/bucket/heatmap_bucket'), RGBAImage = _dereq_('../../util/image').RGBAImage, properties = _dereq_('./heatmap_style_layer_properties'), ref = _dereq_('../properties'), Transitionable = ref.Transitionable, Transitioning = ref.Transitioning, PossiblyEvaluated = ref.PossiblyEvaluated, HeatmapStyleLayer = function (t) {
                        function e(e) {
                            t.call(this, e, properties), this._updateColorRamp();
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.createBucket = function (t) {
                            return new HeatmapBucket(t);
                        }, e.prototype.setPaintProperty = function (e, r, a) {
                            t.prototype.setPaintProperty.call(this, e, r, a), 'heatmap-color' === e && this._updateColorRamp();
                        }, e.prototype._updateColorRamp = function () {
                            for (var t = this._transitionablePaint._values['heatmap-color'].value.expression, e = new Uint8Array(1024), r = e.length, a = 4; a < r; a += 4) {
                                var o = t.evaluate({ heatmapDensity: a / r });
                                e[a + 0] = Math.floor(255 * o.r / o.a), e[a + 1] = Math.floor(255 * o.g / o.a), e[a + 2] = Math.floor(255 * o.b / o.a), e[a + 3] = Math.floor(255 * o.a);
                            }
                            this.colorRamp = new RGBAImage({
                                width: 256,
                                height: 1
                            }, e), this.colorRampTexture = null;
                        }, e.prototype.resize = function () {
                            this.heatmapFbo && (this.heatmapFbo.destroy(), this.heatmapFbo = null);
                        }, e.prototype.queryRadius = function () {
                            return 0;
                        }, e.prototype.queryIntersectsFeature = function () {
                            return !1;
                        }, e.prototype.hasOffscreenPass = function () {
                            return 0 !== this.paint.get('heatmap-opacity') && 'none' !== this.visibility;
                        }, e;
                    }(StyleLayer);
                module.exports = HeatmapStyleLayer;
            },
            {
                '../../data/bucket/heatmap_bucket': 47,
                '../../util/image': 263,
                '../properties': 188,
                '../style_layer': 191,
                './heatmap_style_layer_properties': 201
            }
        ],
        201: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'heatmap-radius': new DataDrivenProperty(styleSpec.paint_heatmap['heatmap-radius']),
                        'heatmap-weight': new DataDrivenProperty(styleSpec.paint_heatmap['heatmap-weight']),
                        'heatmap-intensity': new DataConstantProperty(styleSpec.paint_heatmap['heatmap-intensity']),
                        'heatmap-color': new HeatmapColorProperty(styleSpec.paint_heatmap['heatmap-color']),
                        'heatmap-opacity': new DataConstantProperty(styleSpec.paint_heatmap['heatmap-opacity'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        202: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), properties = _dereq_('./hillshade_style_layer_properties'), ref = _dereq_('../properties'), Transitionable = ref.Transitionable, Transitioning = ref.Transitioning, PossiblyEvaluated = ref.PossiblyEvaluated, HillshadeStyleLayer = function (e) {
                        function r(r) {
                            e.call(this, r, properties);
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r.prototype.hasOffscreenPass = function () {
                            return 0 !== this.paint.get('hillshade-exaggeration') && 'none' !== this.visibility;
                        }, r;
                    }(StyleLayer);
                module.exports = HillshadeStyleLayer;
            },
            {
                '../properties': 188,
                '../style_layer': 191,
                './hillshade_style_layer_properties': 203
            }
        ],
        203: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'hillshade-illumination-direction': new DataConstantProperty(styleSpec.paint_hillshade['hillshade-illumination-direction']),
                        'hillshade-illumination-anchor': new DataConstantProperty(styleSpec.paint_hillshade['hillshade-illumination-anchor']),
                        'hillshade-exaggeration': new DataConstantProperty(styleSpec.paint_hillshade['hillshade-exaggeration']),
                        'hillshade-shadow-color': new DataConstantProperty(styleSpec.paint_hillshade['hillshade-shadow-color']),
                        'hillshade-highlight-color': new DataConstantProperty(styleSpec.paint_hillshade['hillshade-highlight-color']),
                        'hillshade-accent-color': new DataConstantProperty(styleSpec.paint_hillshade['hillshade-accent-color'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        204: [
            function (_dereq_, module, exports) {
                'use strict';
                function getLineWidth(t, e) {
                    return e > 0 ? e + 2 * t : t;
                }
                function offsetLine(t, e) {
                    for (var r = [], i = new Point(0, 0), n = 0; n < t.length; n++) {
                        for (var a = t[n], o = [], l = 0; l < a.length; l++) {
                            var u = a[l - 1], s = a[l], p = a[l + 1], y = 0 === l ? i : s.sub(u)._unit()._perp(), f = l === a.length - 1 ? i : p.sub(s)._unit()._perp(), c = y._add(f)._unit(), h = c.x * f.x + c.y * f.y;
                            c._mult(1 / h), o.push(c._mult(e)._add(s));
                        }
                        r.push(o);
                    }
                    return r;
                }
                var Point = _dereq_('@mapbox/point-geometry'), StyleLayer = _dereq_('../style_layer'), LineBucket = _dereq_('../../data/bucket/line_bucket'), ref = _dereq_('../../util/intersection_tests'), multiPolygonIntersectsBufferedMultiLine = ref.multiPolygonIntersectsBufferedMultiLine, ref$1 = _dereq_('../query_utils'), getMaximumPaintValue = ref$1.getMaximumPaintValue, translateDistance = ref$1.translateDistance, translate = ref$1.translate, properties = _dereq_('./line_style_layer_properties'), ref$2 = _dereq_('../../util/util'), extend = ref$2.extend, EvaluationParameters = _dereq_('../evaluation_parameters'), ref$3 = _dereq_('../properties'), Transitionable = ref$3.Transitionable, Transitioning = ref$3.Transitioning, Layout = ref$3.Layout, PossiblyEvaluated = ref$3.PossiblyEvaluated, DataDrivenProperty = ref$3.DataDrivenProperty, LineFloorwidthProperty = function (t) {
                        function e() {
                            t.apply(this, arguments);
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.possiblyEvaluate = function (e, r) {
                            return r = new EvaluationParameters(Math.floor(r.zoom), {
                                now: r.now,
                                fadeDuration: r.fadeDuration,
                                zoomHistory: r.zoomHistory,
                                transition: r.transition
                            }), t.prototype.possiblyEvaluate.call(this, e, r);
                        }, e.prototype.evaluate = function (e, r, i) {
                            return r = extend({}, r, { zoom: Math.floor(r.zoom) }), t.prototype.evaluate.call(this, e, r, i);
                        }, e;
                    }(DataDrivenProperty), lineFloorwidthProperty = new LineFloorwidthProperty(properties.paint.properties['line-width'].specification);
                lineFloorwidthProperty.useIntegerZoom = !0;
                var LineStyleLayer = function (t) {
                    function e(e) {
                        t.call(this, e, properties);
                    }
                    return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.recalculate = function (e) {
                        t.prototype.recalculate.call(this, e), this.paint._values['line-floorwidth'] = lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, e);
                    }, e.prototype.createBucket = function (t) {
                        return new LineBucket(t);
                    }, e.prototype.queryRadius = function (t) {
                        var e = t, r = getLineWidth(getMaximumPaintValue('line-width', this, e), getMaximumPaintValue('line-gap-width', this, e)), i = getMaximumPaintValue('line-offset', this, e);
                        return r / 2 + Math.abs(i) + translateDistance(this.paint.get('line-translate'));
                    }, e.prototype.queryIntersectsFeature = function (t, e, r, i, n, a) {
                        var o = translate(t, this.paint.get('line-translate'), this.paint.get('line-translate-anchor'), n, a), l = a / 2 * getLineWidth(this.paint.get('line-width').evaluate(e), this.paint.get('line-gap-width').evaluate(e)), u = this.paint.get('line-offset').evaluate(e);
                        return u && (r = offsetLine(r, u * a)), multiPolygonIntersectsBufferedMultiLine(o, r, l);
                    }, e;
                }(StyleLayer);
                module.exports = LineStyleLayer;
            },
            {
                '../../data/bucket/line_bucket': 49,
                '../../util/intersection_tests': 264,
                '../../util/util': 275,
                '../evaluation_parameters': 182,
                '../properties': 188,
                '../query_utils': 189,
                '../style_layer': 191,
                './line_style_layer_properties': 205,
                '@mapbox/point-geometry': 4
            }
        ],
        205: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, layout = new Properties({
                        'line-cap': new DataConstantProperty(styleSpec.layout_line['line-cap']),
                        'line-join': new DataDrivenProperty(styleSpec.layout_line['line-join']),
                        'line-miter-limit': new DataConstantProperty(styleSpec.layout_line['line-miter-limit']),
                        'line-round-limit': new DataConstantProperty(styleSpec.layout_line['line-round-limit'])
                    }), paint = new Properties({
                        'line-opacity': new DataDrivenProperty(styleSpec.paint_line['line-opacity']),
                        'line-color': new DataDrivenProperty(styleSpec.paint_line['line-color']),
                        'line-translate': new DataConstantProperty(styleSpec.paint_line['line-translate']),
                        'line-translate-anchor': new DataConstantProperty(styleSpec.paint_line['line-translate-anchor']),
                        'line-width': new DataDrivenProperty(styleSpec.paint_line['line-width']),
                        'line-gap-width': new DataDrivenProperty(styleSpec.paint_line['line-gap-width']),
                        'line-offset': new DataDrivenProperty(styleSpec.paint_line['line-offset']),
                        'line-blur': new DataDrivenProperty(styleSpec.paint_line['line-blur']),
                        'line-dasharray': new CrossFadedProperty(styleSpec.paint_line['line-dasharray']),
                        'line-pattern': new CrossFadedProperty(styleSpec.paint_line['line-pattern'])
                    });
                module.exports = {
                    paint: paint,
                    layout: layout
                };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        206: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), properties = _dereq_('./raster_style_layer_properties'), ref = _dereq_('../properties'), Transitionable = ref.Transitionable, Transitioning = ref.Transitioning, PossiblyEvaluated = ref.PossiblyEvaluated, RasterStyleLayer = function (e) {
                        function r(r) {
                            e.call(this, r, properties);
                        }
                        return e && (r.__proto__ = e), r.prototype = Object.create(e && e.prototype), r.prototype.constructor = r, r;
                    }(StyleLayer);
                module.exports = RasterStyleLayer;
            },
            {
                '../properties': 188,
                '../style_layer': 191,
                './raster_style_layer_properties': 207
            }
        ],
        207: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, paint = new Properties({
                        'raster-opacity': new DataConstantProperty(styleSpec.paint_raster['raster-opacity']),
                        'raster-hue-rotate': new DataConstantProperty(styleSpec.paint_raster['raster-hue-rotate']),
                        'raster-brightness-min': new DataConstantProperty(styleSpec.paint_raster['raster-brightness-min']),
                        'raster-brightness-max': new DataConstantProperty(styleSpec.paint_raster['raster-brightness-max']),
                        'raster-saturation': new DataConstantProperty(styleSpec.paint_raster['raster-saturation']),
                        'raster-contrast': new DataConstantProperty(styleSpec.paint_raster['raster-contrast']),
                        'raster-fade-duration': new DataConstantProperty(styleSpec.paint_raster['raster-fade-duration'])
                    });
                module.exports = { paint: paint };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        208: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('../style_layer'), SymbolBucket = _dereq_('../../data/bucket/symbol_bucket'), resolveTokens = _dereq_('../../util/token'), ref = _dereq_('../../style-spec/expression'), isExpression = ref.isExpression, properties = _dereq_('./symbol_style_layer_properties'), ref$1 = _dereq_('../properties'), Transitionable = ref$1.Transitionable, Transitioning = ref$1.Transitioning, Layout = ref$1.Layout, PossiblyEvaluated = ref$1.PossiblyEvaluated, SymbolStyleLayer = function (t) {
                        function e(e) {
                            t.call(this, e, properties);
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.recalculate = function (e) {
                            t.prototype.recalculate.call(this, e), 'auto' === this.layout.get('icon-rotation-alignment') && ('line' === this.layout.get('symbol-placement') ? this.layout._values['icon-rotation-alignment'] = 'map' : this.layout._values['icon-rotation-alignment'] = 'viewport'), 'auto' === this.layout.get('text-rotation-alignment') && ('line' === this.layout.get('symbol-placement') ? this.layout._values['text-rotation-alignment'] = 'map' : this.layout._values['text-rotation-alignment'] = 'viewport'), 'auto' === this.layout.get('text-pitch-alignment') && (this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment')), 'auto' === this.layout.get('icon-pitch-alignment') && (this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment'));
                        }, e.prototype.getValueAndResolveTokens = function (t, e) {
                            var o = this.layout.get(t).evaluate(e), i = this._unevaluatedLayout._values[t];
                            return i.isDataDriven() || isExpression(i.value) ? o : resolveTokens(e.properties, o);
                        }, e.prototype.createBucket = function (t) {
                            return new SymbolBucket(t);
                        }, e.prototype.queryRadius = function () {
                            return 0;
                        }, e.prototype.queryIntersectsFeature = function () {
                            return !1;
                        }, e;
                    }(StyleLayer);
                module.exports = SymbolStyleLayer;
            },
            {
                '../../data/bucket/symbol_bucket': 51,
                '../../style-spec/expression': 139,
                '../../util/token': 274,
                '../properties': 188,
                '../style_layer': 191,
                './symbol_style_layer_properties': 209
            }
        ],
        209: [
            function (_dereq_, module, exports) {
                'use strict';
                var styleSpec = _dereq_('../../style-spec/reference/latest'), ref = _dereq_('../properties'), Properties = ref.Properties, DataConstantProperty = ref.DataConstantProperty, DataDrivenProperty = ref.DataDrivenProperty, CrossFadedProperty = ref.CrossFadedProperty, HeatmapColorProperty = ref.HeatmapColorProperty, layout = new Properties({
                        'symbol-placement': new DataConstantProperty(styleSpec.layout_symbol['symbol-placement']),
                        'symbol-spacing': new DataConstantProperty(styleSpec.layout_symbol['symbol-spacing']),
                        'symbol-avoid-edges': new DataConstantProperty(styleSpec.layout_symbol['symbol-avoid-edges']),
                        'icon-allow-overlap': new DataConstantProperty(styleSpec.layout_symbol['icon-allow-overlap']),
                        'icon-ignore-placement': new DataConstantProperty(styleSpec.layout_symbol['icon-ignore-placement']),
                        'icon-optional': new DataConstantProperty(styleSpec.layout_symbol['icon-optional']),
                        'icon-rotation-alignment': new DataConstantProperty(styleSpec.layout_symbol['icon-rotation-alignment']),
                        'icon-size': new DataDrivenProperty(styleSpec.layout_symbol['icon-size']),
                        'icon-text-fit': new DataConstantProperty(styleSpec.layout_symbol['icon-text-fit']),
                        'icon-text-fit-padding': new DataConstantProperty(styleSpec.layout_symbol['icon-text-fit-padding']),
                        'icon-image': new DataDrivenProperty(styleSpec.layout_symbol['icon-image']),
                        'icon-rotate': new DataDrivenProperty(styleSpec.layout_symbol['icon-rotate']),
                        'icon-padding': new DataConstantProperty(styleSpec.layout_symbol['icon-padding']),
                        'icon-keep-upright': new DataConstantProperty(styleSpec.layout_symbol['icon-keep-upright']),
                        'icon-offset': new DataDrivenProperty(styleSpec.layout_symbol['icon-offset']),
                        'icon-anchor': new DataDrivenProperty(styleSpec.layout_symbol['icon-anchor']),
                        'icon-pitch-alignment': new DataConstantProperty(styleSpec.layout_symbol['icon-pitch-alignment']),
                        'text-pitch-alignment': new DataConstantProperty(styleSpec.layout_symbol['text-pitch-alignment']),
                        'text-rotation-alignment': new DataConstantProperty(styleSpec.layout_symbol['text-rotation-alignment']),
                        'text-field': new DataDrivenProperty(styleSpec.layout_symbol['text-field']),
                        'text-font': new DataDrivenProperty(styleSpec.layout_symbol['text-font']),
                        'text-size': new DataDrivenProperty(styleSpec.layout_symbol['text-size']),
                        'text-max-width': new DataDrivenProperty(styleSpec.layout_symbol['text-max-width']),
                        'text-line-height': new DataConstantProperty(styleSpec.layout_symbol['text-line-height']),
                        'text-letter-spacing': new DataDrivenProperty(styleSpec.layout_symbol['text-letter-spacing']),
                        'text-justify': new DataDrivenProperty(styleSpec.layout_symbol['text-justify']),
                        'text-anchor': new DataDrivenProperty(styleSpec.layout_symbol['text-anchor']),
                        'text-max-angle': new DataConstantProperty(styleSpec.layout_symbol['text-max-angle']),
                        'text-rotate': new DataDrivenProperty(styleSpec.layout_symbol['text-rotate']),
                        'text-padding': new DataConstantProperty(styleSpec.layout_symbol['text-padding']),
                        'text-keep-upright': new DataConstantProperty(styleSpec.layout_symbol['text-keep-upright']),
                        'text-transform': new DataDrivenProperty(styleSpec.layout_symbol['text-transform']),
                        'text-offset': new DataDrivenProperty(styleSpec.layout_symbol['text-offset']),
                        'text-allow-overlap': new DataConstantProperty(styleSpec.layout_symbol['text-allow-overlap']),
                        'text-ignore-placement': new DataConstantProperty(styleSpec.layout_symbol['text-ignore-placement']),
                        'text-optional': new DataConstantProperty(styleSpec.layout_symbol['text-optional'])
                    }), paint = new Properties({
                        'icon-opacity': new DataDrivenProperty(styleSpec.paint_symbol['icon-opacity']),
                        'icon-color': new DataDrivenProperty(styleSpec.paint_symbol['icon-color']),
                        'icon-halo-color': new DataDrivenProperty(styleSpec.paint_symbol['icon-halo-color']),
                        'icon-halo-width': new DataDrivenProperty(styleSpec.paint_symbol['icon-halo-width']),
                        'icon-halo-blur': new DataDrivenProperty(styleSpec.paint_symbol['icon-halo-blur']),
                        'icon-translate': new DataConstantProperty(styleSpec.paint_symbol['icon-translate']),
                        'icon-translate-anchor': new DataConstantProperty(styleSpec.paint_symbol['icon-translate-anchor']),
                        'text-opacity': new DataDrivenProperty(styleSpec.paint_symbol['text-opacity']),
                        'text-color': new DataDrivenProperty(styleSpec.paint_symbol['text-color']),
                        'text-halo-color': new DataDrivenProperty(styleSpec.paint_symbol['text-halo-color']),
                        'text-halo-width': new DataDrivenProperty(styleSpec.paint_symbol['text-halo-width']),
                        'text-halo-blur': new DataDrivenProperty(styleSpec.paint_symbol['text-halo-blur']),
                        'text-translate': new DataConstantProperty(styleSpec.paint_symbol['text-translate']),
                        'text-translate-anchor': new DataConstantProperty(styleSpec.paint_symbol['text-translate-anchor'])
                    });
                module.exports = {
                    paint: paint,
                    layout: layout
                };
            },
            {
                '../../style-spec/reference/latest': 151,
                '../properties': 188
            }
        ],
        210: [
            function (_dereq_, module, exports) {
                'use strict';
                var StyleLayer = _dereq_('./style_layer'), util = _dereq_('../util/util'), featureFilter = _dereq_('../style-spec/feature_filter'), groupByLayout = _dereq_('../style-spec/group_by_layout'), StyleLayerIndex = function (e) {
                        e && this.replace(e);
                    };
                StyleLayerIndex.prototype.replace = function (e) {
                    this._layerConfigs = {}, this._layers = {}, this.update(e, []);
                }, StyleLayerIndex.prototype.update = function (e, r) {
                    for (var t = this, a = 0, i = e; a < i.length; a += 1) {
                        var l = i[a];
                        t._layerConfigs[l.id] = l;
                        var y = t._layers[l.id] = StyleLayer.create(l);
                        y._featureFilter = featureFilter(y.filter);
                    }
                    for (var u = 0, s = r; u < s.length; u += 1) {
                        var o = s[u];
                        delete t._layerConfigs[o], delete t._layers[o];
                    }
                    this.familiesBySource = {};
                    for (var n = groupByLayout(util.values(this._layerConfigs)), f = 0, p = n; f < p.length; f += 1) {
                        var c = p[f], _ = c.map(function (e) {
                                return t._layers[e.id];
                            }), d = _[0];
                        if ('none' !== d.visibility) {
                            var v = d.source || '', g = t.familiesBySource[v];
                            g || (g = t.familiesBySource[v] = {});
                            var h = d.sourceLayer || '_geojsonTileLayer', L = g[h];
                            L || (L = g[h] = []), L.push(_);
                        }
                    }
                }, module.exports = StyleLayerIndex;
            },
            {
                '../style-spec/feature_filter': 148,
                '../style-spec/group_by_layout': 150,
                '../util/util': 275,
                './style_layer': 191
            }
        ],
        211: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = _dereq_('../style-spec/validate_style.min'), module.exports.emitErrors = function (r, e) {
                    if (e && e.length) {
                        for (var t = 0, o = e; t < o.length; t += 1) {
                            var s = o[t], i = s.message;
                            r.fire('error', { error: new Error(i) });
                        }
                        return !0;
                    }
                    return !1;
                };
            },
            { '../style-spec/validate_style.min': 181 }
        ],
        212: [
            function (_dereq_, module, exports) {
                'use strict';
                var ZoomHistory = function () {
                    this.first = !0;
                };
                ZoomHistory.prototype.update = function (o, t) {
                    var s = Math.floor(o);
                    return this.first ? (this.first = !1, this.lastIntegerZoom = s, this.lastIntegerZoomTime = 0, this.lastZoom = o, this.lastFloorZoom = s, !0) : (this.lastFloorZoom > s ? (this.lastIntegerZoom = s + 1, this.lastIntegerZoomTime = t) : this.lastFloorZoom < s && (this.lastIntegerZoom = s, this.lastIntegerZoomTime = t), o !== this.lastZoom && (this.lastZoom = o, this.lastFloorZoom = s, !0));
                }, module.exports = ZoomHistory;
            },
            {}
        ],
        213: [
            function (_dereq_, module, exports) {
                'use strict';
                var Point = _dereq_('@mapbox/point-geometry'), ref = _dereq_('../util/web_worker_transfer'), register = ref.register, Anchor = function (t) {
                        function e(e, r, o, n) {
                            t.call(this, e, r), this.angle = o, void 0 !== n && (this.segment = n);
                        }
                        return t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e, e.prototype.clone = function () {
                            return new e(this.x, this.y, this.angle, this.segment);
                        }, e;
                    }(Point);
                register('Anchor', Anchor), module.exports = Anchor;
            },
            {
                '../util/web_worker_transfer': 278,
                '@mapbox/point-geometry': 4
            }
        ],
        214: [
            function (_dereq_, module, exports) {
                'use strict';
                function checkMaxAngle(e, t, a, r, n) {
                    if (void 0 === t.segment) {
                        return !0;
                    }
                    for (var i = t, s = t.segment + 1, f = 0; f > -a / 2;) {
                        if (--s < 0) {
                            return !1;
                        }
                        f -= e[s].dist(i), i = e[s];
                    }
                    f += e[s].dist(e[s + 1]), s++;
                    for (var l = [], o = 0; f < a / 2;) {
                        var u = e[s - 1], c = e[s], g = e[s + 1];
                        if (!g) {
                            return !1;
                        }
                        var h = u.angleTo(c) - c.angleTo(g);
                        for (h = Math.abs((h + 3 * Math.PI) % (2 * Math.PI) - Math.PI), l.push({
                                distance: f,
                                angleDelta: h
                            }), o += h; f - l[0].distance > r;) {
                            o -= l.shift().angleDelta;
                        }
                        if (o > n) {
                            return !1;
                        }
                        s++, f += c.dist(g);
                    }
                    return !0;
                }
                module.exports = checkMaxAngle;
            },
            {}
        ],
        215: [
            function (_dereq_, module, exports) {
                'use strict';
                function clipLine(n, x, y, o, e) {
                    for (var r = [], t = 0; t < n.length; t++) {
                        for (var i = n[t], u = void 0, d = 0; d < i.length - 1; d++) {
                            var P = i[d], w = i[d + 1];
                            P.x < x && w.x < x || (P.x < x ? P = new Point(x, P.y + (w.y - P.y) * ((x - P.x) / (w.x - P.x)))._round() : w.x < x && (w = new Point(x, P.y + (w.y - P.y) * ((x - P.x) / (w.x - P.x)))._round()), P.y < y && w.y < y || (P.y < y ? P = new Point(P.x + (w.x - P.x) * ((y - P.y) / (w.y - P.y)), y)._round() : w.y < y && (w = new Point(P.x + (w.x - P.x) * ((y - P.y) / (w.y - P.y)), y)._round()), P.x >= o && w.x >= o || (P.x >= o ? P = new Point(o, P.y + (w.y - P.y) * ((o - P.x) / (w.x - P.x)))._round() : w.x >= o && (w = new Point(o, P.y + (w.y - P.y) * ((o - P.x) / (w.x - P.x)))._round()), P.y >= e && w.y >= e || (P.y >= e ? P = new Point(P.x + (w.x - P.x) * ((e - P.y) / (w.y - P.y)), e)._round() : w.y >= e && (w = new Point(P.x + (w.x - P.x) * ((e - P.y) / (w.y - P.y)), e)._round()), u && P.equals(u[u.length - 1]) || (u = [P], r.push(u)), u.push(w)))));
                        }
                    }
                    return r;
                }
                var Point = _dereq_('@mapbox/point-geometry');
                module.exports = clipLine;
            },
            { '@mapbox/point-geometry': 4 }
        ],
        216: [
            function (_dereq_, module, exports) {
                'use strict';
                var CollisionFeature = function (t, e, i, o, a, r, l, n, s, d, h) {
                    var u = l.top * n - s, f = l.bottom * n + s, c = l.left * n - s, x = l.right * n + s;
                    if (this.boxStartIndex = t.length, d) {
                        var m = f - u, v = x - c;
                        m > 0 && (m = Math.max(10 * n, m), this._addLineCollisionCircles(t, e, i, i.segment, v, m, o, a, r, h));
                    } else {
                        t.emplaceBack(i.x, i.y, c, u, x, f, o, a, r, 0, 0);
                    }
                    this.boxEndIndex = t.length;
                };
                CollisionFeature.prototype._addLineCollisionCircles = function (t, e, i, o, a, r, l, n, s, d) {
                    var h = r / 2, u = Math.floor(a / h), f = 1 + 0.4 * Math.log(d) / Math.LN2, c = Math.floor(u * f / 2), x = -r / 2, m = i, v = o + 1, C = x, b = -a / 2, g = b - a / 4;
                    do {
                        if (--v < 0) {
                            if (C > b) {
                                return;
                            }
                            v = 0;
                            break;
                        }
                        C -= e[v].dist(m), m = e[v];
                    } while (C > g);
                    for (var p = e[v].dist(e[v + 1]), M = -c; M < u + c; M++) {
                        var _ = M * h, k = b + _;
                        if (_ < 0 && (k += _), _ > a && (k += _ - a), !(k < C)) {
                            for (; C + p < k;) {
                                if (C += p, ++v + 1 >= e.length) {
                                    return;
                                }
                                p = e[v].dist(e[v + 1]);
                            }
                            var y = k - C, F = e[v], L = e[v + 1], B = L.sub(F)._unit()._mult(y)._add(F)._round(), I = Math.abs(k - x) < h ? 0 : 0.8 * (k - x);
                            t.emplaceBack(B.x, B.y, -r / 2, -r / 2, r / 2, r / 2, l, n, s, r / 2, I);
                        }
                    }
                }, module.exports = CollisionFeature;
            },
            {}
        ],
        217: [
            function (_dereq_, module, exports) {
                'use strict';
                function markCollisionCircleUsed(t, i, e) {
                    t[i + 4] = e ? 1 : 0;
                }
                var Point = _dereq_('@mapbox/point-geometry'), intersectionTests = _dereq_('../util/intersection_tests'), Grid = _dereq_('./grid_index'), glmatrix = _dereq_('@mapbox/gl-matrix'), mat4 = glmatrix.mat4, projection = _dereq_('../symbol/projection'), viewportPadding = 100, CollisionIndex = function (t, i, e) {
                        void 0 === i && (i = new Grid(t.width + 2 * viewportPadding, t.height + 2 * viewportPadding, 25)), void 0 === e && (e = new Grid(t.width + 2 * viewportPadding, t.height + 2 * viewportPadding, 25)), this.transform = t, this.grid = i, this.ignoredGrid = e, this.pitchfactor = Math.cos(t._pitch) * t.cameraToCenterDistance, this.screenRightBoundary = t.width + viewportPadding, this.screenBottomBoundary = t.height + viewportPadding;
                    };
                CollisionIndex.prototype.placeCollisionBox = function (t, i, e, n) {
                    var r = this.projectAndGetPerspectiveRatio(n, t.anchorPointX, t.anchorPointY), o = e * r.perspectiveRatio, s = t.x1 * o + r.point.x, a = t.y1 * o + r.point.y, c = t.x2 * o + r.point.x, p = t.y2 * o + r.point.y;
                    return !i && this.grid.hitTest(s, a, c, p) ? {
                        box: [],
                        offscreen: !1
                    } : {
                        box: [
                            s,
                            a,
                            c,
                            p
                        ],
                        offscreen: this.isOffscreen(s, a, c, p)
                    };
                }, CollisionIndex.prototype.approximateTileDistance = function (t, i, e, n, r) {
                    var o = r ? 1 : n / this.pitchfactor, s = t.lastSegmentViewportDistance * e;
                    return t.prevTileDistance + s + (o - 1) * s * Math.abs(Math.sin(i));
                }, CollisionIndex.prototype.placeCollisionCircles = function (t, i, e, n, r, o, s, a, c, p, d, l, h) {
                    var f = this, x = [], g = this.projectAnchor(p, o.anchorX, o.anchorY), u = {}, v = c / 24, y = o.lineOffsetX * c, m = o.lineOffsetY * c, I = new Point(o.anchorX, o.anchorY), P = projection.project(I, d).point, C = projection.placeFirstAndLastGlyph(v, a, y, m, !1, P, I, o, s, d, u, !0), w = !1, D = !0, b = g.perspectiveRatio * n, j = 1 / (n * e), T = 0, k = 0;
                    C && (T = this.approximateTileDistance(C.first.tileDistance, C.first.angle, j, g.cameraDistance, h), k = this.approximateTileDistance(C.last.tileDistance, C.last.angle, j, g.cameraDistance, h));
                    for (var G = 0; G < t.length; G += 5) {
                        var M = t[G], R = t[G + 1], q = t[G + 2], B = t[G + 3];
                        if (!C || B < -T || B > k) {
                            markCollisionCircleUsed(t, G, !1);
                        } else {
                            var A = f.projectPoint(p, M, R), O = q * b;
                            if (x.length > 0) {
                                var U = A.x - x[x.length - 4], X = A.y - x[x.length - 3];
                                if (O * O * 2 > U * U + X * X) {
                                    if (G + 8 < t.length) {
                                        var Y = t[G + 8];
                                        if (Y > -T && Y < k) {
                                            markCollisionCircleUsed(t, G, !1);
                                            continue;
                                        }
                                    }
                                }
                            }
                            var L = G / 5;
                            if (x.push(A.x, A.y, O, L), markCollisionCircleUsed(t, G, !0), D = D && f.isOffscreen(A.x - O, A.y - O, A.x + O, A.y + O), !i && f.grid.hitTestCircle(A.x, A.y, O)) {
                                if (!l) {
                                    return {
                                        circles: [],
                                        offscreen: !1
                                    };
                                }
                                w = !0;
                            }
                        }
                    }
                    return {
                        circles: w ? [] : x,
                        offscreen: D
                    };
                }, CollisionIndex.prototype.queryRenderedSymbols = function (t, i, e, n, r, o) {
                    var s = this, a = {}, c = [];
                    if (0 === t.length || 0 === this.grid.keysLength() && 0 === this.ignoredGrid.keysLength()) {
                        return c;
                    }
                    for (var p = this.transform.calculatePosMatrix(i.toUnwrapped()), d = [], l = 1 / 0, h = 1 / 0, f = -1 / 0, x = -1 / 0, g = 0; g < t.length; g++) {
                        for (var u = t[g], v = 0; v < u.length; v++) {
                            var y = s.projectPoint(p, u[v].x, u[v].y);
                            l = Math.min(l, y.x), h = Math.min(h, y.y), f = Math.max(f, y.x), x = Math.max(x, y.y), d.push(y);
                        }
                    }
                    for (var m = i.key, I = [], P = this.grid.query(l, h, f, x), C = 0; C < P.length; C++) {
                        P[C].sourceID === r && P[C].tileID === m && o[P[C].bucketInstanceId] && I.push(P[C].boxIndex);
                    }
                    for (var w = this.ignoredGrid.query(l, h, f, x), D = 0; D < w.length; D++) {
                        w[D].sourceID === r && w[D].tileID === m && o[w[D].bucketInstanceId] && I.push(w[D].boxIndex);
                    }
                    for (var b = 0; b < I.length; b++) {
                        var j = n.get(I[b]), T = j.sourceLayerIndex, k = j.featureIndex, G = j.bucketIndex;
                        if (void 0 === a[T] && (a[T] = {}), void 0 === a[T][k] && (a[T][k] = {}), !a[T][k][G]) {
                            var M = s.projectAndGetPerspectiveRatio(p, j.anchorPointX, j.anchorPointY), R = e * M.perspectiveRatio, q = j.x1 * R + M.point.x, B = j.y1 * R + M.point.y, A = j.x2 * R + M.point.x, O = j.y2 * R + M.point.y, U = [
                                    new Point(q, B),
                                    new Point(A, B),
                                    new Point(A, O),
                                    new Point(q, O)
                                ];
                            intersectionTests.polygonIntersectsPolygon(d, U) && (a[T][k][G] = !0, c.push(I[b]));
                        }
                    }
                    return c;
                }, CollisionIndex.prototype.insertCollisionBox = function (t, i, e, n, r, o) {
                    var s = i ? this.ignoredGrid : this.grid, a = {
                            tileID: e,
                            sourceID: n,
                            bucketInstanceId: r,
                            boxIndex: o
                        };
                    s.insert(a, t[0], t[1], t[2], t[3]);
                }, CollisionIndex.prototype.insertCollisionCircles = function (t, i, e, n, r, o) {
                    for (var s = i ? this.ignoredGrid : this.grid, a = 0; a < t.length; a += 4) {
                        var c = {
                            tileID: e,
                            sourceID: n,
                            bucketInstanceId: r,
                            boxIndex: o + t[a + 3]
                        };
                        s.insertCircle(c, t[a], t[a + 1], t[a + 2]);
                    }
                }, CollisionIndex.prototype.projectAnchor = function (t, i, e) {
                    var n = [
                        i,
                        e,
                        0,
                        1
                    ];
                    return projection.xyTransformMat4(n, n, t), {
                        perspectiveRatio: 0.5 + this.transform.cameraToCenterDistance / n[3] * 0.5,
                        cameraDistance: n[3]
                    };
                }, CollisionIndex.prototype.projectPoint = function (t, i, e) {
                    var n = [
                        i,
                        e,
                        0,
                        1
                    ];
                    return projection.xyTransformMat4(n, n, t), new Point((n[0] / n[3] + 1) / 2 * this.transform.width + viewportPadding, (-n[1] / n[3] + 1) / 2 * this.transform.height + viewportPadding);
                }, CollisionIndex.prototype.projectAndGetPerspectiveRatio = function (t, i, e) {
                    var n = [
                        i,
                        e,
                        0,
                        1
                    ];
                    return projection.xyTransformMat4(n, n, t), {
                        point: new Point((n[0] / n[3] + 1) / 2 * this.transform.width + viewportPadding, (-n[1] / n[3] + 1) / 2 * this.transform.height + viewportPadding),
                        perspectiveRatio: 0.5 + this.transform.cameraToCenterDistance / n[3] * 0.5
                    };
                }, CollisionIndex.prototype.isOffscreen = function (t, i, e, n) {
                    return e < viewportPadding || t >= this.screenRightBoundary || n < viewportPadding || i > this.screenBottomBoundary;
                }, module.exports = CollisionIndex;
            },
            {
                '../symbol/projection': 224,
                '../util/intersection_tests': 264,
                './grid_index': 220,
                '@mapbox/gl-matrix': 2,
                '@mapbox/point-geometry': 4
            }
        ],
        218: [
            function (_dereq_, module, exports) {
                'use strict';
                var EXTENT = _dereq_('../data/extent'), roundingFactor = 512 / EXTENT / 2, TileLayerIndex = function (e, s, r) {
                        var n = this;
                        this.tileID = e, this.indexedSymbolInstances = {}, this.bucketInstanceId = r;
                        for (var o = 0, t = s; o < t.length; o += 1) {
                            var i = t[o], a = i.key;
                            n.indexedSymbolInstances[a] || (n.indexedSymbolInstances[a] = []), n.indexedSymbolInstances[a].push({
                                crossTileID: i.crossTileID,
                                coord: n.getScaledCoordinates(i, e)
                            });
                        }
                    };
                TileLayerIndex.prototype.getScaledCoordinates = function (e, s) {
                    var r = s.canonical.z - this.tileID.canonical.z, n = roundingFactor / Math.pow(2, r), o = e.anchor;
                    return {
                        x: Math.floor((s.canonical.x * EXTENT + o.x) * n),
                        y: Math.floor((s.canonical.y * EXTENT + o.y) * n)
                    };
                }, TileLayerIndex.prototype.findMatches = function (e, s, r) {
                    for (var n = this, o = this.tileID.canonical.z < s.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - s.canonical.z), t = 0, i = e; t < i.length; t += 1) {
                        var a = i[t];
                        if (!a.crossTileID) {
                            var l = n.indexedSymbolInstances[a.key];
                            if (l) {
                                for (var c = n.getScaledCoordinates(a, s), d = 0, I = l; d < I.length; d += 1) {
                                    var y = I[d];
                                    if (Math.abs(y.coord.x - c.x) <= o && Math.abs(y.coord.y - c.y) <= o && !r[y.crossTileID]) {
                                        r[y.crossTileID] = !0, a.crossTileID = y.crossTileID;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                };
                var CrossTileIDs = function () {
                    this.maxCrossTileID = 0;
                };
                CrossTileIDs.prototype.generate = function () {
                    return ++this.maxCrossTileID;
                };
                var CrossTileSymbolLayerIndex = function () {
                    this.indexes = {}, this.usedCrossTileIDs = {};
                };
                CrossTileSymbolLayerIndex.prototype.addBucket = function (e, s, r) {
                    var n = this;
                    if (this.indexes[e.overscaledZ] && this.indexes[e.overscaledZ][e.key]) {
                        if (this.indexes[e.overscaledZ][e.key].bucketInstanceId === s.bucketInstanceId) {
                            return !1;
                        }
                        this.removeBucketCrossTileIDs(e.overscaledZ, this.indexes[e.overscaledZ][e.key]);
                    }
                    for (var o = 0, t = s.symbolInstances; o < t.length; o += 1) {
                        t[o].crossTileID = 0;
                    }
                    this.usedCrossTileIDs[e.overscaledZ] || (this.usedCrossTileIDs[e.overscaledZ] = {});
                    var i = this.usedCrossTileIDs[e.overscaledZ];
                    for (var a in n.indexes) {
                        var l = n.indexes[a];
                        if (Number(a) > e.overscaledZ) {
                            for (var c in l) {
                                var d = l[c];
                                d.tileID.isChildOf(e) && d.findMatches(s.symbolInstances, e, i);
                            }
                        } else {
                            var I = e.scaledTo(Number(a)), y = l[I.key];
                            y && y.findMatches(s.symbolInstances, e, i);
                        }
                    }
                    for (var v = 0, h = s.symbolInstances; v < h.length; v += 1) {
                        var u = h[v];
                        u.crossTileID || (u.crossTileID = r.generate(), i[u.crossTileID] = !0);
                    }
                    return void 0 === this.indexes[e.overscaledZ] && (this.indexes[e.overscaledZ] = {}), this.indexes[e.overscaledZ][e.key] = new TileLayerIndex(e, s.symbolInstances, s.bucketInstanceId), !0;
                }, CrossTileSymbolLayerIndex.prototype.removeBucketCrossTileIDs = function (e, s) {
                    var r = this;
                    for (var n in s.indexedSymbolInstances) {
                        for (var o = 0, t = s.indexedSymbolInstances[n]; o < t.length; o += 1) {
                            var i = t[o];
                            delete r.usedCrossTileIDs[e][i.crossTileID];
                        }
                    }
                }, CrossTileSymbolLayerIndex.prototype.removeStaleBuckets = function (e) {
                    var s = this, r = !1;
                    for (var n in s.indexes) {
                        var o = s.indexes[n];
                        for (var t in o) {
                            e[o[t].bucketInstanceId] || (s.removeBucketCrossTileIDs(n, o[t]), delete o[t], r = !0);
                        }
                    }
                    return r;
                };
                var CrossTileSymbolIndex = function () {
                    this.layerIndexes = {}, this.crossTileIDs = new CrossTileIDs(), this.maxBucketInstanceId = 0;
                };
                CrossTileSymbolIndex.prototype.addLayer = function (e, s) {
                    var r = this, n = this.layerIndexes[e.id];
                    void 0 === n && (n = this.layerIndexes[e.id] = new CrossTileSymbolLayerIndex());
                    for (var o = !1, t = {}, i = 0, a = s; i < a.length; i += 1) {
                        var l = a[i], c = l.getBucket(e);
                        c && (c.bucketInstanceId || (c.bucketInstanceId = ++r.maxBucketInstanceId), n.addBucket(l.tileID, c, r.crossTileIDs) && (o = !0), t[c.bucketInstanceId] = !0);
                    }
                    return n.removeStaleBuckets(t) && (o = !0), o;
                }, CrossTileSymbolIndex.prototype.pruneUnusedLayers = function (e) {
                    var s = this, r = {};
                    e.forEach(function (e) {
                        r[e] = !0;
                    });
                    for (var n in s.layerIndexes) {
                        r[n] || delete s.layerIndexes[n];
                    }
                }, module.exports = CrossTileSymbolIndex;
            },
            { '../data/extent': 53 }
        ],
        219: [
            function (_dereq_, module, exports) {
                'use strict';
                function getAnchors(e, r, t, n, a, l, o, i, c) {
                    var h = n ? 0.6 * l * o : 0, s = Math.max(n ? n.right - n.left : 0, a ? a.right - a.left : 0), u = 0 === e[0].x || e[0].x === c || 0 === e[0].y || e[0].y === c;
                    r - s * o < r / 4 && (r = s * o + r / 4);
                    var g = 2 * l;
                    return resample(e, u ? r / 2 * i % r : (s / 2 + g) * o * i % r, r, h, t, s * o, u, !1, c);
                }
                function resample(e, r, t, n, a, l, o, i, c) {
                    for (var h = l / 2, s = 0, u = 0; u < e.length - 1; u++) {
                        s += e[u].dist(e[u + 1]);
                    }
                    for (var g = 0, p = r - t, x = [], f = 0; f < e.length - 1; f++) {
                        for (var m = e[f], v = e[f + 1], y = m.dist(v), A = v.angleTo(m); p + t < g + y;) {
                            p += t;
                            var d = (p - g) / y, k = interpolate(m.x, v.x, d), q = interpolate(m.y, v.y, d);
                            if (k >= 0 && k < c && q >= 0 && q < c && p - h >= 0 && p + h <= s) {
                                var M = new Anchor(k, q, A, f);
                                M._round(), n && !checkMaxAngle(e, M, l, n, a) || x.push(M);
                            }
                        }
                        g += y;
                    }
                    return i || x.length || o || (x = resample(e, g / 2, t, n, a, l, o, !0, c)), x;
                }
                var interpolate = _dereq_('../style-spec/util/interpolate').number, Anchor = _dereq_('../symbol/anchor'), checkMaxAngle = _dereq_('./check_max_angle');
                module.exports = getAnchors;
            },
            {
                '../style-spec/util/interpolate': 158,
                '../symbol/anchor': 213,
                './check_max_angle': 214
            }
        ],
        220: [
            function (_dereq_, module, exports) {
                'use strict';
                var GridIndex = function (e, t, i) {
                    var r = this.boxCells = [], s = this.circleCells = [];
                    this.xCellCount = Math.ceil(e / i), this.yCellCount = Math.ceil(t / i);
                    for (var l = 0; l < this.xCellCount * this.yCellCount; l++) {
                        r.push([]), s.push([]);
                    }
                    this.circleKeys = [], this.boxKeys = [], this.bboxes = [], this.circles = [], this.width = e, this.height = t, this.xScale = this.xCellCount / e, this.yScale = this.yCellCount / t, this.boxUid = 0, this.circleUid = 0;
                };
                GridIndex.prototype.keysLength = function () {
                    return this.boxKeys.length + this.circleKeys.length;
                }, GridIndex.prototype.insert = function (e, t, i, r, s) {
                    this._forEachCell(t, i, r, s, this._insertBoxCell, this.boxUid++), this.boxKeys.push(e), this.bboxes.push(t), this.bboxes.push(i), this.bboxes.push(r), this.bboxes.push(s);
                }, GridIndex.prototype.insertCircle = function (e, t, i, r) {
                    this._forEachCell(t - r, i - r, t + r, i + r, this._insertCircleCell, this.circleUid++), this.circleKeys.push(e), this.circles.push(t), this.circles.push(i), this.circles.push(r);
                }, GridIndex.prototype._insertBoxCell = function (e, t, i, r, s, l) {
                    this.boxCells[s].push(l);
                }, GridIndex.prototype._insertCircleCell = function (e, t, i, r, s, l) {
                    this.circleCells[s].push(l);
                }, GridIndex.prototype._query = function (e, t, i, r, s) {
                    if (i < 0 || e > this.width || r < 0 || t > this.height) {
                        return !s && [];
                    }
                    var l = [];
                    if (e <= 0 && t <= 0 && this.width <= i && this.height <= r) {
                        l = Array.prototype.slice.call(this.boxKeys).concat(this.circleKeys);
                    } else {
                        var o = {
                            hitTest: s,
                            seenUids: {
                                box: {},
                                circle: {}
                            }
                        };
                        this._forEachCell(e, t, i, r, this._queryCell, l, o);
                    }
                    return s ? l.length > 0 : l;
                }, GridIndex.prototype._queryCircle = function (e, t, i, r) {
                    var s = e - i, l = e + i, o = t - i, h = t + i;
                    if (l < 0 || s > this.width || h < 0 || o > this.height) {
                        return !r && [];
                    }
                    var n = [], c = {
                            hitTest: r,
                            circle: {
                                x: e,
                                y: t,
                                radius: i
                            },
                            seenUids: {
                                box: {},
                                circle: {}
                            }
                        };
                    return this._forEachCell(s, o, l, h, this._queryCellCircle, n, c), r ? n.length > 0 : n;
                }, GridIndex.prototype.query = function (e, t, i, r) {
                    return this._query(e, t, i, r, !1);
                }, GridIndex.prototype.hitTest = function (e, t, i, r) {
                    return this._query(e, t, i, r, !0);
                }, GridIndex.prototype.hitTestCircle = function (e, t, i) {
                    return this._queryCircle(e, t, i, !0);
                }, GridIndex.prototype._queryCell = function (e, t, i, r, s, l, o) {
                    var h = this, n = o.seenUids, c = this.boxCells[s];
                    if (null !== c) {
                        for (var u = this.bboxes, d = 0, C = c; d < C.length; d += 1) {
                            var a = C[d];
                            if (!n.box[a]) {
                                n.box[a] = !0;
                                var x = 4 * a;
                                if (e <= u[x + 2] && t <= u[x + 3] && i >= u[x + 0] && r >= u[x + 1]) {
                                    if (o.hitTest) {
                                        return l.push(!0), !0;
                                    }
                                    l.push(h.boxKeys[a]);
                                }
                            }
                        }
                    }
                    var p = this.circleCells[s];
                    if (null !== p) {
                        for (var f = this.circles, y = 0, v = p; y < v.length; y += 1) {
                            var b = v[y];
                            if (!n.circle[b]) {
                                n.circle[b] = !0;
                                var _ = 3 * b;
                                if (h._circleAndRectCollide(f[_], f[_ + 1], f[_ + 2], e, t, i, r)) {
                                    if (o.hitTest) {
                                        return l.push(!0), !0;
                                    }
                                    l.push(h.circleKeys[b]);
                                }
                            }
                        }
                    }
                }, GridIndex.prototype._queryCellCircle = function (e, t, i, r, s, l, o) {
                    var h = this, n = o.circle, c = o.seenUids, u = this.boxCells[s];
                    if (null !== u) {
                        for (var d = this.bboxes, C = 0, a = u; C < a.length; C += 1) {
                            var x = a[C];
                            if (!c.box[x]) {
                                c.box[x] = !0;
                                var p = 4 * x;
                                if (h._circleAndRectCollide(n.x, n.y, n.radius, d[p + 0], d[p + 1], d[p + 2], d[p + 3])) {
                                    return l.push(!0), !0;
                                }
                            }
                        }
                    }
                    var f = this.circleCells[s];
                    if (null !== f) {
                        for (var y = this.circles, v = 0, b = f; v < b.length; v += 1) {
                            var _ = b[v];
                            if (!c.circle[_]) {
                                c.circle[_] = !0;
                                var G = 3 * _;
                                if (h._circlesCollide(y[G], y[G + 1], y[G + 2], n.x, n.y, n.radius)) {
                                    return l.push(!0), !0;
                                }
                            }
                        }
                    }
                }, GridIndex.prototype._forEachCell = function (e, t, i, r, s, l, o) {
                    for (var h = this, n = this._convertToXCellCoord(e), c = this._convertToYCellCoord(t), u = this._convertToXCellCoord(i), d = this._convertToYCellCoord(r), C = n; C <= u; C++) {
                        for (var a = c; a <= d; a++) {
                            var x = h.xCellCount * a + C;
                            if (s.call(h, e, t, i, r, x, l, o)) {
                                return;
                            }
                        }
                    }
                }, GridIndex.prototype._convertToXCellCoord = function (e) {
                    return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(e * this.xScale)));
                }, GridIndex.prototype._convertToYCellCoord = function (e) {
                    return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(e * this.yScale)));
                }, GridIndex.prototype._circlesCollide = function (e, t, i, r, s, l) {
                    var o = r - e, h = s - t, n = i + l;
                    return n * n > o * o + h * h;
                }, GridIndex.prototype._circleAndRectCollide = function (e, t, i, r, s, l, o) {
                    var h = (l - r) / 2, n = Math.abs(e - (r + h));
                    if (n > h + i) {
                        return !1;
                    }
                    var c = (o - s) / 2, u = Math.abs(t - (s + c));
                    if (u > c + i) {
                        return !1;
                    }
                    if (n <= h || u <= c) {
                        return !0;
                    }
                    var d = n - h, C = u - c;
                    return d * d + C * C <= i * i;
                }, module.exports = GridIndex;
            },
            {}
        ],
        221: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = function (e) {
                    function t(t) {
                        g.push(e[t]), l++;
                    }
                    function r(e, t, r) {
                        var n = u[e];
                        return delete u[e], u[t] = n, g[n].geometry[0].pop(), g[n].geometry[0] = g[n].geometry[0].concat(r[0]), n;
                    }
                    function n(e, t, r) {
                        var n = i[t];
                        return delete i[t], i[e] = n, g[n].geometry[0].shift(), g[n].geometry[0] = r[0].concat(g[n].geometry[0]), n;
                    }
                    function o(e, t, r) {
                        var n = r ? t[0][t[0].length - 1] : t[0][0];
                        return e + ':' + n.x + ':' + n.y;
                    }
                    for (var i = {}, u = {}, g = [], l = 0, m = 0; m < e.length; m++) {
                        var y = e[m], c = y.geometry, f = y.text;
                        if (f) {
                            var a = o(f, c), s = o(f, c, !0);
                            if (a in u && s in i && u[a] !== i[s]) {
                                var v = n(a, s, c), d = r(a, s, g[v].geometry);
                                delete i[a], delete u[s], u[o(f, g[d].geometry, !0)] = d, g[v].geometry = null;
                            } else {
                                a in u ? r(a, s, c) : s in i ? n(a, s, c) : (t(m), i[a] = l - 1, u[s] = l - 1);
                            }
                        } else {
                            t(m);
                        }
                    }
                    return g.filter(function (e) {
                        return e.geometry;
                    });
                };
            },
            {}
        ],
        222: [
            function (_dereq_, module, exports) {
                'use strict';
                var ref = _dereq_('../util/web_worker_transfer'), register = ref.register, OpacityState = function () {
                        this.opacity = 0, this.targetOpacity = 0, this.time = 0;
                    };
                OpacityState.prototype.clone = function () {
                    var t = new OpacityState();
                    return t.opacity = this.opacity, t.targetOpacity = this.targetOpacity, t.time = this.time, t;
                }, register('OpacityState', OpacityState), module.exports = OpacityState;
            },
            { '../util/web_worker_transfer': 278 }
        ],
        223: [
            function (_dereq_, module, exports) {
                'use strict';
                function updateCollisionVertices(e, t, i) {
                    e.emplaceBack(t ? 1 : 0, i ? 1 : 0), e.emplaceBack(t ? 1 : 0, i ? 1 : 0), e.emplaceBack(t ? 1 : 0, i ? 1 : 0), e.emplaceBack(t ? 1 : 0, i ? 1 : 0);
                }
                function packOpacity(e) {
                    if (0 === e.opacity && !e.placed) {
                        return 0;
                    }
                    if (1 === e.opacity && e.placed) {
                        return 4294967295;
                    }
                    var t = e.placed ? 1 : 0, i = Math.floor(127 * e.opacity);
                    return i * shift25 + t * shift24 + i * shift17 + t * shift16 + i * shift9 + t * shift8 + i * shift1 + t;
                }
                var CollisionIndex = _dereq_('./collision_index'), EXTENT = _dereq_('../data/extent'), symbolSize = _dereq_('./symbol_size'), projection = _dereq_('./projection'), symbolLayoutProperties = _dereq_('../style/style_layer/symbol_style_layer_properties').layout, pixelsToTileUnits = _dereq_('../source/pixels_to_tile_units'), OpacityState = function (e, t, i, o) {
                        this.opacity = e ? Math.max(0, Math.min(1, e.opacity + (e.placed ? t : -t))) : o && i ? 1 : 0, this.placed = i;
                    };
                OpacityState.prototype.isHidden = function () {
                    return 0 === this.opacity && !this.placed;
                };
                var JointOpacityState = function (e, t, i, o, a) {
                    this.text = new OpacityState(e ? e.text : null, t, i, a), this.icon = new OpacityState(e ? e.icon : null, t, o, a);
                };
                JointOpacityState.prototype.isHidden = function () {
                    return this.text.isHidden() && this.icon.isHidden();
                };
                var JointPlacement = function (e, t, i) {
                        this.text = e, this.icon = t, this.skipFade = i;
                    }, Placement = function (e, t) {
                        this.transform = e.clone(), this.collisionIndex = new CollisionIndex(this.transform), this.placements = {}, this.opacities = {}, this.stale = !1, this.fadeDuration = t;
                    };
                Placement.prototype.placeLayerTile = function (e, t, i, o) {
                    var a = t.getBucket(e);
                    if (a) {
                        var l = a.layers[0].layout, n = Math.pow(2, this.transform.zoom - t.tileID.overscaledZ), r = t.tileSize / EXTENT, s = this.transform.calculatePosMatrix(t.tileID.toUnwrapped()), c = projection.getLabelPlaneMatrix(s, 'map' === l.get('text-pitch-alignment'), 'map' === l.get('text-rotation-alignment'), this.transform, pixelsToTileUnits(t, 1, this.transform.zoom)), p = projection.getLabelPlaneMatrix(s, 'map' === l.get('icon-pitch-alignment'), 'map' === l.get('icon-rotation-alignment'), this.transform, pixelsToTileUnits(t, 1, this.transform.zoom));
                        this.placeLayerBucket(a, s, c, p, n, r, i, o, t.collisionBoxArray, t.tileID.key, e.source);
                    }
                }, Placement.prototype.placeLayerBucket = function (e, t, i, o, a, l, n, r, s, c, p) {
                    for (var x = this, y = e.layers[0].layout, h = symbolSize.evaluateSizeForZoom(e.textSizeData, this.transform.zoom, symbolLayoutProperties.properties['text-size']), m = !e.hasTextData() || y.get('text-optional'), d = !e.hasIconData() || y.get('icon-optional'), u = 0, f = e.symbolInstances; u < f.length; u += 1) {
                        var B = f[u];
                        if (!r[B.crossTileID]) {
                            var g = !1, I = !1, v = !0, C = null, D = null, T = null;
                            B.collisionArrays || (B.collisionArrays = e.deserializeCollisionBoxes(s, B.textBoxStartIndex, B.textBoxEndIndex, B.iconBoxStartIndex, B.iconBoxEndIndex)), B.collisionArrays.textBox && (C = x.collisionIndex.placeCollisionBox(B.collisionArrays.textBox, y.get('text-allow-overlap'), l, t), g = C.box.length > 0, v = v && C.offscreen);
                            var V = B.collisionArrays.textCircles;
                            if (V) {
                                var S = e.text.placedSymbolArray.get(B.placedTextSymbolIndices[0]), A = symbolSize.evaluateSizeForFeature(e.textSizeData, h, S);
                                D = x.collisionIndex.placeCollisionCircles(V, y.get('text-allow-overlap'), a, l, B.key, S, e.lineVertexArray, e.glyphOffsetArray, A, t, i, n, 'map' === y.get('text-pitch-alignment')), g = y.get('text-allow-overlap') || D.circles.length > 0, v = v && D.offscreen;
                            }
                            B.collisionArrays.iconBox && (T = x.collisionIndex.placeCollisionBox(B.collisionArrays.iconBox, y.get('icon-allow-overlap'), l, t), I = T.box.length > 0, v = v && T.offscreen), m || d ? d ? m || (I = I && g) : g = I && g : I = g = I && g, g && C && x.collisionIndex.insertCollisionBox(C.box, y.get('text-ignore-placement'), c, p, e.bucketInstanceId, B.textBoxStartIndex), I && T && x.collisionIndex.insertCollisionBox(T.box, y.get('icon-ignore-placement'), c, p, e.bucketInstanceId, B.iconBoxStartIndex), g && D && x.collisionIndex.insertCollisionCircles(D.circles, y.get('text-ignore-placement'), c, p, e.bucketInstanceId, B.textBoxStartIndex), x.placements[B.crossTileID] = new JointPlacement(g, I, v || e.justReloaded), r[B.crossTileID] = !0;
                        }
                    }
                    e.justReloaded = !1;
                }, Placement.prototype.commit = function (e, t) {
                    var i = this;
                    this.commitTime = t;
                    var o = !1, a = e && 0 !== this.fadeDuration ? (this.commitTime - e.commitTime) / this.fadeDuration : 1, l = e ? e.opacities : {};
                    for (var n in i.placements) {
                        var r = i.placements[n], s = l[n];
                        s ? (i.opacities[n] = new JointOpacityState(s, a, r.text, r.icon), o = o || r.text !== s.text.placed || r.icon !== s.icon.placed) : (i.opacities[n] = new JointOpacityState(null, a, r.text, r.icon, r.skipFade), o = o || r.text || r.icon);
                    }
                    for (var c in l) {
                        var p = l[c];
                        if (!i.opacities[c]) {
                            var x = new JointOpacityState(p, a, !1, !1);
                            x.isHidden() || (i.opacities[c] = x, o = o || p.text.placed || p.icon.placed);
                        }
                    }
                    o ? this.lastPlacementChangeTime = t : 'number' != typeof this.lastPlacementChangeTime && (this.lastPlacementChangeTime = e ? e.lastPlacementChangeTime : t);
                }, Placement.prototype.updateLayerOpacities = function (e, t) {
                    for (var i = this, o = {}, a = 0, l = t; a < l.length; a += 1) {
                        var n = l[a], r = n.getBucket(e);
                        r && i.updateBucketOpacities(r, o, n.collisionBoxArray);
                    }
                }, Placement.prototype.updateBucketOpacities = function (e, t, i) {
                    var o = this;
                    e.hasTextData() && e.text.opacityVertexArray.clear(), e.hasIconData() && e.icon.opacityVertexArray.clear(), e.hasCollisionBoxData() && e.collisionBox.collisionVertexArray.clear(), e.hasCollisionCircleData() && e.collisionCircle.collisionVertexArray.clear();
                    for (var a = e.layers[0].layout, l = new JointOpacityState(null, 0, a.get('text-allow-overlap'), a.get('icon-allow-overlap'), !0), n = 0; n < e.symbolInstances.length; n++) {
                        var r = e.symbolInstances[n], s = t[r.crossTileID], c = o.opacities[r.crossTileID];
                        c ? s && (c = l) : (c = l, o.opacities[r.crossTileID] = c), t[r.crossTileID] = !0;
                        var p = r.numGlyphVertices > 0 || r.numVerticalGlyphVertices > 0, x = r.numIconVertices > 0;
                        if (p) {
                            for (var y = packOpacity(c.text), h = (r.numGlyphVertices + r.numVerticalGlyphVertices) / 4, m = 0; m < h; m++) {
                                e.text.opacityVertexArray.emplaceBack(y);
                            }
                            for (var d = 0, u = r.placedTextSymbolIndices; d < u.length; d += 1) {
                                var f = u[d];
                                e.text.placedSymbolArray.get(f).hidden = c.text.isHidden();
                            }
                        }
                        if (x) {
                            for (var B = packOpacity(c.icon), g = 0; g < r.numIconVertices / 4; g++) {
                                e.icon.opacityVertexArray.emplaceBack(B);
                            }
                            e.icon.placedSymbolArray.get(n).hidden = c.icon.isHidden();
                        }
                        r.collisionArrays || (r.collisionArrays = e.deserializeCollisionBoxes(i, r.textBoxStartIndex, r.textBoxEndIndex, r.iconBoxStartIndex, r.iconBoxEndIndex));
                        var I = r.collisionArrays;
                        if (I) {
                            I.textBox && e.hasCollisionBoxData() && updateCollisionVertices(e.collisionBox.collisionVertexArray, c.text.placed, !1), I.iconBox && e.hasCollisionBoxData() && updateCollisionVertices(e.collisionBox.collisionVertexArray, c.icon.placed, !1);
                            var v = I.textCircles;
                            if (v && e.hasCollisionCircleData()) {
                                for (var C = 0; C < v.length; C += 5) {
                                    var D = s || 0 === v[C + 4];
                                    updateCollisionVertices(e.collisionCircle.collisionVertexArray, c.text.placed, D);
                                }
                            }
                        }
                    }
                    e.sortFeatures(this.transform.angle), e.hasTextData() && e.text.opacityVertexBuffer && e.text.opacityVertexBuffer.updateData(e.text.opacityVertexArray), e.hasIconData() && e.icon.opacityVertexBuffer && e.icon.opacityVertexBuffer.updateData(e.icon.opacityVertexArray), e.hasCollisionBoxData() && e.collisionBox.collisionVertexBuffer && e.collisionBox.collisionVertexBuffer.updateData(e.collisionBox.collisionVertexArray), e.hasCollisionCircleData() && e.collisionCircle.collisionVertexBuffer && e.collisionCircle.collisionVertexBuffer.updateData(e.collisionCircle.collisionVertexArray);
                }, Placement.prototype.symbolFadeChange = function (e) {
                    return 0 === this.fadeDuration ? 1 : (e - this.commitTime) / this.fadeDuration;
                }, Placement.prototype.hasTransitions = function (e) {
                    return this.stale || e - this.lastPlacementChangeTime < this.fadeDuration;
                }, Placement.prototype.stillRecent = function (e) {
                    return 'undefined' !== this.commitTime && this.commitTime + this.fadeDuration > e;
                }, Placement.prototype.setStale = function () {
                    this.stale = !0;
                };
                var shift25 = Math.pow(2, 25), shift24 = Math.pow(2, 24), shift17 = Math.pow(2, 17), shift16 = Math.pow(2, 16), shift9 = Math.pow(2, 9), shift8 = Math.pow(2, 8), shift1 = Math.pow(2, 1);
                module.exports = Placement;
            },
            {
                '../data/extent': 53,
                '../source/pixels_to_tile_units': 104,
                '../style/style_layer/symbol_style_layer_properties': 209,
                './collision_index': 217,
                './projection': 224,
                './symbol_size': 228
            }
        ],
        224: [
            function (_dereq_, module, exports) {
                'use strict';
                function getLabelPlaneMatrix(e, t, r, n, a) {
                    var i = mat4.identity(new Float32Array(16));
                    return t ? (mat4.identity(i), mat4.scale(i, i, [
                        1 / a,
                        1 / a,
                        1
                    ]), r || mat4.rotateZ(i, i, n.angle)) : (mat4.scale(i, i, [
                        n.width / 2,
                        -n.height / 2,
                        1
                    ]), mat4.translate(i, i, [
                        1,
                        -1,
                        0
                    ]), mat4.multiply(i, i, e)), i;
                }
                function getGlCoordMatrix(e, t, r, n, a) {
                    var i = mat4.identity(new Float32Array(16));
                    return t ? (mat4.multiply(i, i, e), mat4.scale(i, i, [
                        a,
                        a,
                        1
                    ]), r || mat4.rotateZ(i, i, -n.angle)) : (mat4.scale(i, i, [
                        1,
                        -1,
                        1
                    ]), mat4.translate(i, i, [
                        -1,
                        -1,
                        0
                    ]), mat4.scale(i, i, [
                        2 / n.width,
                        2 / n.height,
                        1
                    ])), i;
                }
                function project(e, t) {
                    var r = [
                        e.x,
                        e.y,
                        0,
                        1
                    ];
                    xyTransformMat4(r, r, t);
                    var n = r[3];
                    return {
                        point: new Point(r[0] / n, r[1] / n),
                        signedDistanceFromCamera: n
                    };
                }
                function isVisible(e, t) {
                    var r = e[0] / e[3], n = e[1] / e[3];
                    return r >= -t[0] && r <= t[0] && n >= -t[1] && n <= t[1];
                }
                function updateLineLabels(e, t, r, n, a, i, o, l) {
                    var s = n ? e.textSizeData : e.iconSizeData, p = symbolSize.evaluateSizeForZoom(s, r.transform.zoom, symbolLayoutProperties.properties[n ? 'text-size' : 'icon-size']), u = [
                            256 / r.width * 2 + 1,
                            256 / r.height * 2 + 1
                        ], y = n ? e.text.dynamicLayoutVertexArray : e.icon.dynamicLayoutVertexArray;
                    y.clear();
                    for (var c = e.lineVertexArray, m = n ? e.text.placedSymbolArray : e.icon.placedSymbolArray, d = r.transform.width / r.transform.height, g = !1, h = 0; h < m.length; h++) {
                        var f = m.get(h);
                        if (f.hidden || f.writingMode === WritingMode.vertical && !g) {
                            hideGlyphs(f.numGlyphs, y);
                        } else {
                            g = !1;
                            var x = [
                                f.anchorX,
                                f.anchorY,
                                0,
                                1
                            ];
                            if (vec4.transformMat4(x, x, t), isVisible(x, u)) {
                                var v = x[3], b = 0.5 + v / r.transform.cameraToCenterDistance * 0.5, L = symbolSize.evaluateSizeForFeature(s, p, f), A = o ? L * b : L / b, G = new Point(f.anchorX, f.anchorY), M = project(G, a).point, S = {}, w = placeGlyphsAlongLine(f, A, !1, l, t, a, i, e.glyphOffsetArray, c, y, M, G, S, d);
                                g = w.useVertical, (w.notEnoughRoom || g || w.needsFlipping && placeGlyphsAlongLine(f, A, !0, l, t, a, i, e.glyphOffsetArray, c, y, M, G, S, d).notEnoughRoom) && hideGlyphs(f.numGlyphs, y);
                            } else {
                                hideGlyphs(f.numGlyphs, y);
                            }
                        }
                    }
                    n ? e.text.dynamicLayoutVertexBuffer.updateData(y) : e.icon.dynamicLayoutVertexBuffer.updateData(y);
                }
                function placeFirstAndLastGlyph(e, t, r, n, a, i, o, l, s, p, u, y) {
                    var c = l.glyphStartIndex + l.numGlyphs, m = l.lineStartIndex, d = l.lineStartIndex + l.lineLength, g = t.getoffsetX(l.glyphStartIndex), h = t.getoffsetX(c - 1), f = placeGlyphAlongLine(e * g, r, n, a, i, o, l.segment, m, d, s, p, u, y);
                    if (!f) {
                        return null;
                    }
                    var x = placeGlyphAlongLine(e * h, r, n, a, i, o, l.segment, m, d, s, p, u, y);
                    return x ? {
                        first: f,
                        last: x
                    } : null;
                }
                function requiresOrientationChange(e, t, r, n) {
                    if (e === WritingMode.horizontal) {
                        if (Math.abs(r.y - t.y) > Math.abs(r.x - t.x) * n) {
                            return { useVertical: !0 };
                        }
                    }
                    return (e === WritingMode.vertical ? t.y < r.y : t.x > r.x) ? { needsFlipping: !0 } : null;
                }
                function placeGlyphsAlongLine(e, t, r, n, a, i, o, l, s, p, u, y, c, m) {
                    var d, g = t / 24, h = e.lineOffsetX * t, f = e.lineOffsetY * t;
                    if (e.numGlyphs > 1) {
                        var x = e.glyphStartIndex + e.numGlyphs, v = e.lineStartIndex, b = e.lineStartIndex + e.lineLength, L = placeFirstAndLastGlyph(g, l, h, f, r, u, y, e, s, i, c, !1);
                        if (!L) {
                            return { notEnoughRoom: !0 };
                        }
                        var A = project(L.first.point, o).point, G = project(L.last.point, o).point;
                        if (n && !r) {
                            var M = requiresOrientationChange(e.writingMode, A, G, m);
                            if (M) {
                                return M;
                            }
                        }
                        d = [L.first];
                        for (var S = e.glyphStartIndex + 1; S < x - 1; S++) {
                            d.push(placeGlyphAlongLine(g * l.getoffsetX(S), h, f, r, u, y, e.segment, v, b, s, i, c, !1));
                        }
                        d.push(L.last);
                    } else {
                        if (n && !r) {
                            var w = project(y, a).point, F = e.lineStartIndex + e.segment + 1, D = new Point(s.getx(F), s.gety(F)), I = project(D, a), j = I.signedDistanceFromCamera > 0 ? I.point : projectTruncatedLineSegment(y, D, w, 1, a), z = requiresOrientationChange(e.writingMode, w, j, m);
                            if (z) {
                                return z;
                            }
                        }
                        var P = placeGlyphAlongLine(g * l.getoffsetX(e.glyphStartIndex), h, f, r, u, y, e.segment, e.lineStartIndex, e.lineStartIndex + e.lineLength, s, i, c, !1);
                        if (!P) {
                            return { notEnoughRoom: !0 };
                        }
                        d = [P];
                    }
                    for (var _ = 0, C = d; _ < C.length; _ += 1) {
                        var V = C[_];
                        addDynamicAttributes(p, V.point, V.angle);
                    }
                    return {};
                }
                function projectTruncatedLineSegment(e, t, r, n, a) {
                    var i = project(e.add(e.sub(t)._unit()), a).point, o = r.sub(i);
                    return r.add(o._mult(n / o.mag()));
                }
                function placeGlyphAlongLine(e, t, r, n, a, i, o, l, s, p, u, y, c) {
                    var m = n ? e - t : e + t, d = m > 0 ? 1 : -1, g = 0;
                    n && (d *= -1, g = Math.PI), d < 0 && (g += Math.PI);
                    for (var h = d > 0 ? l + o : l + o + 1, f = h, x = a, v = a, b = 0, L = 0, A = Math.abs(m); b + L <= A;) {
                        if ((h += d) < l || h >= s) {
                            return null;
                        }
                        if (v = x, void 0 === (x = y[h])) {
                            var G = new Point(p.getx(h), p.gety(h)), M = project(G, u);
                            if (M.signedDistanceFromCamera > 0) {
                                x = y[h] = M.point;
                            } else {
                                var S = h - d;
                                x = projectTruncatedLineSegment(0 === b ? i : new Point(p.getx(S), p.gety(S)), G, v, A - b + 1, u);
                            }
                        }
                        b += L, L = v.dist(x);
                    }
                    var w = (A - b) / L, F = x.sub(v), D = F.mult(w)._add(v);
                    return D._add(F._unit()._perp()._mult(r * d)), {
                        point: D,
                        angle: g + Math.atan2(x.y - v.y, x.x - v.x),
                        tileDistance: c ? {
                            prevTileDistance: h - d === f ? 0 : p.gettileUnitDistanceFromAnchor(h - d),
                            lastSegmentViewportDistance: A - b
                        } : null
                    };
                }
                function hideGlyphs(e, t) {
                    for (var r = 0; r < e; r++) {
                        var n = t.length;
                        t.resize(n + 4), t.float32.set(hiddenGlyphAttributes, 3 * n);
                    }
                }
                function xyTransformMat4(e, t, r) {
                    var n = t[0], a = t[1];
                    return e[0] = r[0] * n + r[4] * a + r[12], e[1] = r[1] * n + r[5] * a + r[13], e[3] = r[3] * n + r[7] * a + r[15], e;
                }
                var Point = _dereq_('@mapbox/point-geometry'), ref = _dereq_('@mapbox/gl-matrix'), mat4 = ref.mat4, vec4 = ref.vec4, symbolSize = _dereq_('./symbol_size'), ref$1 = _dereq_('../data/bucket/symbol_bucket'), addDynamicAttributes = ref$1.addDynamicAttributes, symbolLayoutProperties = _dereq_('../style/style_layer/symbol_style_layer_properties').layout, WritingMode = _dereq_('../symbol/shaping').WritingMode;
                module.exports = {
                    updateLineLabels: updateLineLabels,
                    getLabelPlaneMatrix: getLabelPlaneMatrix,
                    getGlCoordMatrix: getGlCoordMatrix,
                    project: project,
                    placeFirstAndLastGlyph: placeFirstAndLastGlyph,
                    xyTransformMat4: xyTransformMat4
                };
                var hiddenGlyphAttributes = new Float32Array([
                    -1 / 0,
                    -1 / 0,
                    0,
                    -1 / 0,
                    -1 / 0,
                    0,
                    -1 / 0,
                    -1 / 0,
                    0,
                    -1 / 0,
                    -1 / 0,
                    0
                ]);
            },
            {
                '../data/bucket/symbol_bucket': 51,
                '../style/style_layer/symbol_style_layer_properties': 209,
                '../symbol/shaping': 226,
                './symbol_size': 228,
                '@mapbox/gl-matrix': 2,
                '@mapbox/point-geometry': 4
            }
        ],
        225: [
            function (_dereq_, module, exports) {
                'use strict';
                function getIconQuads(t, e, i, o, n, a, r) {
                    var u, l, g, d, f = e.image, c = i.layout, h = e.top - 1 / f.pixelRatio, x = e.left - 1 / f.pixelRatio, p = e.bottom + 1 / f.pixelRatio, s = e.right + 1 / f.pixelRatio;
                    if ('none' !== c.get('icon-text-fit') && n) {
                        var P = s - x, _ = p - h, w = c.get('text-size').evaluate(r) / 24, m = n.left * w, v = n.right * w, y = n.top * w, M = n.bottom * w, R = v - m, b = M - y, G = c.get('icon-text-fit-padding')[0], B = c.get('icon-text-fit-padding')[1], I = c.get('icon-text-fit-padding')[2], Q = c.get('icon-text-fit-padding')[3], O = 'width' === c.get('icon-text-fit') ? 0.5 * (b - _) : 0, A = 'height' === c.get('icon-text-fit') ? 0.5 * (R - P) : 0, D = 'width' === c.get('icon-text-fit') || 'both' === c.get('icon-text-fit') ? R : P, E = 'height' === c.get('icon-text-fit') || 'both' === c.get('icon-text-fit') ? b : _;
                        u = new Point(m + A - Q, y + O - G), l = new Point(m + A + B + D, y + O - G), g = new Point(m + A + B + D, y + O + I + E), d = new Point(m + A - Q, y + O + I + E);
                    } else {
                        u = new Point(x, h), l = new Point(s, h), g = new Point(s, p), d = new Point(x, p);
                    }
                    var F = i.layout.get('icon-rotate').evaluate(r) * Math.PI / 180;
                    if (F) {
                        var H = Math.sin(F), L = Math.cos(F), Y = [
                                L,
                                -H,
                                H,
                                L
                            ];
                        u._matMult(Y), l._matMult(Y), d._matMult(Y), g._matMult(Y);
                    }
                    return [{
                            tl: u,
                            tr: l,
                            bl: d,
                            br: g,
                            tex: {
                                x: f.textureRect.x - 1,
                                y: f.textureRect.y - 1,
                                w: f.textureRect.w + 2,
                                h: f.textureRect.h + 2
                            },
                            writingMode: void 0,
                            glyphOffset: [
                                0,
                                0
                            ]
                        }];
                }
                function getGlyphQuads(t, e, i, o, n, a, r) {
                    for (var u = i.layout.get('text-rotate').evaluate(a) * Math.PI / 180, l = i.layout.get('text-offset').evaluate(a).map(function (t) {
                                return 24 * t;
                            }), g = e.positionedGlyphs, d = [], f = 0; f < g.length; f++) {
                        var c = g[f], h = r[c.glyph];
                        if (h) {
                            var x = h.rect;
                            if (x) {
                                var p = GLYPH_PBF_BORDER + 1, s = h.metrics.advance / 2, P = o ? [
                                        c.x + s,
                                        c.y
                                    ] : [
                                        0,
                                        0
                                    ], _ = o ? [
                                        0,
                                        0
                                    ] : [
                                        c.x + s + l[0],
                                        c.y + l[1]
                                    ], w = h.metrics.left - p - s + _[0], m = -h.metrics.top - p + _[1], v = w + x.w, y = m + x.h, M = new Point(w, m), R = new Point(v, m), b = new Point(w, y), G = new Point(v, y);
                                if (o && c.vertical) {
                                    var B = new Point(-s, s), I = -Math.PI / 2, Q = new Point(5, 0);
                                    M._rotateAround(I, B)._add(Q), R._rotateAround(I, B)._add(Q), b._rotateAround(I, B)._add(Q), G._rotateAround(I, B)._add(Q);
                                }
                                if (u) {
                                    var O = Math.sin(u), A = Math.cos(u), D = [
                                            A,
                                            -O,
                                            O,
                                            A
                                        ];
                                    M._matMult(D), R._matMult(D), b._matMult(D), G._matMult(D);
                                }
                                d.push({
                                    tl: M,
                                    tr: R,
                                    bl: b,
                                    br: G,
                                    tex: x,
                                    writingMode: e.writingMode,
                                    glyphOffset: P
                                });
                            }
                        }
                    }
                    return d;
                }
                var Point = _dereq_('@mapbox/point-geometry'), ref = _dereq_('../style/parse_glyph_pbf'), GLYPH_PBF_BORDER = ref.GLYPH_PBF_BORDER;
                module.exports = {
                    getIconQuads: getIconQuads,
                    getGlyphQuads: getGlyphQuads
                };
            },
            {
                '../style/parse_glyph_pbf': 186,
                '@mapbox/point-geometry': 4
            }
        ],
        226: [
            function (_dereq_, module, exports) {
                'use strict';
                function breakLines(e, t) {
                    for (var a = [], r = 0, i = 0, n = t; i < n.length; i += 1) {
                        var l = n[i];
                        a.push(e.substring(r, l)), r = l;
                    }
                    return r < e.length && a.push(e.substring(r, e.length)), a;
                }
                function shapeText(e, t, a, r, i, n, l, o, c, s) {
                    var h = e.trim();
                    s === WritingMode.vertical && (h = verticalizePunctuation(h));
                    var g, u = [], p = {
                            positionedGlyphs: u,
                            text: h,
                            top: o[1],
                            bottom: o[1],
                            left: o[0],
                            right: o[0],
                            writingMode: s
                        }, b = rtlTextPlugin.processBidirectionalText;
                    return g = b ? b(h, determineLineBreaks(h, l, a, t)) : breakLines(h, determineLineBreaks(h, l, a, t)), shapeLines(p, t, g, r, i, n, s, l, c), !!u.length && p;
                }
                function determineAverageLineWidth(e, t, a, r) {
                    for (var i = 0, n = 0; n < e.length; n++) {
                        var l = r[e.charCodeAt(n)];
                        l && (i += l.metrics.advance + t);
                    }
                    return i / Math.max(1, Math.ceil(i / a));
                }
                function calculateBadness(e, t, a, r) {
                    var i = Math.pow(e - t, 2);
                    return r ? e < t ? i / 2 : 2 * i : i + Math.abs(a) * a;
                }
                function calculatePenalty(e, t) {
                    var a = 0;
                    return 10 === e && (a -= 10000), 40 !== e && 65288 !== e || (a += 50), 41 !== t && 65289 !== t || (a += 50), a;
                }
                function evaluateBreak(e, t, a, r, i, n) {
                    for (var l = null, o = calculateBadness(t, a, i, n), c = 0, s = r; c < s.length; c += 1) {
                        var h = s[c], g = t - h.x, u = calculateBadness(g, a, i, n) + h.badness;
                        u <= o && (l = h, o = u);
                    }
                    return {
                        index: e,
                        x: t,
                        priorBreak: l,
                        badness: o
                    };
                }
                function leastBadBreaks(e) {
                    return e ? leastBadBreaks(e.priorBreak).concat(e.index) : [];
                }
                function determineLineBreaks(e, t, a, r) {
                    if (!a) {
                        return [];
                    }
                    if (!e) {
                        return [];
                    }
                    for (var i = [], n = determineAverageLineWidth(e, t, a, r), l = 0, o = 0; o < e.length; o++) {
                        var c = e.charCodeAt(o), s = r[c];
                        s && !whitespace[c] && (l += s.metrics.advance + t), o < e.length - 1 && (breakable[c] || scriptDetection.charAllowsIdeographicBreaking(c)) && i.push(evaluateBreak(o + 1, l, n, i, calculatePenalty(c, e.charCodeAt(o + 1)), !1));
                    }
                    return leastBadBreaks(evaluateBreak(e.length, l, n, i, 0, !0));
                }
                function getAnchorAlignment(e) {
                    var t = 0.5, a = 0.5;
                    switch (e) {
                    case 'right':
                    case 'top-right':
                    case 'bottom-right':
                        t = 1;
                        break;
                    case 'left':
                    case 'top-left':
                    case 'bottom-left':
                        t = 0;
                    }
                    switch (e) {
                    case 'bottom':
                    case 'bottom-right':
                    case 'bottom-left':
                        a = 1;
                        break;
                    case 'top':
                    case 'top-right':
                    case 'top-left':
                        a = 0;
                    }
                    return {
                        horizontalAlign: t,
                        verticalAlign: a
                    };
                }
                function shapeLines(e, t, a, r, i, n, l, o, c) {
                    for (var s = 0, h = -17, g = 0, u = e.positionedGlyphs, p = 'right' === n ? 1 : 'left' === n ? 0 : 0.5, b = 0, v = a; b < v.length; b += 1) {
                        var d = v[b];
                        if (d = d.trim(), d.length) {
                            for (var f = u.length, k = 0; k < d.length; k++) {
                                var m = d.charCodeAt(k), x = t[m];
                                x && (scriptDetection.charHasUprightVerticalOrientation(m) && l !== WritingMode.horizontal ? (u.push({
                                    glyph: m,
                                    x: s,
                                    y: 0,
                                    vertical: !0
                                }), s += c + o) : (u.push({
                                    glyph: m,
                                    x: s,
                                    y: h,
                                    vertical: !1
                                }), s += x.metrics.advance + o));
                            }
                            if (u.length !== f) {
                                var A = s - o;
                                g = Math.max(A, g), justifyLine(u, t, f, u.length - 1, p);
                            }
                            s = 0, h += r;
                        } else {
                            h += r;
                        }
                    }
                    var B = getAnchorAlignment(i), y = B.horizontalAlign, w = B.verticalAlign;
                    align(u, p, y, w, g, r, a.length);
                    var z = a.length * r;
                    e.top += -w * z, e.bottom = e.top + z, e.left += -y * g, e.right = e.left + g;
                }
                function justifyLine(e, t, a, r, i) {
                    if (i) {
                        var n = t[e[r].glyph];
                        if (n) {
                            for (var l = n.metrics.advance, o = (e[r].x + l) * i, c = a; c <= r; c++) {
                                e[c].x -= o;
                            }
                        }
                    }
                }
                function align(e, t, a, r, i, n, l) {
                    for (var o = (t - a) * i, c = (-r * l + 0.5) * n, s = 0; s < e.length; s++) {
                        e[s].x += o, e[s].y += c;
                    }
                }
                function shapeIcon(e, t, a) {
                    var r = getAnchorAlignment(a), i = r.horizontalAlign, n = r.verticalAlign, l = t[0], o = t[1], c = l - e.displaySize[0] * i, s = c + e.displaySize[0], h = o - e.displaySize[1] * n;
                    return {
                        image: e,
                        top: h,
                        bottom: h + e.displaySize[1],
                        left: c,
                        right: s
                    };
                }
                var scriptDetection = _dereq_('../util/script_detection'), verticalizePunctuation = _dereq_('../util/verticalize_punctuation'), rtlTextPlugin = _dereq_('../source/rtl_text_plugin'), WritingMode = {
                        horizontal: 1,
                        vertical: 2,
                        horizontalOnly: 3
                    };
                module.exports = {
                    shapeText: shapeText,
                    shapeIcon: shapeIcon,
                    WritingMode: WritingMode
                };
                var whitespace = {};
                whitespace[9] = !0, whitespace[10] = !0, whitespace[11] = !0, whitespace[12] = !0, whitespace[13] = !0, whitespace[32] = !0;
                var breakable = {};
                breakable[10] = !0, breakable[32] = !0, breakable[38] = !0, breakable[40] = !0, breakable[41] = !0, breakable[43] = !0, breakable[45] = !0, breakable[47] = !0, breakable[173] = !0, breakable[183] = !0, breakable[8203] = !0, breakable[8208] = !0, breakable[8211] = !0, breakable[8231] = !0;
            },
            {
                '../source/rtl_text_plugin': 109,
                '../util/script_detection': 269,
                '../util/verticalize_punctuation': 277
            }
        ],
        227: [
            function (_dereq_, module, exports) {
                'use strict';
                function performSymbolLayout(e, t, a, i, o, n) {
                    e.createArrays(), e.symbolInstances = [];
                    var r = 512 * e.overscaling;
                    e.tilePixelRatio = EXTENT / r, e.compareText = {}, e.iconsNeedLinear = !1;
                    var l = e.layers[0].layout, s = e.layers[0]._unevaluatedLayout._values, c = {};
                    if ('composite' === e.textSizeData.functionType) {
                        var u = e.textSizeData.zoomRange, x = u.min, g = u.max;
                        c.compositeTextSizes = [
                            s['text-size'].possiblyEvaluate(new EvaluationParameters(x)),
                            s['text-size'].possiblyEvaluate(new EvaluationParameters(g))
                        ];
                    }
                    if ('composite' === e.iconSizeData.functionType) {
                        var y = e.iconSizeData.zoomRange, p = y.min, d = y.max;
                        c.compositeIconSizes = [
                            s['icon-size'].possiblyEvaluate(new EvaluationParameters(p)),
                            s['icon-size'].possiblyEvaluate(new EvaluationParameters(d))
                        ];
                    }
                    c.layoutTextSize = s['text-size'].possiblyEvaluate(new EvaluationParameters(e.zoom + 1)), c.layoutIconSize = s['icon-size'].possiblyEvaluate(new EvaluationParameters(e.zoom + 1)), c.textMaxSize = s['text-size'].possiblyEvaluate(new EvaluationParameters(18));
                    for (var m = 24 * l.get('text-line-height'), v = 'map' === l.get('text-rotation-alignment') && 'line' === l.get('symbol-placement'), f = l.get('text-keep-upright'), h = 0, S = e.features; h < S.length; h += 1) {
                        var z = S[h], b = l.get('text-font').evaluate(z).join(','), T = t[b] || {}, I = a[b] || {}, E = {}, P = z.text;
                        if (P) {
                            var w = scriptDetection.allowsVerticalWritingMode(P), q = l.get('text-offset').evaluate(z).map(function (e) {
                                    return 24 * e;
                                }), A = 24 * l.get('text-letter-spacing').evaluate(z), L = scriptDetection.allowsLetterSpacing(P) ? A : 0, D = l.get('text-anchor').evaluate(z), O = l.get('text-justify').evaluate(z), _ = 'line' !== l.get('symbol-placement') ? 24 * l.get('text-max-width').evaluate(z) : 0;
                            E.horizontal = shapeText(P, T, _, m, D, O, L, q, 24, WritingMode.horizontal), w && v && f && (E.vertical = shapeText(P, T, _, m, D, O, L, q, 24, WritingMode.vertical));
                        }
                        var R = void 0;
                        if (z.icon) {
                            var B = i[z.icon];
                            B && (R = shapeIcon(o[z.icon], l.get('icon-offset').evaluate(z), l.get('icon-anchor').evaluate(z)), void 0 === e.sdfIcons ? e.sdfIcons = B.sdf : e.sdfIcons !== B.sdf && util.warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer'), B.pixelRatio !== e.pixelRatio ? e.iconsNeedLinear = !0 : 0 !== l.get('icon-rotate').constantOr(1) && (e.iconsNeedLinear = !0));
                        }
                        (E.horizontal || R) && addFeature(e, z, E, R, I, c);
                    }
                    n && e.generateCollisionDebugBuffers();
                }
                function addFeature(e, t, a, i, o, n) {
                    var r = n.layoutTextSize.evaluate(t), l = n.layoutIconSize.evaluate(t), s = n.textMaxSize.evaluate(t);
                    void 0 === s && (s = r);
                    var c = e.layers[0].layout, u = c.get('text-offset').evaluate(t), x = c.get('icon-offset').evaluate(t), g = r / 24, y = e.tilePixelRatio * g, p = e.tilePixelRatio * s / 24, d = e.tilePixelRatio * l, m = e.tilePixelRatio * c.get('symbol-spacing'), v = c.get('text-padding') * e.tilePixelRatio, f = c.get('icon-padding') * e.tilePixelRatio, h = c.get('text-max-angle') / 180 * Math.PI, S = 'map' === c.get('text-rotation-alignment') && 'line' === c.get('symbol-placement'), z = 'map' === c.get('icon-rotation-alignment') && 'line' === c.get('symbol-placement'), b = c.get('symbol-placement'), T = m / 2, I = function (r, l) {
                            l.x < 0 || l.x >= EXTENT || l.y < 0 || l.y >= EXTENT || e.symbolInstances.push(addSymbol(e, l, r, a, i, e.layers[0], e.collisionBoxArray, t.index, t.sourceLayerIndex, e.index, y, v, S, u, d, f, z, x, { zoom: e.zoom }, t, o, n));
                        };
                    if ('line' === b) {
                        for (var E = 0, P = clipLine(t.geometry, 0, 0, EXTENT, EXTENT); E < P.length; E += 1) {
                            for (var w = P[E], q = getAnchors(w, m, h, a.vertical || a.horizontal, i, 24, p, e.overscaling, EXTENT), A = 0, L = q; A < L.length; A += 1) {
                                var D = L[A], O = a.horizontal;
                                O && anchorIsTooClose(e, O.text, T, D) || I(w, D);
                            }
                        }
                    } else if ('Polygon' === t.type) {
                        for (var _ = 0, R = classifyRings(t.geometry, 0); _ < R.length; _ += 1) {
                            var B = R[_], M = findPoleOfInaccessibility(B, 16);
                            I(B[0], new Anchor(M.x, M.y, 0));
                        }
                    } else if ('LineString' === t.type) {
                        for (var N = 0, V = t.geometry; N < V.length; N += 1) {
                            var W = V[N];
                            I(W, new Anchor(W[0].x, W[0].y, 0));
                        }
                    } else if ('Point' === t.type) {
                        for (var X = 0, C = t.geometry; X < C.length; X += 1) {
                            for (var F = C[X], k = 0, G = F; k < G.length; k += 1) {
                                var Q = G[k];
                                I([Q], new Anchor(Q.x, Q.y, 0));
                            }
                        }
                    }
                }
                function addTextVertices(e, t, a, i, o, n, r, l, s, c, u, x, g) {
                    var y = getGlyphQuads(t, a, i, o, n, r, x), p = e.textSizeData, d = null;
                    return 'source' === p.functionType ? d = [10 * i.layout.get('text-size').evaluate(r)] : 'composite' === p.functionType && (d = [
                        10 * g.compositeTextSizes[0].evaluate(r),
                        10 * g.compositeTextSizes[1].evaluate(r)
                    ]), e.addSymbols(e.text, y, d, l, o, r, c, t, s.lineStartIndex, s.lineLength), u.push(e.text.placedSymbolArray.length - 1), 4 * y.length;
                }
                function addSymbol(e, t, a, i, o, n, r, l, s, c, u, x, g, y, p, d, m, v, f, h, S, z) {
                    var b, T, I = e.addToLineVertexArray(t, a), E = 0, P = 0, w = 0, q = i.horizontal ? i.horizontal.text : '', A = [];
                    i.horizontal && (b = new CollisionFeature(r, a, t, l, s, c, i.horizontal, u, x, g, e.overscaling), P += addTextVertices(e, t, i.horizontal, n, g, f, h, y, I, i.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly, A, S, z), i.vertical && (w += addTextVertices(e, t, i.vertical, n, g, f, h, y, I, WritingMode.vertical, A, S, z)));
                    var L = b ? b.boxStartIndex : e.collisionBoxArray.length, D = b ? b.boxEndIndex : e.collisionBoxArray.length;
                    if (o) {
                        var O = getIconQuads(t, o, n, m, i.horizontal, f, h);
                        T = new CollisionFeature(r, a, t, l, s, c, o, p, d, !1, e.overscaling), E = 4 * O.length;
                        var _ = e.iconSizeData, R = null;
                        'source' === _.functionType ? R = [10 * n.layout.get('icon-size').evaluate(h)] : 'composite' === _.functionType && (R = [
                            10 * z.compositeIconSizes[0].evaluate(h),
                            10 * z.compositeIconSizes[1].evaluate(h)
                        ]), e.addSymbols(e.icon, O, R, v, m, h, !1, t, I.lineStartIndex, I.lineLength);
                    }
                    var B = T ? T.boxStartIndex : e.collisionBoxArray.length, M = T ? T.boxEndIndex : e.collisionBoxArray.length;
                    return e.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS && util.warnOnce('Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907'), {
                        key: q,
                        textBoxStartIndex: L,
                        textBoxEndIndex: D,
                        iconBoxStartIndex: B,
                        iconBoxEndIndex: M,
                        textOffset: y,
                        iconOffset: v,
                        anchor: t,
                        line: a,
                        featureIndex: l,
                        feature: h,
                        numGlyphVertices: P,
                        numVerticalGlyphVertices: w,
                        numIconVertices: E,
                        textOpacityState: new OpacityState(),
                        iconOpacityState: new OpacityState(),
                        isDuplicate: !1,
                        placedTextSymbolIndices: A,
                        crossTileID: 0
                    };
                }
                function anchorIsTooClose(e, t, a, i) {
                    var o = e.compareText;
                    if (t in o) {
                        for (var n = o[t], r = n.length - 1; r >= 0; r--) {
                            if (i.dist(n[r]) < a) {
                                return !0;
                            }
                        }
                    } else {
                        o[t] = [];
                    }
                    return o[t].push(i), !1;
                }
                var Anchor = _dereq_('./anchor'), getAnchors = _dereq_('./get_anchors'), clipLine = _dereq_('./clip_line'), OpacityState = _dereq_('./opacity_state'), ref = _dereq_('./shaping'), shapeText = ref.shapeText, shapeIcon = ref.shapeIcon, WritingMode = ref.WritingMode, ref$1 = _dereq_('./quads'), getGlyphQuads = ref$1.getGlyphQuads, getIconQuads = ref$1.getIconQuads, CollisionFeature = _dereq_('./collision_feature'), util = _dereq_('../util/util'), scriptDetection = _dereq_('../util/script_detection'), findPoleOfInaccessibility = _dereq_('../util/find_pole_of_inaccessibility'), classifyRings = _dereq_('../util/classify_rings'), EXTENT = _dereq_('../data/extent'), SymbolBucket = _dereq_('../data/bucket/symbol_bucket'), EvaluationParameters = _dereq_('../style/evaluation_parameters'), Point = _dereq_('@mapbox/point-geometry');
                module.exports = { performSymbolLayout: performSymbolLayout };
            },
            {
                '../data/bucket/symbol_bucket': 51,
                '../data/extent': 53,
                '../style/evaluation_parameters': 182,
                '../util/classify_rings': 255,
                '../util/find_pole_of_inaccessibility': 261,
                '../util/script_detection': 269,
                '../util/util': 275,
                './anchor': 213,
                './clip_line': 215,
                './collision_feature': 216,
                './get_anchors': 219,
                './opacity_state': 222,
                './quads': 225,
                './shaping': 226,
                '@mapbox/point-geometry': 4
            }
        ],
        228: [
            function (_dereq_, module, exports) {
                'use strict';
                function getSizeData(e, o) {
                    var i = o.expression;
                    if ('constant' === i.kind) {
                        return {
                            functionType: 'constant',
                            layoutSize: i.evaluate({ zoom: e + 1 })
                        };
                    }
                    if ('source' === i.kind) {
                        return { functionType: 'source' };
                    }
                    for (var t = i.zoomStops, r = 0; r < t.length && t[r] <= e;) {
                        r++;
                    }
                    r = Math.max(0, r - 1);
                    for (var a = r; a < t.length && t[a] < e + 1;) {
                        a++;
                    }
                    a = Math.min(t.length - 1, a);
                    var n = {
                        min: t[r],
                        max: t[a]
                    };
                    return 'composite' === i.kind ? {
                        functionType: 'composite',
                        zoomRange: n,
                        propertyValue: o.value
                    } : {
                        functionType: 'camera',
                        layoutSize: i.evaluate({ zoom: e + 1 }),
                        zoomRange: n,
                        sizeRange: {
                            min: i.evaluate({ zoom: n.min }),
                            max: i.evaluate({ zoom: n.max })
                        },
                        propertyValue: o.value
                    };
                }
                function evaluateSizeForFeature(e, o, i) {
                    var t = o;
                    return 'source' === e.functionType ? i.lowerSize / 10 : 'composite' === e.functionType ? interpolate.number(i.lowerSize / 10, i.upperSize / 10, t.uSizeT) : t.uSize;
                }
                function evaluateSizeForZoom(e, o, i) {
                    if ('constant' === e.functionType) {
                        return {
                            uSizeT: 0,
                            uSize: e.layoutSize
                        };
                    }
                    if ('source' === e.functionType) {
                        return {
                            uSizeT: 0,
                            uSize: 0
                        };
                    }
                    if ('camera' === e.functionType) {
                        var t = e.propertyValue, r = e.zoomRange, a = e.sizeRange, n = normalizePropertyExpression(t, i.specification), u = util.clamp(n.interpolationFactor(o, r.min, r.max), 0, 1);
                        return {
                            uSizeT: 0,
                            uSize: a.min + u * (a.max - a.min)
                        };
                    }
                    var p = e.propertyValue, l = e.zoomRange, m = normalizePropertyExpression(p, i.specification);
                    return {
                        uSizeT: util.clamp(m.interpolationFactor(o, l.min, l.max), 0, 1),
                        uSize: 0
                    };
                }
                var ref = _dereq_('../style-spec/expression'), normalizePropertyExpression = ref.normalizePropertyExpression, interpolate = _dereq_('../style-spec/util/interpolate'), util = _dereq_('../util/util');
                module.exports = {
                    getSizeData: getSizeData,
                    evaluateSizeForFeature: evaluateSizeForFeature,
                    evaluateSizeForZoom: evaluateSizeForZoom
                };
            },
            {
                '../style-spec/expression': 139,
                '../style-spec/util/interpolate': 158,
                '../util/util': 275
            }
        ],
        229: [
            function (_dereq_, module, exports) {
                'use strict';
                var rtlTextPlugin = _dereq_('../source/rtl_text_plugin');
                module.exports = function (e, t, r) {
                    var a = t.layout.get('text-transform').evaluate(r);
                    return 'uppercase' === a ? e = e.toLocaleUpperCase() : 'lowercase' === a && (e = e.toLocaleLowerCase()), rtlTextPlugin.applyArabicShaping && (e = rtlTextPlugin.applyArabicShaping(e)), e;
                };
            },
            { '../source/rtl_text_plugin': 109 }
        ],
        230: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../util/dom'), Point = _dereq_('@mapbox/point-geometry'), handlers = {
                        scrollZoom: _dereq_('./handler/scroll_zoom'),
                        boxZoom: _dereq_('./handler/box_zoom'),
                        dragRotate: _dereq_('./handler/drag_rotate'),
                        dragPan: _dereq_('./handler/drag_pan'),
                        keyboard: _dereq_('./handler/keyboard'),
                        doubleClickZoom: _dereq_('./handler/dblclick_zoom'),
                        touchZoomRotate: _dereq_('./handler/touch_zoom_rotate')
                    };
                module.exports = function (e, t) {
                    function n(e) {
                        h('mouseout', e);
                    }
                    function o(t) {
                        e.doubleClickZoom.isActive() || e.stop(), b = DOM.mousePos(p, t), h('mousedown', t), L = !0;
                    }
                    function r(t) {
                        var n = e.dragRotate && e.dragRotate.isActive();
                        E && !n && h('contextmenu', E), E = null, L = !1, h('mouseup', t);
                    }
                    function a(t) {
                        if (!(e.dragPan && e.dragPan.isActive() || e.dragRotate && e.dragRotate.isActive())) {
                            for (var n = t.toElement || t.target; n && n !== p;) {
                                n = n.parentNode;
                            }
                            n === p && h('mousemove', t);
                        }
                    }
                    function u(e) {
                        for (var t = e.toElement || e.target; t && t !== p;) {
                            t = t.parentNode;
                        }
                        t === p && h('mouseover', e);
                    }
                    function i(t) {
                        e.stop(), g('touchstart', t), !t.touches || t.touches.length > 1 || (k ? (clearTimeout(k), k = null, h('dblclick', t)) : k = setTimeout(s, 300));
                    }
                    function c(e) {
                        g('touchmove', e);
                    }
                    function d(e) {
                        g('touchend', e);
                    }
                    function l(e) {
                        g('touchcancel', e);
                    }
                    function s() {
                        k = null;
                    }
                    function v(e) {
                        DOM.mousePos(p, e).equals(b) && h('click', e);
                    }
                    function m(e) {
                        h('dblclick', e), e.preventDefault();
                    }
                    function f(t) {
                        var n = e.dragRotate && e.dragRotate.isActive();
                        L || n ? L && (E = t) : h('contextmenu', t), t.preventDefault();
                    }
                    function h(t, n) {
                        var o = DOM.mousePos(p, n);
                        return e.fire(t, {
                            lngLat: e.unproject(o),
                            point: o,
                            originalEvent: n
                        });
                    }
                    function g(t, n) {
                        var o = DOM.touchPos(p, n), r = o.reduce(function (e, t, n, o) {
                                return e.add(t.div(o.length));
                            }, new Point(0, 0));
                        return e.fire(t, {
                            lngLat: e.unproject(r),
                            point: r,
                            lngLats: o.map(function (t) {
                                return e.unproject(t);
                            }, this),
                            points: o,
                            originalEvent: n
                        });
                    }
                    var p = e.getCanvasContainer(), E = null, L = !1, b = null, k = null;
                    for (var q in handlers) {
                        e[q] = new handlers[q](e, t), t.interactive && t[q] && e[q].enable(t[q]);
                    }
                    p.addEventListener('mouseout', n, !1), p.addEventListener('mousedown', o, !1), p.addEventListener('mouseup', r, !1), p.addEventListener('mousemove', a, !1), p.addEventListener('mouseover', u, !1), p.addEventListener('touchstart', i, !1), p.addEventListener('touchend', d, !1), p.addEventListener('touchmove', c, !1), p.addEventListener('touchcancel', l, !1), p.addEventListener('click', v, !1), p.addEventListener('dblclick', m, !1), p.addEventListener('contextmenu', f, !1);
                };
            },
            {
                '../util/dom': 259,
                './handler/box_zoom': 239,
                './handler/dblclick_zoom': 240,
                './handler/drag_pan': 241,
                './handler/drag_rotate': 242,
                './handler/keyboard': 243,
                './handler/scroll_zoom': 244,
                './handler/touch_zoom_rotate': 245,
                '@mapbox/point-geometry': 4
            }
        ],
        231: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), interpolate = _dereq_('../style-spec/util/interpolate').number, browser = _dereq_('../util/browser'), LngLat = _dereq_('../geo/lng_lat'), LngLatBounds = _dereq_('../geo/lng_lat_bounds'), Point = _dereq_('@mapbox/point-geometry'), Evented = _dereq_('../util/evented'), Camera = function (t) {
                        function i(i, e) {
                            t.call(this), this.moving = !1, this.transform = i, this._bearingSnap = e.bearingSnap;
                        }
                        return t && (i.__proto__ = t), i.prototype = Object.create(t && t.prototype), i.prototype.constructor = i, i.prototype.getCenter = function () {
                            return this.transform.center;
                        }, i.prototype.setCenter = function (t, i) {
                            return this.jumpTo({ center: t }, i);
                        }, i.prototype.panBy = function (t, i, e) {
                            return t = Point.convert(t).mult(-1), this.panTo(this.transform.center, util.extend({ offset: t }, i), e);
                        }, i.prototype.panTo = function (t, i, e) {
                            return this.easeTo(util.extend({ center: t }, i), e);
                        }, i.prototype.getZoom = function () {
                            return this.transform.zoom;
                        }, i.prototype.setZoom = function (t, i) {
                            return this.jumpTo({ zoom: t }, i), this;
                        }, i.prototype.zoomTo = function (t, i, e) {
                            return this.easeTo(util.extend({ zoom: t }, i), e);
                        }, i.prototype.zoomIn = function (t, i) {
                            return this.zoomTo(this.getZoom() + 1, t, i), this;
                        }, i.prototype.zoomOut = function (t, i) {
                            return this.zoomTo(this.getZoom() - 1, t, i), this;
                        }, i.prototype.getBearing = function () {
                            return this.transform.bearing;
                        }, i.prototype.setBearing = function (t, i) {
                            return this.jumpTo({ bearing: t }, i), this;
                        }, i.prototype.rotateTo = function (t, i, e) {
                            return this.easeTo(util.extend({ bearing: t }, i), e);
                        }, i.prototype.resetNorth = function (t, i) {
                            return this.rotateTo(0, util.extend({ duration: 1000 }, t), i), this;
                        }, i.prototype.snapToNorth = function (t, i) {
                            return Math.abs(this.getBearing()) < this._bearingSnap ? this.resetNorth(t, i) : this;
                        }, i.prototype.getPitch = function () {
                            return this.transform.pitch;
                        }, i.prototype.setPitch = function (t, i) {
                            return this.jumpTo({ pitch: t }, i), this;
                        }, i.prototype.fitBounds = function (t, i, e) {
                            if (i = util.extend({
                                    padding: {
                                        top: 0,
                                        bottom: 0,
                                        right: 0,
                                        left: 0
                                    },
                                    offset: [
                                        0,
                                        0
                                    ],
                                    maxZoom: this.transform.maxZoom
                                }, i), 'number' == typeof i.padding) {
                                var o = i.padding;
                                i.padding = {
                                    top: o,
                                    bottom: o,
                                    right: o,
                                    left: o
                                };
                            }
                            if (!util.deepEqual(Object.keys(i.padding).sort(function (t, i) {
                                    return t < i ? -1 : t > i ? 1 : 0;
                                }), [
                                    'bottom',
                                    'left',
                                    'right',
                                    'top'
                                ])) {
                                return util.warnOnce('options.padding must be a positive number, or an Object with keys \'bottom\', \'left\', \'right\', \'top\''), this;
                            }
                            t = LngLatBounds.convert(t);
                            var n = [
                                    (i.padding.left - i.padding.right) / 2,
                                    (i.padding.top - i.padding.bottom) / 2
                                ], r = Math.min(i.padding.right, i.padding.left), a = Math.min(i.padding.top, i.padding.bottom);
                            i.offset = [
                                i.offset[0] + n[0],
                                i.offset[1] + n[1]
                            ];
                            var s = Point.convert(i.offset), h = this.transform, p = h.project(t.getNorthWest()), u = h.project(t.getSouthEast()), c = u.sub(p), m = (h.width - 2 * r - 2 * Math.abs(s.x)) / c.x, f = (h.height - 2 * a - 2 * Math.abs(s.y)) / c.y;
                            return f < 0 || m < 0 ? (util.warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.'), this) : (i.center = h.unproject(p.add(u).div(2)), i.zoom = Math.min(h.scaleZoom(h.scale * Math.min(m, f)), i.maxZoom), i.bearing = 0, i.linear ? this.easeTo(i, e) : this.flyTo(i, e));
                        }, i.prototype.jumpTo = function (t, i) {
                            this.stop();
                            var e = this.transform, o = !1, n = !1, r = !1;
                            return 'zoom' in t && e.zoom !== +t.zoom && (o = !0, e.zoom = +t.zoom), void 0 !== t.center && (e.center = LngLat.convert(t.center)), 'bearing' in t && e.bearing !== +t.bearing && (n = !0, e.bearing = +t.bearing), 'pitch' in t && e.pitch !== +t.pitch && (r = !0, e.pitch = +t.pitch), this.fire('movestart', i).fire('move', i), o && this.fire('zoomstart', i).fire('zoom', i).fire('zoomend', i), n && this.fire('rotate', i), r && this.fire('pitchstart', i).fire('pitch', i).fire('pitchend', i), this.fire('moveend', i);
                        }, i.prototype.easeTo = function (t, i) {
                            var e = this;
                            this.stop(), t = util.extend({
                                offset: [
                                    0,
                                    0
                                ],
                                duration: 500,
                                easing: util.ease
                            }, t), !1 === t.animate && (t.duration = 0);
                            var o = this.transform, n = this.getZoom(), r = this.getBearing(), a = this.getPitch(), s = 'zoom' in t ? +t.zoom : n, h = 'bearing' in t ? this._normalizeBearing(t.bearing, r) : r, p = 'pitch' in t ? +t.pitch : a, u = o.centerPoint.add(Point.convert(t.offset)), c = o.pointLocation(u), m = LngLat.convert(t.center || c);
                            this._normalizeCenter(m);
                            var f, g, d = o.project(c), l = o.project(m).sub(d), v = o.zoomScale(s - n);
                            return t.around && (f = LngLat.convert(t.around), g = o.locationPoint(f)), this.zooming = s !== n, this.rotating = r !== h, this.pitching = p !== a, this._prepareEase(i, t.noMoveStart), clearTimeout(this._onEaseEnd), this._ease(function (t) {
                                if (e.zooming && (o.zoom = interpolate(n, s, t)), e.rotating && (o.bearing = interpolate(r, h, t)), e.pitching && (o.pitch = interpolate(a, p, t)), f) {
                                    o.setLocationAtPoint(f, g);
                                } else {
                                    var c = o.zoomScale(o.zoom - n), m = s > n ? Math.min(2, v) : Math.max(0.5, v), _ = Math.pow(m, 1 - t), b = o.unproject(d.add(l.mult(t * _)).mult(c));
                                    o.setLocationAtPoint(o.renderWorldCopies ? b.wrap() : b, u);
                                }
                                e._fireMoveEvents(i);
                            }, function () {
                                t.delayEndEvents ? e._onEaseEnd = setTimeout(function () {
                                    return e._afterEase(i);
                                }, t.delayEndEvents) : e._afterEase(i);
                            }, t), this;
                        }, i.prototype._prepareEase = function (t, i) {
                            this.moving = !0, i || this.fire('movestart', t), this.zooming && this.fire('zoomstart', t), this.pitching && this.fire('pitchstart', t);
                        }, i.prototype._fireMoveEvents = function (t) {
                            this.fire('move', t), this.zooming && this.fire('zoom', t), this.rotating && this.fire('rotate', t), this.pitching && this.fire('pitch', t);
                        }, i.prototype._afterEase = function (t) {
                            var i = this.zooming, e = this.pitching;
                            this.moving = !1, this.zooming = !1, this.rotating = !1, this.pitching = !1, i && this.fire('zoomend', t), e && this.fire('pitchend', t), this.fire('moveend', t);
                        }, i.prototype.flyTo = function (t, i) {
                            function e(t) {
                                var i = (M * M - z * z + (t ? -1 : 1) * L * L * x * x) / (2 * (t ? M : z) * L * x);
                                return Math.log(Math.sqrt(i * i + 1) - i);
                            }
                            function o(t) {
                                return (Math.exp(t) - Math.exp(-t)) / 2;
                            }
                            function n(t) {
                                return (Math.exp(t) + Math.exp(-t)) / 2;
                            }
                            function r(t) {
                                return o(t) / n(t);
                            }
                            var a = this;
                            this.stop(), t = util.extend({
                                offset: [
                                    0,
                                    0
                                ],
                                speed: 1.2,
                                curve: 1.42,
                                easing: util.ease
                            }, t);
                            var s = this.transform, h = this.getZoom(), p = this.getBearing(), u = this.getPitch(), c = 'zoom' in t ? util.clamp(+t.zoom, s.minZoom, s.maxZoom) : h, m = 'bearing' in t ? this._normalizeBearing(t.bearing, p) : p, f = 'pitch' in t ? +t.pitch : u, g = s.zoomScale(c - h), d = s.centerPoint.add(Point.convert(t.offset)), l = s.pointLocation(d), v = LngLat.convert(t.center || l);
                            this._normalizeCenter(v);
                            var _ = s.project(l), b = s.project(v).sub(_), y = t.curve, z = Math.max(s.width, s.height), M = z / g, x = b.mag();
                            if ('minZoom' in t) {
                                var E = util.clamp(Math.min(t.minZoom, h, c), s.minZoom, s.maxZoom), T = z / s.zoomScale(E - h);
                                y = Math.sqrt(T / x * 2);
                            }
                            var L = y * y, j = e(0), w = function (t) {
                                    return n(j) / n(j + y * t);
                                }, Z = function (t) {
                                    return z * ((n(j) * r(j + y * t) - o(j)) / L) / x;
                                }, P = (e(1) - j) / y;
                            if (Math.abs(x) < 0.000001 || !isFinite(P)) {
                                if (Math.abs(z - M) < 0.000001) {
                                    return this.easeTo(t, i);
                                }
                                var S = M < z ? -1 : 1;
                                P = Math.abs(Math.log(M / z)) / y, Z = function () {
                                    return 0;
                                }, w = function (t) {
                                    return Math.exp(S * y * t);
                                };
                            }
                            if ('duration' in t) {
                                t.duration = +t.duration;
                            } else {
                                var B = 'screenSpeed' in t ? +t.screenSpeed / y : +t.speed;
                                t.duration = 1000 * P / B;
                            }
                            return t.maxDuration && t.duration > t.maxDuration && (t.duration = 0), this.zooming = !0, this.rotating = p !== m, this.pitching = f !== u, this._prepareEase(i, !1), this._ease(function (t) {
                                var e = t * P, o = 1 / w(e);
                                s.zoom = h + s.scaleZoom(o), a.rotating && (s.bearing = interpolate(p, m, t)), a.pitching && (s.pitch = interpolate(u, f, t));
                                var n = s.unproject(_.add(b.mult(Z(e))).mult(o));
                                s.setLocationAtPoint(s.renderWorldCopies ? n.wrap() : n, d), a._fireMoveEvents(i);
                            }, function () {
                                return a._afterEase(i);
                            }, t), this;
                        }, i.prototype.isEasing = function () {
                            return !!this._isEasing;
                        }, i.prototype.isMoving = function () {
                            return this.moving;
                        }, i.prototype.stop = function () {
                            return this._onFrame && this._finishAnimation(), this;
                        }, i.prototype._ease = function (t, i, e) {
                            var o = this;
                            !1 === e.animate || 0 === e.duration ? (t(1), i()) : (this._easeStart = browser.now(), this._isEasing = !0, this._easeOptions = e, this._startAnimation(function (i) {
                                var e = Math.min((browser.now() - o._easeStart) / o._easeOptions.duration, 1);
                                t(o._easeOptions.easing(e)), 1 === e && o.stop();
                            }, function () {
                                o._isEasing = !1, i();
                            }));
                        }, i.prototype._updateCamera = function () {
                            this._onFrame && this._onFrame(this.transform);
                        }, i.prototype._startAnimation = function (t, i) {
                            return void 0 === i && (i = function () {
                            }), this.stop(), this._onFrame = t, this._finishFn = i, this._update(), this;
                        }, i.prototype._finishAnimation = function () {
                            delete this._onFrame;
                            var t = this._finishFn;
                            delete this._finishFn, t.call(this);
                        }, i.prototype._normalizeBearing = function (t, i) {
                            t = util.wrap(t, -180, 180);
                            var e = Math.abs(t - i);
                            return Math.abs(t - 360 - i) < e && (t -= 360), Math.abs(t + 360 - i) < e && (t += 360), t;
                        }, i.prototype._normalizeCenter = function (t) {
                            var i = this.transform;
                            if (i.renderWorldCopies && !i.lngRange) {
                                var e = t.lng - i.center.lng;
                                t.lng += e > 180 ? -360 : e < -180 ? 360 : 0;
                            }
                        }, i;
                    }(Evented);
                module.exports = Camera;
            },
            {
                '../geo/lng_lat': 62,
                '../geo/lng_lat_bounds': 63,
                '../style-spec/util/interpolate': 158,
                '../util/browser': 252,
                '../util/evented': 260,
                '../util/util': 275,
                '@mapbox/point-geometry': 4
            }
        ],
        232: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), config = _dereq_('../../util/config'), AttributionControl = function (t) {
                        this.options = t, util.bindAll([
                            '_updateEditLink',
                            '_updateData',
                            '_updateCompact'
                        ], this);
                    };
                AttributionControl.prototype.getDefaultPosition = function () {
                    return 'bottom-right';
                }, AttributionControl.prototype.onAdd = function (t) {
                    var i = this.options && this.options.compact;
                    return this._map = t, this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib'), i && this._container.classList.add('mapboxgl-compact'), this._updateAttributions(), this._updateEditLink(), this._map.on('sourcedata', this._updateData), this._map.on('moveend', this._updateEditLink), void 0 === i && (this._map.on('resize', this._updateCompact), this._updateCompact()), this._container;
                }, AttributionControl.prototype.onRemove = function () {
                    DOM.remove(this._container), this._map.off('sourcedata', this._updateData), this._map.off('moveend', this._updateEditLink), this._map.off('resize', this._updateCompact), this._map = void 0;
                }, AttributionControl.prototype._updateEditLink = function () {
                    var t = this._editLink;
                    t || (t = this._editLink = this._container.querySelector('.mapbox-improve-map'));
                    var i = [
                        {
                            key: 'owner',
                            value: this.styleOwner
                        },
                        {
                            key: 'id',
                            value: this.styleId
                        },
                        {
                            key: 'access_token',
                            value: config.ACCESS_TOKEN
                        }
                    ];
                    if (t) {
                        var e = i.reduce(function (t, e, o) {
                            return e.value && (t += e.key + '=' + e.value + (o < i.length - 1 ? '&' : '')), t;
                        }, '?');
                        t.href = 'https://www.mapbox.com/feedback/' + e + (this._map._hash ? this._map._hash.getHashString(!0) : '');
                    }
                }, AttributionControl.prototype._updateData = function (t) {
                    t && 'metadata' === t.sourceDataType && (this._updateAttributions(), this._updateEditLink());
                }, AttributionControl.prototype._updateAttributions = function () {
                    if (this._map.style) {
                        var t = [];
                        if (this._map.style.stylesheet) {
                            var i = this._map.style.stylesheet;
                            this.styleOwner = i.owner, this.styleId = i.id;
                        }
                        var e = this._map.style.sourceCaches;
                        for (var o in e) {
                            var a = e[o].getSource();
                            a.attribution && t.indexOf(a.attribution) < 0 && t.push(a.attribution);
                        }
                        t.sort(function (t, i) {
                            return t.length - i.length;
                        }), t = t.filter(function (i, e) {
                            for (var o = e + 1; o < t.length; o++) {
                                if (t[o].indexOf(i) >= 0) {
                                    return !1;
                                }
                            }
                            return !0;
                        }), t.length ? (this._container.innerHTML = t.join(' | '), this._container.classList.remove('mapboxgl-attrib-empty')) : this._container.classList.add('mapboxgl-attrib-empty'), this._editLink = null;
                    }
                }, AttributionControl.prototype._updateCompact = function () {
                    this._map.getCanvasContainer().offsetWidth <= 640 ? this._container.classList.add('mapboxgl-compact') : this._container.classList.remove('mapboxgl-compact');
                }, module.exports = AttributionControl;
            },
            {
                '../../util/config': 256,
                '../../util/dom': 259,
                '../../util/util': 275
            }
        ],
        233: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), window = _dereq_('../../util/window'), FullscreenControl = function () {
                        this._fullscreen = !1, util.bindAll([
                            '_onClickFullscreen',
                            '_changeIcon'
                        ], this), 'onfullscreenchange' in window.document ? this._fullscreenchange = 'fullscreenchange' : 'onmozfullscreenchange' in window.document ? this._fullscreenchange = 'mozfullscreenchange' : 'onwebkitfullscreenchange' in window.document ? this._fullscreenchange = 'webkitfullscreenchange' : 'onmsfullscreenchange' in window.document && (this._fullscreenchange = 'MSFullscreenChange'), this._className = 'mapboxgl-ctrl';
                    };
                FullscreenControl.prototype.onAdd = function (e) {
                    return this._map = e, this._mapContainer = this._map.getContainer(), this._container = DOM.create('div', this._className + ' mapboxgl-ctrl-group'), this._checkFullscreenSupport() ? this._setupUI() : (this._container.style.display = 'none', util.warnOnce('This device does not support fullscreen mode.')), this._container;
                }, FullscreenControl.prototype.onRemove = function () {
                    DOM.remove(this._container), this._map = null, window.document.removeEventListener(this._fullscreenchange, this._changeIcon);
                }, FullscreenControl.prototype._checkFullscreenSupport = function () {
                    return !!(window.document.fullscreenEnabled || window.document.mozFullScreenEnabled || window.document.msFullscreenEnabled || window.document.webkitFullscreenEnabled);
                }, FullscreenControl.prototype._setupUI = function () {
                    var e = this._fullscreenButton = DOM.create('button', this._className + '-icon ' + this._className + '-fullscreen', this._container);
                    e.setAttribute('aria-label', 'Toggle fullscreen'), e.type = 'button', this._fullscreenButton.addEventListener('click', this._onClickFullscreen), window.document.addEventListener(this._fullscreenchange, this._changeIcon);
                }, FullscreenControl.prototype._isFullscreen = function () {
                    return this._fullscreen;
                }, FullscreenControl.prototype._changeIcon = function () {
                    (window.document.fullscreenElement || window.document.mozFullScreenElement || window.document.webkitFullscreenElement || window.document.msFullscreenElement) === this._mapContainer !== this._fullscreen && (this._fullscreen = !this._fullscreen, this._fullscreenButton.classList.toggle(this._className + '-shrink'), this._fullscreenButton.classList.toggle(this._className + '-fullscreen'));
                }, FullscreenControl.prototype._onClickFullscreen = function () {
                    this._isFullscreen() ? window.document.exitFullscreen ? window.document.exitFullscreen() : window.document.mozCancelFullScreen ? window.document.mozCancelFullScreen() : window.document.msExitFullscreen ? window.document.msExitFullscreen() : window.document.webkitCancelFullScreen && window.document.webkitCancelFullScreen() : this._mapContainer.requestFullscreen ? this._mapContainer.requestFullscreen() : this._mapContainer.mozRequestFullScreen ? this._mapContainer.mozRequestFullScreen() : this._mapContainer.msRequestFullscreen ? this._mapContainer.msRequestFullscreen() : this._mapContainer.webkitRequestFullscreen && this._mapContainer.webkitRequestFullscreen();
                }, module.exports = FullscreenControl;
            },
            {
                '../../util/dom': 259,
                '../../util/util': 275,
                '../../util/window': 254
            }
        ],
        234: [
            function (_dereq_, module, exports) {
                'use strict';
                function checkGeolocationSupport(t) {
                    void 0 !== supportsGeolocation ? t(supportsGeolocation) : void 0 !== window.navigator.permissions ? window.navigator.permissions.query({ name: 'geolocation' }).then(function (o) {
                        supportsGeolocation = 'denied' !== o.state, t(supportsGeolocation);
                    }) : (supportsGeolocation = !!window.navigator.geolocation, t(supportsGeolocation));
                }
                var Evented = _dereq_('../../util/evented'), DOM = _dereq_('../../util/dom'), window = _dereq_('../../util/window'), util = _dereq_('../../util/util'), LngLat = _dereq_('../../geo/lng_lat'), Marker = _dereq_('../marker'), defaultOptions = {
                        positionOptions: {
                            enableHighAccuracy: !1,
                            timeout: 6000
                        },
                        fitBoundsOptions: { maxZoom: 15 },
                        trackUserLocation: !1,
                        showUserLocation: !0
                    }, className = 'mapboxgl-ctrl', supportsGeolocation, GeolocateControl = function (t) {
                        function o(o) {
                            t.call(this), this.options = util.extend({}, defaultOptions, o), util.bindAll([
                                '_onSuccess',
                                '_onError',
                                '_finish',
                                '_setupUI',
                                '_updateCamera',
                                '_updateMarker',
                                '_onClickGeolocate'
                            ], this);
                        }
                        return t && (o.__proto__ = t), o.prototype = Object.create(t && t.prototype), o.prototype.constructor = o, o.prototype.onAdd = function (t) {
                            return this._map = t, this._container = DOM.create('div', className + ' ' + className + '-group'), checkGeolocationSupport(this._setupUI), this._container;
                        }, o.prototype.onRemove = function () {
                            void 0 !== this._geolocationWatchID && (window.navigator.geolocation.clearWatch(this._geolocationWatchID), this._geolocationWatchID = void 0), this.options.showUserLocation && this._userLocationDotMarker.remove(), DOM.remove(this._container), this._map = void 0;
                        }, o.prototype._onSuccess = function (t) {
                            if (this.options.trackUserLocation) {
                                switch (this._lastKnownPosition = t, this._watchState) {
                                case 'WAITING_ACTIVE':
                                case 'ACTIVE_LOCK':
                                case 'ACTIVE_ERROR':
                                    this._watchState = 'ACTIVE_LOCK', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');
                                    break;
                                case 'BACKGROUND':
                                case 'BACKGROUND_ERROR':
                                    this._watchState = 'BACKGROUND', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');
                                }
                            }
                            this.options.showUserLocation && 'OFF' !== this._watchState && this._updateMarker(t), this.options.trackUserLocation && 'ACTIVE_LOCK' !== this._watchState || this._updateCamera(t), this.options.showUserLocation && this._dotElement.classList.remove('mapboxgl-user-location-dot-stale'), this.fire('geolocate', t), this._finish();
                        }, o.prototype._updateCamera = function (t) {
                            var o = new LngLat(t.coords.longitude, t.coords.latitude), e = t.coords.accuracy;
                            this._map.fitBounds(o.toBounds(e), this.options.fitBoundsOptions, { geolocateSource: !0 });
                        }, o.prototype._updateMarker = function (t) {
                            t ? this._userLocationDotMarker.setLngLat([
                                t.coords.longitude,
                                t.coords.latitude
                            ]).addTo(this._map) : this._userLocationDotMarker.remove();
                        }, o.prototype._onError = function (t) {
                            if (this.options.trackUserLocation) {
                                if (1 === t.code) {
                                    this._watchState = 'OFF', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error'), void 0 !== this._geolocationWatchID && this._clearWatch();
                                } else {
                                    switch (this._watchState) {
                                    case 'WAITING_ACTIVE':
                                        this._watchState = 'ACTIVE_ERROR', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');
                                        break;
                                    case 'ACTIVE_LOCK':
                                        this._watchState = 'ACTIVE_ERROR', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                                        break;
                                    case 'BACKGROUND':
                                        this._watchState = 'BACKGROUND_ERROR', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');
                                    }
                                }
                            }
                            'OFF' !== this._watchState && this.options.showUserLocation && this._dotElement.classList.add('mapboxgl-user-location-dot-stale'), this.fire('error', t), this._finish();
                        }, o.prototype._finish = function () {
                            this._timeoutId && clearTimeout(this._timeoutId), this._timeoutId = void 0;
                        }, o.prototype._setupUI = function (t) {
                            var o = this;
                            !1 !== t && (this._container.addEventListener('contextmenu', function (t) {
                                return t.preventDefault();
                            }), this._geolocateButton = DOM.create('button', className + '-icon ' + className + '-geolocate', this._container), this._geolocateButton.type = 'button', this._geolocateButton.setAttribute('aria-label', 'Geolocate'), this.options.trackUserLocation && (this._geolocateButton.setAttribute('aria-pressed', 'false'), this._watchState = 'OFF'), this.options.showUserLocation && (this._dotElement = DOM.create('div', 'mapboxgl-user-location-dot'), this._userLocationDotMarker = new Marker(this._dotElement), this.options.trackUserLocation && (this._watchState = 'OFF')), this._geolocateButton.addEventListener('click', this._onClickGeolocate.bind(this)), this.options.trackUserLocation && this._map.on('movestart', function (t) {
                                t.geolocateSource || 'ACTIVE_LOCK' !== o._watchState || (o._watchState = 'BACKGROUND', o._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background'), o._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'), o.fire('trackuserlocationend'));
                            }));
                        }, o.prototype._onClickGeolocate = function () {
                            if (this.options.trackUserLocation) {
                                switch (this._watchState) {
                                case 'OFF':
                                    this._watchState = 'WAITING_ACTIVE', this.fire('trackuserlocationstart');
                                    break;
                                case 'WAITING_ACTIVE':
                                case 'ACTIVE_LOCK':
                                case 'ACTIVE_ERROR':
                                case 'BACKGROUND_ERROR':
                                    this._watchState = 'OFF', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'), this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error'), this.fire('trackuserlocationend');
                                    break;
                                case 'BACKGROUND':
                                    this._watchState = 'ACTIVE_LOCK', this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background'), this._lastKnownPosition && this._updateCamera(this._lastKnownPosition), this.fire('trackuserlocationstart');
                                }
                                switch (this._watchState) {
                                case 'WAITING_ACTIVE':
                                    this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');
                                    break;
                                case 'ACTIVE_LOCK':
                                    this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');
                                    break;
                                case 'ACTIVE_ERROR':
                                    this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');
                                    break;
                                case 'BACKGROUND':
                                    this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');
                                    break;
                                case 'BACKGROUND_ERROR':
                                    this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');
                                }
                                'OFF' === this._watchState && void 0 !== this._geolocationWatchID ? this._clearWatch() : void 0 === this._geolocationWatchID && (this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.setAttribute('aria-pressed', 'true'), this._geolocationWatchID = window.navigator.geolocation.watchPosition(this._onSuccess, this._onError, this.options.positionOptions));
                            } else {
                                window.navigator.geolocation.getCurrentPosition(this._onSuccess, this._onError, this.options.positionOptions), this._timeoutId = setTimeout(this._finish, 10000);
                            }
                        }, o.prototype._clearWatch = function () {
                            window.navigator.geolocation.clearWatch(this._geolocationWatchID), this._geolocationWatchID = void 0, this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting'), this._geolocateButton.setAttribute('aria-pressed', 'false'), this.options.showUserLocation && this._updateMarker(null);
                        }, o;
                    }(Evented);
                module.exports = GeolocateControl;
            },
            {
                '../../geo/lng_lat': 62,
                '../../util/dom': 259,
                '../../util/evented': 260,
                '../../util/util': 275,
                '../../util/window': 254,
                '../marker': 248
            }
        ],
        235: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), LogoControl = function () {
                        util.bindAll(['_updateLogo'], this);
                    };
                LogoControl.prototype.onAdd = function (o) {
                    this._map = o, this._container = DOM.create('div', 'mapboxgl-ctrl');
                    var t = DOM.create('a', 'mapboxgl-ctrl-logo');
                    return t.target = '_blank', t.href = 'https://www.mapbox.com/', t.setAttribute('aria-label', 'Mapbox logo'), this._container.appendChild(t), this._container.style.display = 'none', this._map.on('sourcedata', this._updateLogo), this._updateLogo(), this._container;
                }, LogoControl.prototype.onRemove = function () {
                    DOM.remove(this._container), this._map.off('sourcedata', this._updateLogo);
                }, LogoControl.prototype.getDefaultPosition = function () {
                    return 'bottom-left';
                }, LogoControl.prototype._updateLogo = function (o) {
                    o && 'metadata' !== o.sourceDataType || (this._container.style.display = this._logoRequired() ? 'block' : 'none');
                }, LogoControl.prototype._logoRequired = function () {
                    if (this._map.style) {
                        var o = this._map.style.sourceCaches;
                        for (var t in o) {
                            if (o[t].getSource().mapbox_logo) {
                                return !0;
                            }
                        }
                        return !1;
                    }
                }, module.exports = LogoControl;
            },
            {
                '../../util/dom': 259,
                '../../util/util': 275
            }
        ],
        236: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), DragRotateHandler = _dereq_('../handler/drag_rotate'), defaultOptions = {
                        showCompass: !0,
                        showZoom: !0
                    }, NavigationControl = function (t) {
                        var o = this;
                        this.options = util.extend({}, defaultOptions, t), this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-group'), this._container.addEventListener('contextmenu', function (t) {
                            return t.preventDefault();
                        }), this.options.showZoom && (this._zoomInButton = this._createButton('mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-in', 'Zoom In', function () {
                            return o._map.zoomIn();
                        }), this._zoomOutButton = this._createButton('mapboxgl-ctrl-icon mapboxgl-ctrl-zoom-out', 'Zoom Out', function () {
                            return o._map.zoomOut();
                        })), this.options.showCompass && (util.bindAll(['_rotateCompassArrow'], this), this._compass = this._createButton('mapboxgl-ctrl-icon mapboxgl-ctrl-compass', 'Reset North', function () {
                            return o._map.resetNorth();
                        }), this._compassArrow = DOM.create('span', 'mapboxgl-ctrl-compass-arrow', this._compass));
                    };
                NavigationControl.prototype._rotateCompassArrow = function () {
                    var t = 'rotate(' + this._map.transform.angle * (180 / Math.PI) + 'deg)';
                    this._compassArrow.style.transform = t;
                }, NavigationControl.prototype.onAdd = function (t) {
                    return this._map = t, this.options.showCompass && (this._map.on('rotate', this._rotateCompassArrow), this._rotateCompassArrow(), this._handler = new DragRotateHandler(t, {
                        button: 'left',
                        element: this._compass
                    }), this._handler.enable()), this._container;
                }, NavigationControl.prototype.onRemove = function () {
                    DOM.remove(this._container), this.options.showCompass && (this._map.off('rotate', this._rotateCompassArrow), this._handler.disable(), delete this._handler), delete this._map;
                }, NavigationControl.prototype._createButton = function (t, o, r) {
                    var e = DOM.create('button', t, this._container);
                    return e.type = 'button', e.setAttribute('aria-label', o), e.addEventListener('click', r), e;
                }, module.exports = NavigationControl;
            },
            {
                '../../util/dom': 259,
                '../../util/util': 275,
                '../handler/drag_rotate': 242
            }
        ],
        237: [
            function (_dereq_, module, exports) {
                'use strict';
                function updateScale(t, e, o) {
                    var n = o && o.maxWidth || 100, i = t._container.clientHeight / 2, a = getDistance(t.unproject([
                            0,
                            i
                        ]), t.unproject([
                            n,
                            i
                        ]));
                    if (o && 'imperial' === o.unit) {
                        var l = 3.2808 * a;
                        if (l > 5280) {
                            setScale(e, n, l / 5280, 'mi');
                        } else {
                            setScale(e, n, l, 'ft');
                        }
                    } else if (o && 'nautical' === o.unit) {
                        var r = a / 1852;
                        setScale(e, n, r, 'nm');
                    } else {
                        setScale(e, n, a, 'm');
                    }
                }
                function setScale(t, e, o, n) {
                    var i = getRoundNum(o), a = i / o;
                    'm' === n && i >= 1000 && (i /= 1000, n = 'km'), t.style.width = e * a + 'px', t.innerHTML = i + n;
                }
                function getDistance(t, e) {
                    var o = Math.PI / 180, n = t.lat * o, i = e.lat * o, a = Math.sin(n) * Math.sin(i) + Math.cos(n) * Math.cos(i) * Math.cos((e.lng - t.lng) * o);
                    return 6371000 * Math.acos(Math.min(a, 1));
                }
                function getRoundNum(t) {
                    var e = Math.pow(10, ('' + Math.floor(t)).length - 1), o = t / e;
                    return o = o >= 10 ? 10 : o >= 5 ? 5 : o >= 3 ? 3 : o >= 2 ? 2 : 1, e * o;
                }
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), ScaleControl = function (t) {
                        this.options = t, util.bindAll(['_onMove'], this);
                    };
                ScaleControl.prototype.getDefaultPosition = function () {
                    return 'bottom-left';
                }, ScaleControl.prototype._onMove = function () {
                    updateScale(this._map, this._container, this.options);
                }, ScaleControl.prototype.onAdd = function (t) {
                    return this._map = t, this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', t.getContainer()), this._map.on('move', this._onMove), this._onMove(), this._container;
                }, ScaleControl.prototype.onRemove = function () {
                    DOM.remove(this._container), this._map.off('move', this._onMove), this._map = void 0;
                }, module.exports = ScaleControl;
            },
            {
                '../../util/dom': 259,
                '../../util/util': 275
            }
        ],
        238: [
            function (_dereq_, module, exports) {
                'use strict';
            },
            {}
        ],
        239: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), LngLatBounds = _dereq_('../../geo/lng_lat_bounds'), util = _dereq_('../../util/util'), window = _dereq_('../../util/window'), BoxZoomHandler = function (o) {
                        this._map = o, this._el = o.getCanvasContainer(), this._container = o.getContainer(), util.bindAll([
                            '_onMouseDown',
                            '_onMouseMove',
                            '_onMouseUp',
                            '_onKeyDown'
                        ], this);
                    };
                BoxZoomHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, BoxZoomHandler.prototype.isActive = function () {
                    return !!this._active;
                }, BoxZoomHandler.prototype.enable = function () {
                    this.isEnabled() || (this._map.dragPan && this._map.dragPan.disable(), this._el.addEventListener('mousedown', this._onMouseDown, !1), this._map.dragPan && this._map.dragPan.enable(), this._enabled = !0);
                }, BoxZoomHandler.prototype.disable = function () {
                    this.isEnabled() && (this._el.removeEventListener('mousedown', this._onMouseDown), this._enabled = !1);
                }, BoxZoomHandler.prototype._onMouseDown = function (o) {
                    o.shiftKey && 0 === o.button && (window.document.addEventListener('mousemove', this._onMouseMove, !1), window.document.addEventListener('keydown', this._onKeyDown, !1), window.document.addEventListener('mouseup', this._onMouseUp, !1), DOM.disableDrag(), this._startPos = DOM.mousePos(this._el, o), this._active = !0);
                }, BoxZoomHandler.prototype._onMouseMove = function (o) {
                    var e = this._startPos, t = DOM.mousePos(this._el, o);
                    this._box || (this._box = DOM.create('div', 'mapboxgl-boxzoom', this._container), this._container.classList.add('mapboxgl-crosshair'), this._fireEvent('boxzoomstart', o));
                    var n = Math.min(e.x, t.x), i = Math.max(e.x, t.x), s = Math.min(e.y, t.y), a = Math.max(e.y, t.y);
                    DOM.setTransform(this._box, 'translate(' + n + 'px,' + s + 'px)'), this._box.style.width = i - n + 'px', this._box.style.height = a - s + 'px';
                }, BoxZoomHandler.prototype._onMouseUp = function (o) {
                    if (0 === o.button) {
                        var e = this._startPos, t = DOM.mousePos(this._el, o), n = new LngLatBounds().extend(this._map.unproject(e)).extend(this._map.unproject(t));
                        this._finish(), e.x === t.x && e.y === t.y ? this._fireEvent('boxzoomcancel', o) : this._map.fitBounds(n, { linear: !0 }).fire('boxzoomend', {
                            originalEvent: o,
                            boxZoomBounds: n
                        });
                    }
                }, BoxZoomHandler.prototype._onKeyDown = function (o) {
                    27 === o.keyCode && (this._finish(), this._fireEvent('boxzoomcancel', o));
                }, BoxZoomHandler.prototype._finish = function () {
                    this._active = !1, window.document.removeEventListener('mousemove', this._onMouseMove, !1), window.document.removeEventListener('keydown', this._onKeyDown, !1), window.document.removeEventListener('mouseup', this._onMouseUp, !1), this._container.classList.remove('mapboxgl-crosshair'), this._box && (DOM.remove(this._box), this._box = null), DOM.enableDrag();
                }, BoxZoomHandler.prototype._fireEvent = function (o, e) {
                    return this._map.fire(o, { originalEvent: e });
                }, module.exports = BoxZoomHandler;
            },
            {
                '../../geo/lng_lat_bounds': 63,
                '../../util/dom': 259,
                '../../util/util': 275,
                '../../util/window': 254
            }
        ],
        240: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../../util/util'), DoubleClickZoomHandler = function (o) {
                        this._map = o, util.bindAll([
                            '_onDblClick',
                            '_onZoomEnd'
                        ], this);
                    };
                DoubleClickZoomHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, DoubleClickZoomHandler.prototype.isActive = function () {
                    return !!this._active;
                }, DoubleClickZoomHandler.prototype.enable = function () {
                    this.isEnabled() || (this._map.on('dblclick', this._onDblClick), this._enabled = !0);
                }, DoubleClickZoomHandler.prototype.disable = function () {
                    this.isEnabled() && (this._map.off('dblclick', this._onDblClick), this._enabled = !1);
                }, DoubleClickZoomHandler.prototype._onDblClick = function (o) {
                    this._active = !0, this._map.on('zoomend', this._onZoomEnd), this._map.zoomTo(this._map.getZoom() + (o.originalEvent.shiftKey ? -1 : 1), { around: o.lngLat }, o);
                }, DoubleClickZoomHandler.prototype._onZoomEnd = function () {
                    this._active = !1, this._map.off('zoomend', this._onZoomEnd);
                }, module.exports = DoubleClickZoomHandler;
            },
            { '../../util/util': 275 }
        ],
        241: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), window = _dereq_('../../util/window'), browser = _dereq_('../../util/browser'), inertiaLinearity = 0.3, inertiaEasing = util.bezier(0, 0, inertiaLinearity, 1), inertiaMaxSpeed = 1400, inertiaDeceleration = 2500, DragPanHandler = function (e) {
                        this._map = e, this._el = e.getCanvasContainer(), util.bindAll([
                            '_onDown',
                            '_onMove',
                            '_onUp',
                            '_onTouchEnd',
                            '_onMouseUp',
                            '_onDragFrame',
                            '_onDragFinished'
                        ], this);
                    };
                DragPanHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, DragPanHandler.prototype.isActive = function () {
                    return !!this._active;
                }, DragPanHandler.prototype.enable = function () {
                    this.isEnabled() || (this._el.classList.add('mapboxgl-touch-drag-pan'), this._el.addEventListener('mousedown', this._onDown), this._el.addEventListener('touchstart', this._onDown), this._enabled = !0);
                }, DragPanHandler.prototype.disable = function () {
                    this.isEnabled() && (this._el.classList.remove('mapboxgl-touch-drag-pan'), this._el.removeEventListener('mousedown', this._onDown), this._el.removeEventListener('touchstart', this._onDown), this._enabled = !1);
                }, DragPanHandler.prototype._onDown = function (e) {
                    this._ignoreEvent(e) || this.isActive() || (e.touches ? (window.document.addEventListener('touchmove', this._onMove), window.document.addEventListener('touchend', this._onTouchEnd)) : (window.document.addEventListener('mousemove', this._onMove), window.document.addEventListener('mouseup', this._onMouseUp)), window.addEventListener('blur', this._onMouseUp), this._active = !1, this._previousPos = DOM.mousePos(this._el, e), this._inertia = [[
                            browser.now(),
                            this._previousPos
                        ]]);
                }, DragPanHandler.prototype._onMove = function (e) {
                    if (!this._ignoreEvent(e)) {
                        this._lastMoveEvent = e, e.preventDefault();
                        var t = DOM.mousePos(this._el, e);
                        if (this._drainInertiaBuffer(), this._inertia.push([
                                browser.now(),
                                t
                            ]), !this._previousPos) {
                            return void (this._previousPos = t);
                        }
                        this._pos = t, this.isActive() || (this._active = !0, this._map.moving = !0, this._fireEvent('dragstart', e), this._fireEvent('movestart', e), this._map._startAnimation(this._onDragFrame, this._onDragFinished)), this._map._update();
                    }
                }, DragPanHandler.prototype._onDragFrame = function (e) {
                    var t = this._lastMoveEvent;
                    t && (e.setLocationAtPoint(e.pointLocation(this._previousPos), this._pos), this._fireEvent('drag', t), this._fireEvent('move', t), this._previousPos = this._pos, delete this._lastMoveEvent);
                }, DragPanHandler.prototype._onDragFinished = function (e) {
                    var t = this;
                    if (this.isActive()) {
                        this._active = !1, delete this._lastMoveEvent, delete this._previousPos, delete this._pos, this._fireEvent('dragend', e), this._drainInertiaBuffer();
                        var n = function () {
                                t._map.moving = !1, t._fireEvent('moveend', e);
                            }, i = this._inertia;
                        if (i.length < 2) {
                            return void n();
                        }
                        var o = i[i.length - 1], r = i[0], s = o[1].sub(r[1]), a = (o[0] - r[0]) / 1000;
                        if (0 === a || o[1].equals(r[1])) {
                            return void n();
                        }
                        var h = s.mult(inertiaLinearity / a), u = h.mag();
                        u > inertiaMaxSpeed && (u = inertiaMaxSpeed, h._unit()._mult(u));
                        var d = u / (inertiaDeceleration * inertiaLinearity), _ = h.mult(-d / 2);
                        this._map.panBy(_, {
                            duration: 1000 * d,
                            easing: inertiaEasing,
                            noMoveStart: !0
                        }, { originalEvent: e });
                    }
                }, DragPanHandler.prototype._onUp = function (e) {
                    this._onDragFinished(e);
                }, DragPanHandler.prototype._onMouseUp = function (e) {
                    this._ignoreEvent(e) || (this._onUp(e), window.document.removeEventListener('mousemove', this._onMove), window.document.removeEventListener('mouseup', this._onMouseUp), window.removeEventListener('blur', this._onMouseUp));
                }, DragPanHandler.prototype._onTouchEnd = function (e) {
                    this._ignoreEvent(e) || (this._onUp(e), window.document.removeEventListener('touchmove', this._onMove), window.document.removeEventListener('touchend', this._onTouchEnd));
                }, DragPanHandler.prototype._fireEvent = function (e, t) {
                    return this._map.fire(e, t ? { originalEvent: t } : {});
                }, DragPanHandler.prototype._ignoreEvent = function (e) {
                    var t = this._map;
                    return !(!t.boxZoom || !t.boxZoom.isActive()) || (!(!t.dragRotate || !t.dragRotate.isActive()) || (e.touches ? e.touches.length > 1 : !!e.ctrlKey || 'mousemove' !== e.type && e.button && 0 !== e.button));
                }, DragPanHandler.prototype._drainInertiaBuffer = function () {
                    for (var e = this._inertia, t = browser.now(); e.length > 0 && t - e[0][0] > 160;) {
                        e.shift();
                    }
                }, module.exports = DragPanHandler;
            },
            {
                '../../util/browser': 252,
                '../../util/dom': 259,
                '../../util/util': 275,
                '../../util/window': 254
            }
        ],
        242: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), window = _dereq_('../../util/window'), browser = _dereq_('../../util/browser'), inertiaLinearity = 0.25, inertiaEasing = util.bezier(0, 0, inertiaLinearity, 1), inertiaMaxSpeed = 180, inertiaDeceleration = 720, DragRotateHandler = function (t, e) {
                        this._map = t, this._el = e.element || t.getCanvasContainer(), this._button = e.button || 'right', this._bearingSnap = e.bearingSnap || 0, this._pitchWithRotate = !1 !== e.pitchWithRotate, util.bindAll([
                            '_onDown',
                            '_onMove',
                            '_onUp',
                            '_onDragFrame',
                            '_onDragFinished'
                        ], this);
                    };
                DragRotateHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, DragRotateHandler.prototype.isActive = function () {
                    return !!this._active;
                }, DragRotateHandler.prototype.enable = function () {
                    this.isEnabled() || (this._el.addEventListener('mousedown', this._onDown), this._enabled = !0);
                }, DragRotateHandler.prototype.disable = function () {
                    this.isEnabled() && (this._el.removeEventListener('mousedown', this._onDown), this._enabled = !1);
                }, DragRotateHandler.prototype._onDown = function (t) {
                    if (!(this._map.boxZoom && this._map.boxZoom.isActive() || this._map.dragPan && this._map.dragPan.isActive() || this.isActive())) {
                        if ('right' === this._button) {
                            var e = t.ctrlKey ? 0 : 2, i = t.button;
                            if (void 0 !== window.InstallTrigger && 2 === t.button && t.ctrlKey && window.navigator.platform.toUpperCase().indexOf('MAC') >= 0 && (i = 0), i !== e) {
                                return;
                            }
                        } else if (t.ctrlKey || 0 !== t.button) {
                            return;
                        }
                        DOM.disableDrag(), window.document.addEventListener('mousemove', this._onMove, { capture: !0 }), window.document.addEventListener('mouseup', this._onUp), window.addEventListener('blur', this._onUp), this._active = !1, this._inertia = [[
                                browser.now(),
                                this._map.getBearing()
                            ]], this._previousPos = DOM.mousePos(this._el, t), this._center = this._map.transform.centerPoint, t.preventDefault();
                    }
                }, DragRotateHandler.prototype._onMove = function (t) {
                    this._lastMoveEvent = t;
                    var e = DOM.mousePos(this._el, t);
                    if (!this._previousPos) {
                        return void (this._previousPos = e);
                    }
                    this._pos = e, this.isActive() || (this._active = !0, this._map.moving = !0, this._fireEvent('rotatestart', t), this._fireEvent('movestart', t), this._pitchWithRotate && this._fireEvent('pitchstart', t), this._map._startAnimation(this._onDragFrame, this._onDragFinished)), this._map._update();
                }, DragRotateHandler.prototype._onUp = function (t) {
                    window.document.removeEventListener('mousemove', this._onMove, { capture: !0 }), window.document.removeEventListener('mouseup', this._onUp), window.removeEventListener('blur', this._onUp), DOM.enableDrag(), this._onDragFinished(t);
                }, DragRotateHandler.prototype._onDragFrame = function (t) {
                    var e = this._lastMoveEvent;
                    if (e) {
                        var i = this._previousPos, n = this._pos, r = 0.8 * (i.x - n.x), a = -0.5 * (i.y - n.y), o = t.bearing - r, s = t.pitch - a, h = this._inertia, _ = h[h.length - 1];
                        this._drainInertiaBuffer(), h.push([
                            browser.now(),
                            this._map._normalizeBearing(o, _[1])
                        ]), t.bearing = o, this._pitchWithRotate && (this._fireEvent('pitch', e), t.pitch = s), this._fireEvent('rotate', e), this._fireEvent('move', e), delete this._lastMoveEvent, this._previousPos = this._pos;
                    }
                }, DragRotateHandler.prototype._onDragFinished = function (t) {
                    var e = this;
                    if (this.isActive()) {
                        this._active = !1, delete this._lastMoveEvent, delete this._previousPos, this._fireEvent('rotateend', t), this._drainInertiaBuffer();
                        var i = this._map, n = i.getBearing(), r = this._inertia, a = function () {
                                Math.abs(n) < e._bearingSnap ? i.resetNorth({ noMoveStart: !0 }, { originalEvent: t }) : (e._map.moving = !1, e._fireEvent('moveend', t)), e._pitchWithRotate && e._fireEvent('pitchend', t);
                            };
                        if (r.length < 2) {
                            return void a();
                        }
                        var o = r[0], s = r[r.length - 1], h = r[r.length - 2], _ = i._normalizeBearing(n, h[1]), v = s[1] - o[1], p = v < 0 ? -1 : 1, d = (s[0] - o[0]) / 1000;
                        if (0 === v || 0 === d) {
                            return void a();
                        }
                        var u = Math.abs(v * (inertiaLinearity / d));
                        u > inertiaMaxSpeed && (u = inertiaMaxSpeed);
                        var l = u / (inertiaDeceleration * inertiaLinearity);
                        _ += p * u * (l / 2), Math.abs(i._normalizeBearing(_, 0)) < this._bearingSnap && (_ = i._normalizeBearing(0, _)), i.rotateTo(_, {
                            duration: 1000 * l,
                            easing: inertiaEasing,
                            noMoveStart: !0
                        }, { originalEvent: t });
                    }
                }, DragRotateHandler.prototype._fireEvent = function (t, e) {
                    return this._map.fire(t, e ? { originalEvent: e } : {});
                }, DragRotateHandler.prototype._drainInertiaBuffer = function () {
                    for (var t = this._inertia, e = browser.now(); t.length > 0 && e - t[0][0] > 160;) {
                        t.shift();
                    }
                }, module.exports = DragRotateHandler;
            },
            {
                '../../util/browser': 252,
                '../../util/dom': 259,
                '../../util/util': 275,
                '../../util/window': 254
            }
        ],
        243: [
            function (_dereq_, module, exports) {
                'use strict';
                function easeOut(e) {
                    return e * (2 - e);
                }
                var util = _dereq_('../../util/util'), panStep = 100, bearingStep = 15, pitchStep = 10, KeyboardHandler = function (e) {
                        this._map = e, this._el = e.getCanvasContainer(), util.bindAll(['_onKeyDown'], this);
                    };
                KeyboardHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, KeyboardHandler.prototype.enable = function () {
                    this.isEnabled() || (this._el.addEventListener('keydown', this._onKeyDown, !1), this._enabled = !0);
                }, KeyboardHandler.prototype.disable = function () {
                    this.isEnabled() && (this._el.removeEventListener('keydown', this._onKeyDown), this._enabled = !1);
                }, KeyboardHandler.prototype._onKeyDown = function (e) {
                    if (!(e.altKey || e.ctrlKey || e.metaKey)) {
                        var t = 0, a = 0, n = 0, r = 0, i = 0;
                        switch (e.keyCode) {
                        case 61:
                        case 107:
                        case 171:
                        case 187:
                            t = 1;
                            break;
                        case 189:
                        case 109:
                        case 173:
                            t = -1;
                            break;
                        case 37:
                            e.shiftKey ? a = -1 : (e.preventDefault(), r = -1);
                            break;
                        case 39:
                            e.shiftKey ? a = 1 : (e.preventDefault(), r = 1);
                            break;
                        case 38:
                            e.shiftKey ? n = 1 : (e.preventDefault(), i = -1);
                            break;
                        case 40:
                            e.shiftKey ? n = -1 : (i = 1, e.preventDefault());
                            break;
                        default:
                            return;
                        }
                        var s = this._map, o = s.getZoom(), l = {
                                duration: 300,
                                delayEndEvents: 500,
                                easing: easeOut,
                                zoom: t ? Math.round(o) + t * (e.shiftKey ? 2 : 1) : o,
                                bearing: s.getBearing() + a * bearingStep,
                                pitch: s.getPitch() + n * pitchStep,
                                offset: [
                                    -r * panStep,
                                    -i * panStep
                                ],
                                center: s.getCenter()
                            };
                        s.easeTo(l, { originalEvent: e });
                    }
                }, module.exports = KeyboardHandler;
            },
            { '../../util/util': 275 }
        ],
        244: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), browser = _dereq_('../../util/browser'), window = _dereq_('../../util/window'), interpolate = _dereq_('../../style-spec/util/interpolate').number, LngLat = _dereq_('../../geo/lng_lat'), wheelZoomDelta = 4.000244140625, defaultZoomRate = 0.01, wheelZoomRate = 1 / 450, maxScalePerFrame = 2, ua = window.navigator.userAgent.toLowerCase(), firefox = -1 !== ua.indexOf('firefox'), safari = -1 !== ua.indexOf('safari') && -1 === ua.indexOf('chrom'), ScrollZoomHandler = function (t) {
                        this._map = t, this._el = t.getCanvasContainer(), this._delta = 0, util.bindAll([
                            '_onWheel',
                            '_onTimeout',
                            '_onScrollFrame',
                            '_onScrollFinished'
                        ], this);
                    };
                ScrollZoomHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, ScrollZoomHandler.prototype.isActive = function () {
                    return !!this._active;
                }, ScrollZoomHandler.prototype.enable = function (t) {
                    this.isEnabled() || (this._el.addEventListener('wheel', this._onWheel, !1), this._el.addEventListener('mousewheel', this._onWheel, !1), this._enabled = !0, this._aroundCenter = t && 'center' === t.around);
                }, ScrollZoomHandler.prototype.disable = function () {
                    this.isEnabled() && (this._el.removeEventListener('wheel', this._onWheel), this._el.removeEventListener('mousewheel', this._onWheel), this._enabled = !1);
                }, ScrollZoomHandler.prototype._onWheel = function (t) {
                    var e = 0;
                    'wheel' === t.type ? (e = t.deltaY, firefox && t.deltaMode === window.WheelEvent.DOM_DELTA_PIXEL && (e /= browser.devicePixelRatio), t.deltaMode === window.WheelEvent.DOM_DELTA_LINE && (e *= 40)) : 'mousewheel' === t.type && (e = -t.wheelDeltaY, safari && (e /= 3));
                    var i = browser.now(), o = i - (this._lastWheelEventTime || 0);
                    this._lastWheelEventTime = i, 0 !== e && e % wheelZoomDelta == 0 ? this._type = 'wheel' : 0 !== e && Math.abs(e) < 4 ? this._type = 'trackpad' : o > 400 ? (this._type = null, this._lastValue = e, this._timeout = setTimeout(this._onTimeout, 40, t)) : this._type || (this._type = Math.abs(o * e) < 200 ? 'trackpad' : 'wheel', this._timeout && (clearTimeout(this._timeout), this._timeout = null, e += this._lastValue)), t.shiftKey && e && (e /= 4), this._type && (this._lastWheelEvent = t, this._delta -= e, this.isActive() || this._start(t)), t.preventDefault();
                }, ScrollZoomHandler.prototype._onTimeout = function (t) {
                    this._type = 'wheel', this._delta -= this._lastValue, this.isActive() || this._start(t);
                }, ScrollZoomHandler.prototype._start = function (t) {
                    if (this._delta) {
                        this._active = !0, this._map.moving = !0, this._map.zooming = !0, this._map.fire('movestart', { originalEvent: t }), this._map.fire('zoomstart', { originalEvent: t }), clearTimeout(this._finishTimeout);
                        var e = DOM.mousePos(this._el, t);
                        this._around = LngLat.convert(this._aroundCenter ? this._map.getCenter() : this._map.unproject(e)), this._aroundPoint = this._map.transform.locationPoint(this._around), this._map._startAnimation(this._onScrollFrame, this._onScrollFinished);
                    }
                }, ScrollZoomHandler.prototype._onScrollFrame = function (t) {
                    if (this.isActive()) {
                        if (0 !== this._delta) {
                            var e = 'wheel' === this._type && Math.abs(this._delta) > wheelZoomDelta ? wheelZoomRate : defaultZoomRate, i = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * e)));
                            this._delta < 0 && 0 !== i && (i = 1 / i);
                            var o = 'number' == typeof this._targetZoom ? t.zoomScale(this._targetZoom) : t.scale;
                            this._targetZoom = Math.min(t.maxZoom, Math.max(t.minZoom, t.scaleZoom(o * i))), 'wheel' === this._type && (this._startZoom = t.zoom, this._easing = this._smoothOutEasing(200)), this._delta = 0;
                        }
                        if ('wheel' === this._type) {
                            var a = Math.min((browser.now() - this._lastWheelEventTime) / 200, 1), s = this._easing(a);
                            t.zoom = interpolate(this._startZoom, this._targetZoom, s), 1 === a && this._map.stop();
                        } else {
                            t.zoom = this._targetZoom, this._map.stop();
                        }
                        t.setLocationAtPoint(this._around, this._aroundPoint), this._map.fire('move', { originalEvent: this._lastWheelEvent }), this._map.fire('zoom', { originalEvent: this._lastWheelEvent });
                    }
                }, ScrollZoomHandler.prototype._onScrollFinished = function () {
                    var t = this;
                    this.isActive() && (this._active = !1, this._finishTimeout = setTimeout(function () {
                        t._map.moving = !1, t._map.zooming = !1, t._map.fire('zoomend'), t._map.fire('moveend'), delete t._targetZoom;
                    }, 200));
                }, ScrollZoomHandler.prototype._smoothOutEasing = function (t) {
                    var e = util.ease;
                    if (this._prevEase) {
                        var i = this._prevEase, o = (browser.now() - i.start) / i.duration, a = i.easing(o + 0.01) - i.easing(o), s = 0.27 / Math.sqrt(a * a + 0.0001) * 0.01, r = Math.sqrt(0.0729 - s * s);
                        e = util.bezier(s, r, 0.25, 1);
                    }
                    return this._prevEase = {
                        start: browser.now(),
                        duration: t,
                        easing: e
                    }, e;
                }, module.exports = ScrollZoomHandler;
            },
            {
                '../../geo/lng_lat': 62,
                '../../style-spec/util/interpolate': 158,
                '../../util/browser': 252,
                '../../util/dom': 259,
                '../../util/util': 275,
                '../../util/window': 254
            }
        ],
        245: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../../util/dom'), util = _dereq_('../../util/util'), window = _dereq_('../../util/window'), browser = _dereq_('../../util/browser'), inertiaLinearity = 0.15, inertiaEasing = util.bezier(0, 0, inertiaLinearity, 1), inertiaDeceleration = 12, inertiaMaxSpeed = 2.5, significantScaleThreshold = 0.15, significantRotateThreshold = 10, TouchZoomRotateHandler = function (t) {
                        this._map = t, this._el = t.getCanvasContainer(), util.bindAll([
                            '_onStart',
                            '_onMove',
                            '_onEnd'
                        ], this);
                    };
                TouchZoomRotateHandler.prototype.isEnabled = function () {
                    return !!this._enabled;
                }, TouchZoomRotateHandler.prototype.enable = function (t) {
                    this.isEnabled() || (this._el.classList.add('mapboxgl-touch-zoom-rotate'), this._el.addEventListener('touchstart', this._onStart, !1), this._enabled = !0, this._aroundCenter = t && 'center' === t.around);
                }, TouchZoomRotateHandler.prototype.disable = function () {
                    this.isEnabled() && (this._el.classList.remove('mapboxgl-touch-zoom-rotate'), this._el.removeEventListener('touchstart', this._onStart), this._enabled = !1);
                }, TouchZoomRotateHandler.prototype.disableRotation = function () {
                    this._rotationDisabled = !0;
                }, TouchZoomRotateHandler.prototype.enableRotation = function () {
                    this._rotationDisabled = !1;
                }, TouchZoomRotateHandler.prototype._onStart = function (t) {
                    if (2 === t.touches.length) {
                        var e = DOM.mousePos(this._el, t.touches[0]), o = DOM.mousePos(this._el, t.touches[1]);
                        this._startVec = e.sub(o), this._startScale = this._map.transform.scale, this._startBearing = this._map.transform.bearing, this._gestureIntent = void 0, this._inertia = [], window.document.addEventListener('touchmove', this._onMove, !1), window.document.addEventListener('touchend', this._onEnd, !1);
                    }
                }, TouchZoomRotateHandler.prototype._onMove = function (t) {
                    if (2 === t.touches.length) {
                        var e = DOM.mousePos(this._el, t.touches[0]), o = DOM.mousePos(this._el, t.touches[1]), i = e.add(o).div(2), n = e.sub(o), a = n.mag() / this._startVec.mag(), r = this._rotationDisabled ? 0 : 180 * n.angleWith(this._startVec) / Math.PI, s = this._map;
                        if (this._gestureIntent) {
                            var h = {
                                duration: 0,
                                around: s.unproject(i)
                            };
                            'rotate' === this._gestureIntent && (h.bearing = this._startBearing + r), 'zoom' !== this._gestureIntent && 'rotate' !== this._gestureIntent || (h.zoom = s.transform.scaleZoom(this._startScale * a)), s.stop(), this._drainInertiaBuffer(), this._inertia.push([
                                browser.now(),
                                a,
                                i
                            ]), s.easeTo(h, { originalEvent: t });
                        } else {
                            var u = Math.abs(1 - a) > significantScaleThreshold;
                            Math.abs(r) > significantRotateThreshold ? this._gestureIntent = 'rotate' : u && (this._gestureIntent = 'zoom'), this._gestureIntent && (this._startVec = n, this._startScale = s.transform.scale, this._startBearing = s.transform.bearing);
                        }
                        t.preventDefault();
                    }
                }, TouchZoomRotateHandler.prototype._onEnd = function (t) {
                    window.document.removeEventListener('touchmove', this._onMove), window.document.removeEventListener('touchend', this._onEnd), this._drainInertiaBuffer();
                    var e = this._inertia, o = this._map;
                    if (e.length < 2) {
                        return void o.snapToNorth({}, { originalEvent: t });
                    }
                    var i = e[e.length - 1], n = e[0], a = o.transform.scaleZoom(this._startScale * i[1]), r = o.transform.scaleZoom(this._startScale * n[1]), s = a - r, h = (i[0] - n[0]) / 1000, u = i[2];
                    if (0 === h || a === r) {
                        return void o.snapToNorth({}, { originalEvent: t });
                    }
                    var l = s * inertiaLinearity / h;
                    Math.abs(l) > inertiaMaxSpeed && (l = l > 0 ? inertiaMaxSpeed : -inertiaMaxSpeed);
                    var d = 1000 * Math.abs(l / (inertiaDeceleration * inertiaLinearity)), c = a + l * d / 2000;
                    c < 0 && (c = 0), o.easeTo({
                        zoom: c,
                        duration: d,
                        easing: inertiaEasing,
                        around: this._aroundCenter ? o.getCenter() : o.unproject(u)
                    }, { originalEvent: t });
                }, TouchZoomRotateHandler.prototype._drainInertiaBuffer = function () {
                    for (var t = this._inertia, e = browser.now(); t.length > 2 && e - t[0][0] > 160;) {
                        t.shift();
                    }
                }, module.exports = TouchZoomRotateHandler;
            },
            {
                '../../util/browser': 252,
                '../../util/dom': 259,
                '../../util/util': 275,
                '../../util/window': 254
            }
        ],
        246: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('../util/util'), window = _dereq_('../util/window'), throttle = _dereq_('../util/throttle'), Hash = function () {
                        util.bindAll([
                            '_onHashChange',
                            '_updateHash'
                        ], this), this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 300);
                    };
                Hash.prototype.addTo = function (t) {
                    return this._map = t, window.addEventListener('hashchange', this._onHashChange, !1), this._map.on('moveend', this._updateHash), this;
                }, Hash.prototype.remove = function () {
                    return window.removeEventListener('hashchange', this._onHashChange, !1), this._map.off('moveend', this._updateHash), delete this._map, this;
                }, Hash.prototype.getHashString = function (t) {
                    var e = this._map.getCenter(), h = Math.round(100 * this._map.getZoom()) / 100, a = Math.ceil((h * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10), n = Math.pow(10, a), i = Math.round(e.lng * n) / n, o = Math.round(e.lat * n) / n, s = this._map.getBearing(), r = this._map.getPitch(), u = '';
                    return u += t ? '#/' + i + '/' + o + '/' + h : '#' + h + '/' + o + '/' + i, (s || r) && (u += '/' + Math.round(10 * s) / 10), r && (u += '/' + Math.round(r)), u;
                }, Hash.prototype._onHashChange = function () {
                    var t = window.location.hash.replace('#', '').split('/');
                    return t.length >= 3 && (this._map.jumpTo({
                        center: [
                            +t[2],
                            +t[1]
                        ],
                        zoom: +t[0],
                        bearing: +(t[3] || 0),
                        pitch: +(t[4] || 0)
                    }), !0);
                }, Hash.prototype._updateHashUnthrottled = function () {
                    var t = this.getHashString();
                    window.history.replaceState('', '', t);
                }, module.exports = Hash;
            },
            {
                '../util/throttle': 272,
                '../util/util': 275,
                '../util/window': 254
            }
        ],
        247: [
            function (_dereq_, module, exports) {
                'use strict';
                function removeNode(t) {
                    t.parentNode && t.parentNode.removeChild(t);
                }
                var util = _dereq_('../util/util'), browser = _dereq_('../util/browser'), window = _dereq_('../util/window'), ref = _dereq_('../util/window'), HTMLImageElement = ref.HTMLImageElement, HTMLElement = ref.HTMLElement, DOM = _dereq_('../util/dom'), ajax = _dereq_('../util/ajax'), Style = _dereq_('../style/style'), EvaluationParameters = _dereq_('../style/evaluation_parameters'), Painter = _dereq_('../render/painter'), Transform = _dereq_('../geo/transform'), Hash = _dereq_('./hash'), bindHandlers = _dereq_('./bind_handlers'), Camera = _dereq_('./camera'), LngLat = _dereq_('../geo/lng_lat'), LngLatBounds = _dereq_('../geo/lng_lat_bounds'), Point = _dereq_('@mapbox/point-geometry'), AttributionControl = _dereq_('./control/attribution_control'), LogoControl = _dereq_('./control/logo_control'), isSupported = _dereq_('@mapbox/mapbox-gl-supported'), ref$1 = _dereq_('../util/image'), RGBAImage = ref$1.RGBAImage;
                _dereq_('./events');
                var defaultMinZoom = 0, defaultMaxZoom = 22, defaultOptions = {
                        center: [
                            0,
                            0
                        ],
                        zoom: 0,
                        bearing: 0,
                        pitch: 0,
                        minZoom: defaultMinZoom,
                        maxZoom: defaultMaxZoom,
                        interactive: !0,
                        scrollZoom: !0,
                        boxZoom: !0,
                        dragRotate: !0,
                        dragPan: !0,
                        keyboard: !0,
                        doubleClickZoom: !0,
                        touchZoomRotate: !0,
                        bearingSnap: 7,
                        hash: !1,
                        attributionControl: !0,
                        failIfMajorPerformanceCaveat: !1,
                        preserveDrawingBuffer: !1,
                        trackResize: !0,
                        renderWorldCopies: !0,
                        refreshExpiredTiles: !0,
                        maxTileCacheSize: null,
                        transformRequest: null,
                        fadeDuration: 300
                    }, Map = function (t) {
                        function e(e) {
                            if (e = util.extend({}, defaultOptions, e), null != e.minZoom && null != e.maxZoom && e.minZoom > e.maxZoom) {
                                throw new Error('maxZoom must be greater than minZoom');
                            }
                            var r = new Transform(e.minZoom, e.maxZoom, e.renderWorldCopies);
                            t.call(this, r, e), this._interactive = e.interactive, this._maxTileCacheSize = e.maxTileCacheSize, this._failIfMajorPerformanceCaveat = e.failIfMajorPerformanceCaveat, this._preserveDrawingBuffer = e.preserveDrawingBuffer, this._trackResize = e.trackResize, this._bearingSnap = e.bearingSnap, this._refreshExpiredTiles = e.refreshExpiredTiles, this._fadeDuration = e.fadeDuration, this._crossFadingFactor = 1, this._collectResourceTiming = e.collectResourceTiming;
                            var o = e.transformRequest;
                            if (this._transformRequest = o ? function (t, e) {
                                    return o(t, e) || { url: t };
                                } : function (t) {
                                    return { url: t };
                                }, 'string' == typeof e.container) {
                                var i = window.document.getElementById(e.container);
                                if (!i) {
                                    throw new Error('Container \'' + e.container + '\' not found.');
                                }
                                this._container = i;
                            } else {
                                if (!(e.container instanceof HTMLElement)) {
                                    throw new Error('Invalid type: \'container\' must be a String or HTMLElement.');
                                }
                                this._container = e.container;
                            }
                            e.maxBounds && this.setMaxBounds(e.maxBounds), util.bindAll([
                                '_onWindowOnline',
                                '_onWindowResize',
                                '_contextLost',
                                '_contextRestored',
                                '_update',
                                '_render',
                                '_onData',
                                '_onDataLoading'
                            ], this), this._setupContainer(), this._setupPainter(), this.on('move', this._update.bind(this, !1)), this.on('zoom', this._update.bind(this, !0)), void 0 !== window && (window.addEventListener('online', this._onWindowOnline, !1), window.addEventListener('resize', this._onWindowResize, !1)), bindHandlers(this, e), this._hash = e.hash && new Hash().addTo(this), this._hash && this._hash._onHashChange() || this.jumpTo({
                                center: e.center,
                                zoom: e.zoom,
                                bearing: e.bearing,
                                pitch: e.pitch
                            }), this.resize(), e.style && this.setStyle(e.style, { localIdeographFontFamily: e.localIdeographFontFamily }), e.attributionControl && this.addControl(new AttributionControl()), this.addControl(new LogoControl(), e.logoPosition), this.on('style.load', function () {
                                this.transform.unmodified && this.jumpTo(this.style.stylesheet);
                            }), this.on('data', this._onData), this.on('dataloading', this._onDataLoading);
                        }
                        t && (e.__proto__ = t), e.prototype = Object.create(t && t.prototype), e.prototype.constructor = e;
                        var r = {
                            showTileBoundaries: {},
                            showCollisionBoxes: {},
                            showOverdrawInspector: {},
                            repaint: {},
                            vertices: {}
                        };
                        return e.prototype.addControl = function (t, e) {
                            void 0 === e && t.getDefaultPosition && (e = t.getDefaultPosition()), void 0 === e && (e = 'top-right');
                            var r = t.onAdd(this), o = this._controlPositions[e];
                            return -1 !== e.indexOf('bottom') ? o.insertBefore(r, o.firstChild) : o.appendChild(r), this;
                        }, e.prototype.removeControl = function (t) {
                            return t.onRemove(this), this;
                        }, e.prototype.resize = function () {
                            var t = this._containerDimensions(), e = t[0], r = t[1];
                            return this._resizeCanvas(e, r), this.transform.resize(e, r), this.painter.resize(e, r), this.fire('movestart').fire('move').fire('resize').fire('moveend');
                        }, e.prototype.getBounds = function () {
                            var t = new LngLatBounds(this.transform.pointLocation(new Point(0, this.transform.height)), this.transform.pointLocation(new Point(this.transform.width, 0)));
                            return (this.transform.angle || this.transform.pitch) && (t.extend(this.transform.pointLocation(new Point(this.transform.size.x, 0))), t.extend(this.transform.pointLocation(new Point(0, this.transform.size.y)))), t;
                        }, e.prototype.getMaxBounds = function () {
                            return this.transform.latRange && 2 === this.transform.latRange.length && this.transform.lngRange && 2 === this.transform.lngRange.length ? new LngLatBounds([
                                this.transform.lngRange[0],
                                this.transform.latRange[0]
                            ], [
                                this.transform.lngRange[1],
                                this.transform.latRange[1]
                            ]) : null;
                        }, e.prototype.setMaxBounds = function (t) {
                            if (t) {
                                var e = LngLatBounds.convert(t);
                                this.transform.lngRange = [
                                    e.getWest(),
                                    e.getEast()
                                ], this.transform.latRange = [
                                    e.getSouth(),
                                    e.getNorth()
                                ], this.transform._constrain(), this._update();
                            } else {
                                null !== t && void 0 !== t || (this.transform.lngRange = null, this.transform.latRange = null, this._update());
                            }
                            return this;
                        }, e.prototype.setMinZoom = function (t) {
                            if ((t = null === t || void 0 === t ? defaultMinZoom : t) >= defaultMinZoom && t <= this.transform.maxZoom) {
                                return this.transform.minZoom = t, this._update(), this.getZoom() < t && this.setZoom(t), this;
                            }
                            throw new Error('minZoom must be between ' + defaultMinZoom + ' and the current maxZoom, inclusive');
                        }, e.prototype.getMinZoom = function () {
                            return this.transform.minZoom;
                        }, e.prototype.setMaxZoom = function (t) {
                            if ((t = null === t || void 0 === t ? defaultMaxZoom : t) >= this.transform.minZoom) {
                                return this.transform.maxZoom = t, this._update(), this.getZoom() > t && this.setZoom(t), this;
                            }
                            throw new Error('maxZoom must be greater than the current minZoom');
                        }, e.prototype.getMaxZoom = function () {
                            return this.transform.maxZoom;
                        }, e.prototype.project = function (t) {
                            return this.transform.locationPoint(LngLat.convert(t));
                        }, e.prototype.unproject = function (t) {
                            return this.transform.pointLocation(Point.convert(t));
                        }, e.prototype.on = function (e, r, o) {
                            var i = this;
                            if (void 0 === o) {
                                return t.prototype.on.call(this, e, r);
                            }
                            var n = function () {
                                if ('mouseenter' === e || 'mouseover' === e) {
                                    var t = !1;
                                    return {
                                        layer: r,
                                        listener: o,
                                        delegates: {
                                            mousemove: function (n) {
                                                var s = i.getLayer(r) ? i.queryRenderedFeatures(n.point, { layers: [r] }) : [];
                                                s.length ? t || (t = !0, o.call(i, util.extend({ features: s }, n, { type: e }))) : t = !1;
                                            },
                                            mouseout: function () {
                                                t = !1;
                                            }
                                        }
                                    };
                                }
                                if ('mouseleave' === e || 'mouseout' === e) {
                                    var n = !1;
                                    return {
                                        layer: r,
                                        listener: o,
                                        delegates: {
                                            mousemove: function (t) {
                                                (i.getLayer(r) ? i.queryRenderedFeatures(t.point, { layers: [r] }) : []).length ? n = !0 : n && (n = !1, o.call(i, util.extend({}, t, { type: e })));
                                            },
                                            mouseout: function (t) {
                                                n && (n = !1, o.call(i, util.extend({}, t, { type: e })));
                                            }
                                        }
                                    };
                                }
                                var s = function (t) {
                                    var e = i.getLayer(r) ? i.queryRenderedFeatures(t.point, { layers: [r] }) : [];
                                    e.length && o.call(i, util.extend({ features: e }, t));
                                };
                                return {
                                    layer: r,
                                    listener: o,
                                    delegates: (a = {}, a[e] = s, a)
                                };
                                var a;
                            }();
                            this._delegatedListeners = this._delegatedListeners || {}, this._delegatedListeners[e] = this._delegatedListeners[e] || [], this._delegatedListeners[e].push(n);
                            for (var s in n.delegates) {
                                i.on(s, n.delegates[s]);
                            }
                            return this;
                        }, e.prototype.off = function (e, r, o) {
                            var i = this;
                            if (void 0 === o) {
                                return t.prototype.off.call(this, e, r);
                            }
                            if (this._delegatedListeners && this._delegatedListeners[e]) {
                                for (var n = this._delegatedListeners[e], s = 0; s < n.length; s++) {
                                    var a = n[s];
                                    if (a.layer === r && a.listener === o) {
                                        for (var h in a.delegates) {
                                            i.off(h, a.delegates[h]);
                                        }
                                        return n.splice(s, 1), i;
                                    }
                                }
                            }
                            return this;
                        }, e.prototype.queryRenderedFeatures = function (t, e) {
                            return 2 === arguments.length ? (t = arguments[0], e = arguments[1]) : 1 === arguments.length && function (t) {
                                return t instanceof Point || Array.isArray(t);
                            }(arguments[0]) ? (t = arguments[0], e = {}) : 1 === arguments.length ? (t = void 0, e = arguments[0]) : (t = void 0, e = {}), this.style ? this.style.queryRenderedFeatures(this._makeQueryGeometry(t), e, this.transform.zoom, this.transform.angle) : [];
                        }, e.prototype._makeQueryGeometry = function (t) {
                            var e = this;
                            void 0 === t && (t = [
                                Point.convert([
                                    0,
                                    0
                                ]),
                                Point.convert([
                                    this.transform.width,
                                    this.transform.height
                                ])
                            ]);
                            var r;
                            if (t instanceof Point || 'number' == typeof t[0]) {
                                r = [Point.convert(t)];
                            } else {
                                var o = [
                                    Point.convert(t[0]),
                                    Point.convert(t[1])
                                ];
                                r = [
                                    o[0],
                                    new Point(o[1].x, o[0].y),
                                    o[1],
                                    new Point(o[0].x, o[1].y),
                                    o[0]
                                ];
                            }
                            return r = r.map(function (t) {
                                return e.transform.pointCoordinate(t);
                            });
                        }, e.prototype.querySourceFeatures = function (t, e) {
                            return this.style.querySourceFeatures(t, e);
                        }, e.prototype.setStyle = function (t, e) {
                            if ((!e || !1 !== e.diff && !e.localIdeographFontFamily) && this.style && t && 'object' == typeof t) {
                                try {
                                    return this.style.setState(t) && this._update(!0), this;
                                } catch (t) {
                                    util.warnOnce('Unable to perform style diff: ' + (t.message || t.error || t) + '.  Rebuilding the style from scratch.');
                                }
                            }
                            return this.style && (this.style.setEventedParent(null), this.style._remove()), t ? (this.style = new Style(this, e || {}), this.style.setEventedParent(this, { style: this.style }), 'string' == typeof t ? this.style.loadURL(t) : this.style.loadJSON(t), this) : (delete this.style, this);
                        }, e.prototype.getStyle = function () {
                            if (this.style) {
                                return this.style.serialize();
                            }
                        }, e.prototype.isStyleLoaded = function () {
                            return this.style ? this.style.loaded() : util.warnOnce('There is no style added to the map.');
                        }, e.prototype.addSource = function (t, e) {
                            return this.style.addSource(t, e), this._update(!0), this;
                        }, e.prototype.isSourceLoaded = function (t) {
                            var e = this.style && this.style.sourceCaches[t];
                            return void 0 === e ? void this.fire('error', { error: new Error('There is no source with ID \'' + t + '\'') }) : e.loaded();
                        }, e.prototype.areTilesLoaded = function () {
                            var t = this.style && this.style.sourceCaches;
                            for (var e in t) {
                                var r = t[e], o = r._tiles;
                                for (var i in o) {
                                    var n = o[i];
                                    if ('loaded' !== n.state && 'errored' !== n.state) {
                                        return !1;
                                    }
                                }
                            }
                            return !0;
                        }, e.prototype.addSourceType = function (t, e, r) {
                            return this.style.addSourceType(t, e, r);
                        }, e.prototype.removeSource = function (t) {
                            return this.style.removeSource(t), this._update(!0), this;
                        }, e.prototype.getSource = function (t) {
                            return this.style.getSource(t);
                        }, e.prototype.addImage = function (t, e, r) {
                            void 0 === r && (r = {});
                            var o = r.pixelRatio;
                            void 0 === o && (o = 1);
                            var i = r.sdf;
                            if (void 0 === i && (i = !1), e instanceof HTMLImageElement) {
                                var n = browser.getImageData(e), s = n.width, a = n.height, h = n.data;
                                this.style.addImage(t, {
                                    data: new RGBAImage({
                                        width: s,
                                        height: a
                                    }, h),
                                    pixelRatio: o,
                                    sdf: i
                                });
                            } else {
                                if (void 0 === e.width || void 0 === e.height) {
                                    return this.fire('error', { error: new Error('Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`') });
                                }
                                var l = e.width, u = e.height, d = e.data;
                                this.style.addImage(t, {
                                    data: new RGBAImage({
                                        width: l,
                                        height: u
                                    }, d.slice(0)),
                                    pixelRatio: o,
                                    sdf: i
                                });
                            }
                        }, e.prototype.hasImage = function (t) {
                            return t ? !!this.style.getImage(t) : (this.fire('error', { error: new Error('Missing required image id') }), !1);
                        }, e.prototype.removeImage = function (t) {
                            this.style.removeImage(t);
                        }, e.prototype.loadImage = function (t, e) {
                            ajax.getImage(this._transformRequest(t, ajax.ResourceType.Image), e);
                        }, e.prototype.addLayer = function (t, e) {
                            return this.style.addLayer(t, e), this._update(!0), this;
                        }, e.prototype.moveLayer = function (t, e) {
                            return this.style.moveLayer(t, e), this._update(!0), this;
                        }, e.prototype.removeLayer = function (t) {
                            return this.style.removeLayer(t), this._update(!0), this;
                        }, e.prototype.getLayer = function (t) {
                            return this.style.getLayer(t);
                        }, e.prototype.setFilter = function (t, e) {
                            return this.style.setFilter(t, e), this._update(!0), this;
                        }, e.prototype.setLayerZoomRange = function (t, e, r) {
                            return this.style.setLayerZoomRange(t, e, r), this._update(!0), this;
                        }, e.prototype.getFilter = function (t) {
                            return this.style.getFilter(t);
                        }, e.prototype.setPaintProperty = function (t, e, r) {
                            return this.style.setPaintProperty(t, e, r), this._update(!0), this;
                        }, e.prototype.getPaintProperty = function (t, e) {
                            return this.style.getPaintProperty(t, e);
                        }, e.prototype.setLayoutProperty = function (t, e, r) {
                            return this.style.setLayoutProperty(t, e, r), this._update(!0), this;
                        }, e.prototype.getLayoutProperty = function (t, e) {
                            return this.style.getLayoutProperty(t, e);
                        }, e.prototype.setLight = function (t) {
                            return this.style.setLight(t), this._update(!0), this;
                        }, e.prototype.getLight = function () {
                            return this.style.getLight();
                        }, e.prototype.getContainer = function () {
                            return this._container;
                        }, e.prototype.getCanvasContainer = function () {
                            return this._canvasContainer;
                        }, e.prototype.getCanvas = function () {
                            return this._canvas;
                        }, e.prototype._containerDimensions = function () {
                            var t = 0, e = 0;
                            return this._container && (t = this._container.offsetWidth || 400, e = this._container.offsetHeight || 300), [
                                t,
                                e
                            ];
                        }, e.prototype._setupContainer = function () {
                            var t = this._container;
                            t.classList.add('mapboxgl-map'), (this._missingCSSContainer = DOM.create('div', 'mapboxgl-missing-css', t)).innerHTML = 'Missing Mapbox GL JS CSS';
                            var e = this._canvasContainer = DOM.create('div', 'mapboxgl-canvas-container', t);
                            this._interactive && e.classList.add('mapboxgl-interactive'), this._canvas = DOM.create('canvas', 'mapboxgl-canvas', e), this._canvas.style.position = 'absolute', this._canvas.addEventListener('webglcontextlost', this._contextLost, !1), this._canvas.addEventListener('webglcontextrestored', this._contextRestored, !1), this._canvas.setAttribute('tabindex', '0'), this._canvas.setAttribute('aria-label', 'Map');
                            var r = this._containerDimensions();
                            this._resizeCanvas(r[0], r[1]);
                            var o = this._controlContainer = DOM.create('div', 'mapboxgl-control-container', t), i = this._controlPositions = {};
                            [
                                'top-left',
                                'top-right',
                                'bottom-left',
                                'bottom-right'
                            ].forEach(function (t) {
                                i[t] = DOM.create('div', 'mapboxgl-ctrl-' + t, o);
                            });
                        }, e.prototype._resizeCanvas = function (t, e) {
                            var r = window.devicePixelRatio || 1;
                            this._canvas.width = r * t, this._canvas.height = r * e, this._canvas.style.width = t + 'px', this._canvas.style.height = e + 'px';
                        }, e.prototype._setupPainter = function () {
                            var t = util.extend({
                                    failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,
                                    preserveDrawingBuffer: this._preserveDrawingBuffer
                                }, isSupported.webGLContextAttributes), e = this._canvas.getContext('webgl', t) || this._canvas.getContext('experimental-webgl', t);
                            if (!e) {
                                return void this.fire('error', { error: new Error('Failed to initialize WebGL') });
                            }
                            this.painter = new Painter(e, this.transform);
                        }, e.prototype._contextLost = function (t) {
                            t.preventDefault(), this._frameId && (browser.cancelFrame(this._frameId), this._frameId = null), this.fire('webglcontextlost', { originalEvent: t });
                        }, e.prototype._contextRestored = function (t) {
                            this._setupPainter(), this.resize(), this._update(), this.fire('webglcontextrestored', { originalEvent: t });
                        }, e.prototype.loaded = function () {
                            return !this._styleDirty && !this._sourcesDirty && !(!this.style || !this.style.loaded());
                        }, e.prototype._update = function (t) {
                            this.style && (this._styleDirty = this._styleDirty || t, this._sourcesDirty = !0, this._rerender());
                        }, e.prototype._render = function () {
                            this._updateCamera();
                            var t = !1;
                            if (this.style && this._styleDirty) {
                                this._styleDirty = !1;
                                var e = this.transform.zoom, r = browser.now();
                                this.style.zoomHistory.update(e, r);
                                var o = new EvaluationParameters(e, {
                                        now: r,
                                        fadeDuration: this._fadeDuration,
                                        zoomHistory: this.style.zoomHistory,
                                        transition: this.style.getTransition()
                                    }), i = o.crossFadingFactor();
                                1 === i && i === this._crossFadingFactor || (t = !0, this._crossFadingFactor = i), this.style.update(o);
                            }
                            return this.style && this._sourcesDirty && (this._sourcesDirty = !1, this.style._updateSources(this.transform)), this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._fadeDuration), this.painter.render(this.style, {
                                showTileBoundaries: this.showTileBoundaries,
                                showOverdrawInspector: this._showOverdrawInspector,
                                rotating: this.rotating,
                                zooming: this.zooming,
                                fadeDuration: this._fadeDuration
                            }), this.fire('render'), this.loaded() && !this._loaded && (this._loaded = !0, this.fire('load')), this.style && (this.style.hasTransitions() || t) && (this._styleDirty = !0), (this._sourcesDirty || this._repaint || this._styleDirty || this._placementDirty) && this._rerender(), this;
                        }, e.prototype.remove = function () {
                            this._hash && this._hash.remove(), browser.cancelFrame(this._frameId), this._frameId = null, this.setStyle(null), void 0 !== window && (window.removeEventListener('resize', this._onWindowResize, !1), window.removeEventListener('online', this._onWindowOnline, !1));
                            var t = this.painter.context.gl.getExtension('WEBGL_lose_context');
                            t && t.loseContext(), removeNode(this._canvasContainer), removeNode(this._controlContainer), removeNode(this._missingCSSContainer), this._container.classList.remove('mapboxgl-map'), this.fire('remove');
                        }, e.prototype._rerender = function () {
                            var t = this;
                            this.style && !this._frameId && (this._frameId = browser.frame(function () {
                                t._frameId = null, t._render();
                            }));
                        }, e.prototype._onWindowOnline = function () {
                            this._update();
                        }, e.prototype._onWindowResize = function () {
                            this._trackResize && this.stop().resize()._update();
                        }, r.showTileBoundaries.get = function () {
                            return !!this._showTileBoundaries;
                        }, r.showTileBoundaries.set = function (t) {
                            this._showTileBoundaries !== t && (this._showTileBoundaries = t, this._update());
                        }, r.showCollisionBoxes.get = function () {
                            return !!this._showCollisionBoxes;
                        }, r.showCollisionBoxes.set = function (t) {
                            this._showCollisionBoxes !== t && (this._showCollisionBoxes = t, t ? this.style._generateCollisionBoxes() : this._update());
                        }, r.showOverdrawInspector.get = function () {
                            return !!this._showOverdrawInspector;
                        }, r.showOverdrawInspector.set = function (t) {
                            this._showOverdrawInspector !== t && (this._showOverdrawInspector = t, this._update());
                        }, r.repaint.get = function () {
                            return !!this._repaint;
                        }, r.repaint.set = function (t) {
                            this._repaint = t, this._update();
                        }, r.vertices.get = function () {
                            return !!this._vertices;
                        }, r.vertices.set = function (t) {
                            this._vertices = t, this._update();
                        }, e.prototype._onData = function (t) {
                            this._update('style' === t.dataType), this.fire(t.dataType + 'data', t);
                        }, e.prototype._onDataLoading = function (t) {
                            this.fire(t.dataType + 'dataloading', t);
                        }, Object.defineProperties(e.prototype, r), e;
                    }(Camera);
                module.exports = Map;
            },
            {
                '../geo/lng_lat': 62,
                '../geo/lng_lat_bounds': 63,
                '../geo/transform': 64,
                '../render/painter': 90,
                '../style/evaluation_parameters': 182,
                '../style/style': 190,
                '../util/ajax': 251,
                '../util/browser': 252,
                '../util/dom': 259,
                '../util/image': 263,
                '../util/util': 275,
                '../util/window': 254,
                './bind_handlers': 230,
                './camera': 231,
                './control/attribution_control': 232,
                './control/logo_control': 235,
                './events': 238,
                './hash': 246,
                '@mapbox/mapbox-gl-supported': 3,
                '@mapbox/point-geometry': 4
            }
        ],
        248: [
            function (_dereq_, module, exports) {
                'use strict';
                var DOM = _dereq_('../util/dom'), LngLat = _dereq_('../geo/lng_lat'), Point = _dereq_('@mapbox/point-geometry'), smartWrap = _dereq_('../util/smart_wrap'), ref = _dereq_('../util/util'), bindAll = ref.bindAll, Marker = function (t, e) {
                        if (bindAll([
                                '_update',
                                '_onMapClick'
                            ], this), !t) {
                            t = DOM.create('div');
                            var r = DOM.createNS('http://www.w3.org/2000/svg', 'svg');
                            r.setAttributeNS(null, 'height', '41px'), r.setAttributeNS(null, 'width', '27px'), r.setAttributeNS(null, 'viewBox', '0 0 27 41');
                            var i = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            i.setAttributeNS(null, 'stroke', 'none'), i.setAttributeNS(null, 'stroke-width', '1'), i.setAttributeNS(null, 'fill', 'none'), i.setAttributeNS(null, 'fill-rule', 'evenodd');
                            var s = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            s.setAttributeNS(null, 'fill-rule', 'nonzero');
                            var p = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            p.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)'), p.setAttributeNS(null, 'fill', '#000000');
                            for (var n = [
                                        {
                                            rx: '10.5',
                                            ry: '5.25002273'
                                        },
                                        {
                                            rx: '10.5',
                                            ry: '5.25002273'
                                        },
                                        {
                                            rx: '9.5',
                                            ry: '4.77275007'
                                        },
                                        {
                                            rx: '8.5',
                                            ry: '4.29549936'
                                        },
                                        {
                                            rx: '7.5',
                                            ry: '3.81822308'
                                        },
                                        {
                                            rx: '6.5',
                                            ry: '3.34094679'
                                        },
                                        {
                                            rx: '5.5',
                                            ry: '2.86367051'
                                        },
                                        {
                                            rx: '4.5',
                                            ry: '2.38636864'
                                        }
                                    ], l = 0, o = n; l < o.length; l += 1) {
                                var a = o[l], u = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse');
                                u.setAttributeNS(null, 'opacity', '0.04'), u.setAttributeNS(null, 'cx', '10.5'), u.setAttributeNS(null, 'cy', '5.80029008'), u.setAttributeNS(null, 'rx', a.rx), u.setAttributeNS(null, 'ry', a.ry), p.appendChild(u);
                            }
                            var h = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            h.setAttributeNS(null, 'fill', '#3FB1CE');
                            var _ = DOM.createNS('http://www.w3.org/2000/svg', 'path');
                            _.setAttributeNS(null, 'd', 'M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z'), h.appendChild(_);
                            var g = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            g.setAttributeNS(null, 'opacity', '0.25'), g.setAttributeNS(null, 'fill', '#000000');
                            var f = DOM.createNS('http://www.w3.org/2000/svg', 'path');
                            f.setAttributeNS(null, 'd', 'M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z'), g.appendChild(f);
                            var d = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            d.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)'), d.setAttributeNS(null, 'fill', '#FFFFFF');
                            var w = DOM.createNS('http://www.w3.org/2000/svg', 'g');
                            w.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)');
                            var c = DOM.createNS('http://www.w3.org/2000/svg', 'circle');
                            c.setAttributeNS(null, 'fill', '#000000'), c.setAttributeNS(null, 'opacity', '0.25'), c.setAttributeNS(null, 'cx', '5.5'), c.setAttributeNS(null, 'cy', '5.5'), c.setAttributeNS(null, 'r', '5.4999962');
                            var v = DOM.createNS('http://www.w3.org/2000/svg', 'circle');
                            v.setAttributeNS(null, 'fill', '#FFFFFF'), v.setAttributeNS(null, 'cx', '5.5'), v.setAttributeNS(null, 'cy', '5.5'), v.setAttributeNS(null, 'r', '5.4999962'), w.appendChild(c), w.appendChild(v), s.appendChild(p), s.appendChild(h), s.appendChild(g), s.appendChild(d), s.appendChild(w), r.appendChild(s), t.appendChild(r);
                            var m = [
                                0,
                                -14
                            ];
                            e && e.offset || (e ? e.offset = m : e = { offset: m });
                        }
                        this._offset = Point.convert(e && e.offset || [
                            0,
                            0
                        ]), t.classList.add('mapboxgl-marker'), this._element = t, this._popup = null;
                    };
                Marker.prototype.addTo = function (t) {
                    return this.remove(), this._map = t, t.getCanvasContainer().appendChild(this._element), t.on('move', this._update), t.on('moveend', this._update), this._update(), this._map.on('click', this._onMapClick), this;
                }, Marker.prototype.remove = function () {
                    return this._map && (this._map.off('click', this._onMapClick), this._map.off('move', this._update), this._map.off('moveend', this._update), delete this._map), DOM.remove(this._element), this._popup && this._popup.remove(), this;
                }, Marker.prototype.getLngLat = function () {
                    return this._lngLat;
                }, Marker.prototype.setLngLat = function (t) {
                    return this._lngLat = LngLat.convert(t), this._pos = null, this._popup && this._popup.setLngLat(this._lngLat), this._update(), this;
                }, Marker.prototype.getElement = function () {
                    return this._element;
                }, Marker.prototype.setPopup = function (t) {
                    return this._popup && (this._popup.remove(), this._popup = null), t && ('offset' in t.options || (t.options.offset = this._offset), this._popup = t, this._lngLat && this._popup.setLngLat(this._lngLat)), this;
                }, Marker.prototype._onMapClick = function (t) {
                    var e = t.originalEvent.target, r = this._element;
                    this._popup && (e === r || r.contains(e)) && this.togglePopup();
                }, Marker.prototype.getPopup = function () {
                    return this._popup;
                }, Marker.prototype.togglePopup = function () {
                    var t = this._popup;
                    return t ? (t.isOpen() ? t.remove() : t.addTo(this._map), this) : this;
                }, Marker.prototype._update = function (t) {
                    this._map && (this._map.transform.renderWorldCopies && (this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform)), this._pos = this._map.project(this._lngLat)._add(this._offset), t && 'moveend' !== t.type || (this._pos = this._pos.round()), DOM.setTransform(this._element, 'translate(-50%, -50%) translate(' + this._pos.x + 'px, ' + this._pos.y + 'px)'));
                }, Marker.prototype.getOffset = function () {
                    return this._offset;
                }, Marker.prototype.setOffset = function (t) {
                    return this._offset = Point.convert(t), this._update(), this;
                }, module.exports = Marker;
            },
            {
                '../geo/lng_lat': 62,
                '../util/dom': 259,
                '../util/smart_wrap': 270,
                '../util/util': 275,
                '@mapbox/point-geometry': 4
            }
        ],
        249: [
            function (_dereq_, module, exports) {
                'use strict';
                function normalizeOffset(t) {
                    if (t) {
                        if ('number' == typeof t) {
                            var o = Math.round(Math.sqrt(0.5 * Math.pow(t, 2)));
                            return {
                                top: new Point(0, t),
                                'top-left': new Point(o, o),
                                'top-right': new Point(-o, o),
                                bottom: new Point(0, -t),
                                'bottom-left': new Point(o, -o),
                                'bottom-right': new Point(-o, -o),
                                left: new Point(t, 0),
                                right: new Point(-t, 0)
                            };
                        }
                        if (t instanceof Point || Array.isArray(t)) {
                            var e = Point.convert(t);
                            return {
                                top: e,
                                'top-left': e,
                                'top-right': e,
                                bottom: e,
                                'bottom-left': e,
                                'bottom-right': e,
                                left: e,
                                right: e
                            };
                        }
                        return {
                            top: Point.convert(t.top || [
                                0,
                                0
                            ]),
                            'top-left': Point.convert(t['top-left'] || [
                                0,
                                0
                            ]),
                            'top-right': Point.convert(t['top-right'] || [
                                0,
                                0
                            ]),
                            bottom: Point.convert(t.bottom || [
                                0,
                                0
                            ]),
                            'bottom-left': Point.convert(t['bottom-left'] || [
                                0,
                                0
                            ]),
                            'bottom-right': Point.convert(t['bottom-right'] || [
                                0,
                                0
                            ]),
                            left: Point.convert(t.left || [
                                0,
                                0
                            ]),
                            right: Point.convert(t.right || [
                                0,
                                0
                            ])
                        };
                    }
                    return normalizeOffset(new Point(0, 0));
                }
                var util = _dereq_('../util/util'), Evented = _dereq_('../util/evented'), DOM = _dereq_('../util/dom'), LngLat = _dereq_('../geo/lng_lat'), Point = _dereq_('@mapbox/point-geometry'), window = _dereq_('../util/window'), smartWrap = _dereq_('../util/smart_wrap'), defaultOptions = {
                        closeButton: !0,
                        closeOnClick: !0
                    }, Popup = function (t) {
                        function o(o) {
                            t.call(this), this.options = util.extend(Object.create(defaultOptions), o), util.bindAll([
                                '_update',
                                '_onClickClose'
                            ], this);
                        }
                        return t && (o.__proto__ = t), o.prototype = Object.create(t && t.prototype), o.prototype.constructor = o, o.prototype.addTo = function (t) {
                            return this._map = t, this._map.on('move', this._update), this.options.closeOnClick && this._map.on('click', this._onClickClose), this._update(), this;
                        }, o.prototype.isOpen = function () {
                            return !!this._map;
                        }, o.prototype.remove = function () {
                            return this._content && DOM.remove(this._content), this._container && (DOM.remove(this._container), delete this._container), this._map && (this._map.off('move', this._update), this._map.off('click', this._onClickClose), delete this._map), this.fire('close'), this;
                        }, o.prototype.getLngLat = function () {
                            return this._lngLat;
                        }, o.prototype.setLngLat = function (t) {
                            return this._lngLat = LngLat.convert(t), this._pos = null, this._update(), this;
                        }, o.prototype.setText = function (t) {
                            return this.setDOMContent(window.document.createTextNode(t));
                        }, o.prototype.setHTML = function (t) {
                            var o, e = window.document.createDocumentFragment(), n = window.document.createElement('body');
                            for (n.innerHTML = t;;) {
                                if (!(o = n.firstChild)) {
                                    break;
                                }
                                e.appendChild(o);
                            }
                            return this.setDOMContent(e);
                        }, o.prototype.setDOMContent = function (t) {
                            return this._createContent(), this._content.appendChild(t), this._update(), this;
                        }, o.prototype._createContent = function () {
                            this._content && DOM.remove(this._content), this._content = DOM.create('div', 'mapboxgl-popup-content', this._container), this.options.closeButton && (this._closeButton = DOM.create('button', 'mapboxgl-popup-close-button', this._content), this._closeButton.type = 'button', this._closeButton.setAttribute('aria-label', 'Close popup'), this._closeButton.innerHTML = '&#215;', this._closeButton.addEventListener('click', this._onClickClose));
                        }, o.prototype._update = function () {
                            if (this._map && this._lngLat && this._content) {
                                this._container || (this._container = DOM.create('div', 'mapboxgl-popup', this._map.getContainer()), this._tip = DOM.create('div', 'mapboxgl-popup-tip', this._container), this._container.appendChild(this._content)), this._map.transform.renderWorldCopies && (this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform));
                                var t = this._pos = this._map.project(this._lngLat), o = this.options.anchor, e = normalizeOffset(this.options.offset);
                                if (!o) {
                                    var n = this._container.offsetWidth, i = this._container.offsetHeight;
                                    o = t.y + e.bottom.y < i ? ['top'] : t.y > this._map.transform.height - i ? ['bottom'] : [], t.x < n / 2 ? o.push('left') : t.x > this._map.transform.width - n / 2 && o.push('right'), o = 0 === o.length ? 'bottom' : o.join('-');
                                }
                                var r = t.add(e[o]).round(), s = {
                                        top: 'translate(-50%,0)',
                                        'top-left': 'translate(0,0)',
                                        'top-right': 'translate(-100%,0)',
                                        bottom: 'translate(-50%,-100%)',
                                        'bottom-left': 'translate(0,-100%)',
                                        'bottom-right': 'translate(-100%,-100%)',
                                        left: 'translate(0,-50%)',
                                        right: 'translate(-100%,-50%)'
                                    }, p = this._container.classList;
                                for (var a in s) {
                                    p.remove('mapboxgl-popup-anchor-' + a);
                                }
                                p.add('mapboxgl-popup-anchor-' + o), DOM.setTransform(this._container, s[o] + ' translate(' + r.x + 'px,' + r.y + 'px)');
                            }
                        }, o.prototype._onClickClose = function () {
                            this.remove();
                        }, o;
                    }(Evented);
                module.exports = Popup;
            },
            {
                '../geo/lng_lat': 62,
                '../util/dom': 259,
                '../util/evented': 260,
                '../util/smart_wrap': 270,
                '../util/util': 275,
                '../util/window': 254,
                '@mapbox/point-geometry': 4
            }
        ],
        250: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('./util'), ref = _dereq_('./web_worker_transfer'), serialize = ref.serialize, deserialize = ref.deserialize, Actor = function (e, t, r) {
                        this.target = e, this.parent = t, this.mapId = r, this.callbacks = {}, this.callbackID = 0, util.bindAll(['receive'], this), this.target.addEventListener('message', this.receive, !1);
                    };
                Actor.prototype.send = function (e, t, r, i) {
                    var a = r ? this.mapId + ':' + this.callbackID++ : null;
                    r && (this.callbacks[a] = r);
                    var s = [];
                    this.target.postMessage({
                        targetMapId: i,
                        sourceMapId: this.mapId,
                        type: e,
                        id: String(a),
                        data: serialize(t, s)
                    }, s);
                }, Actor.prototype.receive = function (e) {
                    var t, r = this, i = e.data, a = i.id;
                    if (!i.targetMapId || this.mapId === i.targetMapId) {
                        var s = function (e, t) {
                            var i = [];
                            r.target.postMessage({
                                sourceMapId: r.mapId,
                                type: '<response>',
                                id: String(a),
                                error: e ? String(e) : null,
                                data: serialize(t, i)
                            }, i);
                        };
                        if ('<response>' === i.type) {
                            t = this.callbacks[i.id], delete this.callbacks[i.id], t && i.error ? t(new Error(i.error)) : t && t(null, deserialize(i.data));
                        } else if (void 0 !== i.id && this.parent[i.type]) {
                            this.parent[i.type](i.sourceMapId, deserialize(i.data), s);
                        } else if (void 0 !== i.id && this.parent.getWorkerSource) {
                            var d = i.type.split('.'), l = this.parent.getWorkerSource(i.sourceMapId, d[0]);
                            l[d[1]](deserialize(i.data), s);
                        } else {
                            this.parent[i.type](deserialize(i.data));
                        }
                    }
                }, Actor.prototype.remove = function () {
                    this.target.removeEventListener('message', this.receive, !1);
                }, module.exports = Actor;
            },
            {
                './util': 275,
                './web_worker_transfer': 278
            }
        ],
        251: [
            function (_dereq_, module, exports) {
                'use strict';
                function makeRequest(e) {
                    var t = new window.XMLHttpRequest();
                    t.open('GET', e.url, !0);
                    for (var r in e.headers) {
                        t.setRequestHeader(r, e.headers[r]);
                    }
                    return t.withCredentials = 'include' === e.credentials, t;
                }
                function sameOrigin(e) {
                    var t = window.document.createElement('a');
                    return t.href = e, t.protocol === window.document.location.protocol && t.host === window.document.location.host;
                }
                var window = _dereq_('./window'), ResourceType = {
                        Unknown: 'Unknown',
                        Style: 'Style',
                        Source: 'Source',
                        Tile: 'Tile',
                        Glyphs: 'Glyphs',
                        SpriteImage: 'SpriteImage',
                        SpriteJSON: 'SpriteJSON',
                        Image: 'Image'
                    };
                exports.ResourceType = ResourceType, 'function' == typeof Object.freeze && Object.freeze(ResourceType);
                var AJAXError = function (e) {
                    function t(t, r) {
                        e.call(this, t), this.status = r;
                    }
                    return e && (t.__proto__ = e), t.prototype = Object.create(e && e.prototype), t.prototype.constructor = t, t;
                }(Error);
                exports.getJSON = function (e, t) {
                    var r = makeRequest(e);
                    return r.setRequestHeader('Accept', 'application/json'), r.onerror = function () {
                        t(new Error(r.statusText));
                    }, r.onload = function () {
                        if (r.status >= 200 && r.status < 300 && r.response) {
                            var e;
                            try {
                                e = JSON.parse(r.response);
                            } catch (e) {
                                return t(e);
                            }
                            t(null, e);
                        } else {
                            t(new AJAXError(r.statusText, r.status));
                        }
                    }, r.send(), r;
                }, exports.getArrayBuffer = function (e, t) {
                    var r = makeRequest(e);
                    return r.responseType = 'arraybuffer', r.onerror = function () {
                        t(new Error(r.statusText));
                    }, r.onload = function () {
                        var e = r.response;
                        if (0 === e.byteLength && 200 === r.status) {
                            return t(new Error('http status 200 returned without content.'));
                        }
                        r.status >= 200 && r.status < 300 && r.response ? t(null, {
                            data: e,
                            cacheControl: r.getResponseHeader('Cache-Control'),
                            expires: r.getResponseHeader('Expires')
                        }) : t(new AJAXError(r.statusText, r.status));
                    }, r.send(), r;
                };
                var transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';
                exports.getImage = function (e, t) {
                    return exports.getArrayBuffer(e, function (e, r) {
                        if (e) {
                            t(e);
                        } else if (r) {
                            var n = new window.Image(), o = window.URL || window.webkitURL;
                            n.onload = function () {
                                t(null, n), o.revokeObjectURL(n.src);
                            };
                            var s = new window.Blob([new Uint8Array(r.data)], { type: 'image/png' });
                            n.cacheControl = r.cacheControl, n.expires = r.expires, n.src = r.data.byteLength ? o.createObjectURL(s) : transparentPngUrl;
                        }
                    });
                }, exports.getVideo = function (e, t) {
                    var r = window.document.createElement('video');
                    r.onloadstart = function () {
                        t(null, r);
                    };
                    for (var n = 0; n < e.length; n++) {
                        var o = window.document.createElement('source');
                        sameOrigin(e[n]) || (r.crossOrigin = 'Anonymous'), o.src = e[n], r.appendChild(o);
                    }
                    return r;
                };
            },
            { './window': 254 }
        ],
        252: [
            function (_dereq_, module, exports) {
                'use strict';
                var window = _dereq_('./window'), now = window.performance && window.performance.now ? window.performance.now.bind(window.performance) : Date.now.bind(Date), frame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame, cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.msCancelAnimationFrame;
                module.exports = {
                    now: now,
                    frame: function (e) {
                        return frame(e);
                    },
                    cancelFrame: function (e) {
                        return cancel(e);
                    },
                    getImageData: function (e) {
                        var n = window.document.createElement('canvas'), t = n.getContext('2d');
                        if (!t) {
                            throw new Error('failed to create canvas 2d context');
                        }
                        return n.width = e.width, n.height = e.height, t.drawImage(e, 0, 0, e.width, e.height), t.getImageData(0, 0, e.width, e.height);
                    },
                    hardwareConcurrency: window.navigator.hardwareConcurrency || 4,
                    get devicePixelRatio() {
                        return window.devicePixelRatio;
                    },
                    supportsWebp: !1
                };
                var webpImgTest = window.document.createElement('img');
                webpImgTest.onload = function () {
                    module.exports.supportsWebp = !0;
                }, webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=';
            },
            { './window': 254 }
        ],
        253: [
            function (_dereq_, module, exports) {
                'use strict';
                var WebWorkify = _dereq_('webworkify'), window = _dereq_('../window'), workerURL = window.URL.createObjectURL(new WebWorkify(_dereq_('../../source/worker'), { bare: !0 }));
                module.exports = function () {
                    return new window.Worker(workerURL);
                };
            },
            {
                '../../source/worker': 118,
                '../window': 254,
                'webworkify': 36
            }
        ],
        254: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = self;
            },
            {}
        ],
        255: [
            function (_dereq_, module, exports) {
                'use strict';
                function compareAreas(e, r) {
                    return r.area - e.area;
                }
                var quickselect = _dereq_('quickselect'), calculateSignedArea = _dereq_('./util').calculateSignedArea;
                module.exports = function (e, r) {
                    var a = e.length;
                    if (a <= 1) {
                        return [e];
                    }
                    for (var t, u, c = [], i = 0; i < a; i++) {
                        var l = calculateSignedArea(e[i]);
                        0 !== l && (e[i].area = Math.abs(l), void 0 === u && (u = l < 0), u === l < 0 ? (t && c.push(t), t = [e[i]]) : t.push(e[i]));
                    }
                    if (t && c.push(t), r > 1) {
                        for (var n = 0; n < c.length; n++) {
                            c[n].length <= r || (quickselect(c[n], r, 1, c[n].length - 1, compareAreas), c[n] = c[n].slice(0, r));
                        }
                    }
                    return c;
                };
            },
            {
                './util': 275,
                'quickselect': 31
            }
        ],
        256: [
            function (_dereq_, module, exports) {
                'use strict';
                var config = {
                    API_URL: 'https://api.mapbox.com',
                    REQUIRE_ACCESS_TOKEN: !0,
                    ACCESS_TOKEN: null
                };
                module.exports = config;
            },
            {}
        ],
        257: [
            function (_dereq_, module, exports) {
                'use strict';
                var DictionaryCoder = function (r) {
                    var t = this;
                    this._stringToNumber = {}, this._numberToString = [];
                    for (var o = 0; o < r.length; o++) {
                        var i = r[o];
                        t._stringToNumber[i] = o, t._numberToString[o] = i;
                    }
                };
                DictionaryCoder.prototype.encode = function (r) {
                    return this._stringToNumber[r];
                }, DictionaryCoder.prototype.decode = function (r) {
                    return this._numberToString[r];
                }, module.exports = DictionaryCoder;
            },
            {}
        ],
        258: [
            function (_dereq_, module, exports) {
                'use strict';
                var util = _dereq_('./util'), Actor = _dereq_('./actor'), Dispatcher = function (t, r) {
                        var o = this;
                        this.workerPool = t, this.actors = [], this.currentActor = 0, this.id = util.uniqueId();
                        for (var i = this.workerPool.acquire(this.id), e = 0; e < i.length; e++) {
                            var s = i[e], c = new Actor(s, r, o.id);
                            c.name = 'Worker ' + e, o.actors.push(c);
                        }
                    };
                Dispatcher.prototype.broadcast = function (t, r, o) {
                    o = o || function () {
                    }, util.asyncAll(this.actors, function (o, i) {
                        o.send(t, r, i);
                    }, o);
                }, Dispatcher.prototype.send = function (t, r, o, i) {
                    return ('number' != typeof i || isNaN(i)) && (i = this.currentActor = (this.currentActor + 1) % this.actors.length), this.actors[i].send(t, r, o), i;
                }, Dispatcher.prototype.remove = function () {
                    this.actors.forEach(function (t) {
                        t.remove();
                    }), this.actors = [], this.workerPool.release(this.id);
                }, module.exports = Dispatcher;
            },
            {
                './actor': 250,
                './util': 275
            }
        ],
        259: [
            function (_dereq_, module, exports) {
                'use strict';
                function testProp(e) {
                    for (var t = 0; t < e.length; t++) {
                        if (e[t] in docStyle) {
                            return e[t];
                        }
                    }
                    return e[0];
                }
                var Point = _dereq_('@mapbox/point-geometry'), window = _dereq_('./window');
                exports.create = function (e, t, n) {
                    var o = window.document.createElement(e);
                    return t && (o.className = t), n && n.appendChild(o), o;
                }, exports.createNS = function (e, t) {
                    return window.document.createElementNS(e, t);
                };
                var docStyle = window.document.documentElement.style, selectProp = testProp([
                        'userSelect',
                        'MozUserSelect',
                        'WebkitUserSelect',
                        'msUserSelect'
                    ]), userSelect;
                exports.disableDrag = function () {
                    selectProp && (userSelect = docStyle[selectProp], docStyle[selectProp] = 'none');
                }, exports.enableDrag = function () {
                    selectProp && (docStyle[selectProp] = userSelect);
                };
                var transformProp = testProp([
                    'transform',
                    'WebkitTransform'
                ]);
                exports.setTransform = function (e, t) {
                    e.style[transformProp] = t;
                };
                var suppressClick = function (e) {
                    e.preventDefault(), e.stopPropagation(), window.removeEventListener('click', suppressClick, !0);
                };
                exports.suppressClick = function () {
                    window.addEventListener('click', suppressClick, !0), window.setTimeout(function () {
                        window.removeEventListener('click', suppressClick, !0);
                    }, 0);
                }, exports.mousePos = function (e, t) {
                    var n = e.getBoundingClientRect();
                    return t = t.touches ? t.touches[0] : t, new Point(t.clientX - n.left - e.clientLeft, t.clientY - n.top - e.clientTop);
                }, exports.touchPos = function (e, t) {
                    for (var n = e.getBoundingClientRect(), o = [], r = 'touchend' === t.type ? t.changedTouches : t.touches, c = 0; c < r.length; c++) {
                        o.push(new Point(r[c].clientX - n.left - e.clientLeft, r[c].clientY - n.top - e.clientTop));
                    }
                    return o;
                }, exports.remove = function (e) {
                    e.parentNode && e.parentNode.removeChild(e);
                };
            },
            {
                './window': 254,
                '@mapbox/point-geometry': 4
            }
        ],
        260: [
            function (_dereq_, module, exports) {
                'use strict';
                function _addEventListener(e, t, n) {
                    n[e] = n[e] || [], n[e].push(t);
                }
                function _removeEventListener(e, t, n) {
                    if (n && n[e]) {
                        var i = n[e].indexOf(t);
                        -1 !== i && n[e].splice(i, 1);
                    }
                }
                var util = _dereq_('./util'), Evented = function () {
                    };
                Evented.prototype.on = function (e, t) {
                    return this._listeners = this._listeners || {}, _addEventListener(e, t, this._listeners), this;
                }, Evented.prototype.off = function (e, t) {
                    return _removeEventListener(e, t, this._listeners), _removeEventListener(e, t, this._oneTimeListeners), this;
                }, Evented.prototype.once = function (e, t) {
                    return this._oneTimeListeners = this._oneTimeListeners || {}, _addEventListener(e, t, this._oneTimeListeners), this;
                }, Evented.prototype.fire = function (e, t) {
                    var n = this;
                    if (this.listens(e)) {
                        t = util.extend({}, t, {
                            type: e,
                            target: this
                        });
                        for (var i = this._listeners && this._listeners[e] ? this._listeners[e].slice() : [], s = 0, r = i; s < r.length; s += 1) {
                            r[s].call(n, t);
                        }
                        for (var o = this._oneTimeListeners && this._oneTimeListeners[e] ? this._oneTimeListeners[e].slice() : [], h = 0, _ = o; h < _.length; h += 1) {
                            var v = _[h];
                            _removeEventListener(e, v, n._oneTimeListeners), v.call(n, t);
                        }
                        this._eventedParent && this._eventedParent.fire(e, util.extend({}, t, 'function' == typeof this._eventedParentData ? this._eventedParentData() : this._eventedParentData));
                    } else {
                        util.endsWith(e, 'error') && console.error(t && t.error || t || 'Empty error event');
                    }
                    return this;
                }, Evented.prototype.listens = function (e) {
                    return this._listeners && this._listeners[e] && this._listeners[e].length > 0 || this._oneTimeListeners && this._oneTimeListeners[e] && this._oneTimeListeners[e].length > 0 || this._eventedParent && this._eventedParent.listens(e);
                }, Evented.prototype.setEventedParent = function (e, t) {
                    return this._eventedParent = e, this._eventedParentData = t, this;
                }, module.exports = Evented;
            },
            { './util': 275 }
        ],
        261: [
            function (_dereq_, module, exports) {
                'use strict';
                function compareMax(e, t) {
                    return t.max - e.max;
                }
                function Cell(e, t, n, o) {
                    this.p = new Point(e, t), this.h = n, this.d = pointToPolygonDist(this.p, o), this.max = this.d + this.h * Math.SQRT2;
                }
                function pointToPolygonDist(e, t) {
                    for (var n = !1, o = 1 / 0, r = 0; r < t.length; r++) {
                        for (var i = t[r], l = 0, u = i.length, a = u - 1; l < u; a = l++) {
                            var s = i[l], p = i[a];
                            s.y > e.y != p.y > e.y && e.x < (p.x - s.x) * (e.y - s.y) / (p.y - s.y) + s.x && (n = !n), o = Math.min(o, distToSegmentSquared(e, s, p));
                        }
                    }
                    return (n ? 1 : -1) * Math.sqrt(o);
                }
                function getCentroidCell(e) {
                    for (var t = 0, n = 0, o = 0, r = e[0], i = 0, l = r.length, u = l - 1; i < l; u = i++) {
                        var a = r[i], s = r[u], p = a.x * s.y - s.x * a.y;
                        n += (a.x + s.x) * p, o += (a.y + s.y) * p, t += 3 * p;
                    }
                    return new Cell(n / t, o / t, 0, e);
                }
                var Queue = _dereq_('tinyqueue'), Point = _dereq_('@mapbox/point-geometry'), distToSegmentSquared = _dereq_('./intersection_tests').distToSegmentSquared;
                module.exports = function (e, t, n) {
                    void 0 === t && (t = 1), void 0 === n && (n = !1);
                    for (var o = 1 / 0, r = 1 / 0, i = -1 / 0, l = -1 / 0, u = e[0], a = 0; a < u.length; a++) {
                        var s = u[a];
                        (!a || s.x < o) && (o = s.x), (!a || s.y < r) && (r = s.y), (!a || s.x > i) && (i = s.x), (!a || s.y > l) && (l = s.y);
                    }
                    var p = i - o, h = l - r, d = Math.min(p, h), x = d / 2, y = new Queue(null, compareMax);
                    if (0 === d) {
                        return new Point(o, r);
                    }
                    for (var g = o; g < i; g += d) {
                        for (var f = r; f < l; f += d) {
                            y.push(new Cell(g + x, f + x, x, e));
                        }
                    }
                    for (var m = getCentroidCell(e), v = y.length; y.length;) {
                        var c = y.pop();
                        (c.d > m.d || !m.d) && (m = c, n && console.log('found best %d after %d probes', Math.round(10000 * c.d) / 10000, v)), c.max - m.d <= t || (x = c.h / 2, y.push(new Cell(c.p.x - x, c.p.y - x, x, e)), y.push(new Cell(c.p.x + x, c.p.y - x, x, e)), y.push(new Cell(c.p.x - x, c.p.y + x, x, e)), y.push(new Cell(c.p.x + x, c.p.y + x, x, e)), v += 4);
                    }
                    return n && (console.log('num probes: ' + v), console.log('best distance: ' + m.d)), m.p;
                };
            },
            {
                './intersection_tests': 264,
                '@mapbox/point-geometry': 4,
                'tinyqueue': 33
            }
        ],
        262: [
            function (_dereq_, module, exports) {
                'use strict';
                var WorkerPool = _dereq_('./worker_pool'), globalWorkerPool;
                module.exports = function () {
                    return globalWorkerPool || (globalWorkerPool = new WorkerPool()), globalWorkerPool;
                };
            },
            { './worker_pool': 279 }
        ],
        263: [
            function (_dereq_, module, exports) {
                'use strict';
                function createImage(e, t, i, h) {
                    var a = t.width, r = t.height;
                    if (h) {
                        if (h.length !== a * r * i) {
                            throw new RangeError('mismatched image size');
                        }
                    } else {
                        h = new Uint8Array(a * r * i);
                    }
                    return e.width = a, e.height = r, e.data = h, e;
                }
                function resizeImage(e, t, i) {
                    var h = t.width, a = t.height;
                    if (h !== e.width || a !== e.height) {
                        var r = createImage({}, {
                            width: h,
                            height: a
                        }, i);
                        copyImage(e, r, {
                            x: 0,
                            y: 0
                        }, {
                            x: 0,
                            y: 0
                        }, {
                            width: Math.min(e.width, h),
                            height: Math.min(e.height, a)
                        }, i), e.width = h, e.height = a, e.data = r.data;
                    }
                }
                function copyImage(e, t, i, h, a, r) {
                    if (0 === a.width || 0 === a.height) {
                        return t;
                    }
                    if (a.width > e.width || a.height > e.height || i.x > e.width - a.width || i.y > e.height - a.height) {
                        throw new RangeError('out of range source coordinates for image copy');
                    }
                    if (a.width > t.width || a.height > t.height || h.x > t.width - a.width || h.y > t.height - a.height) {
                        throw new RangeError('out of range destination coordinates for image copy');
                    }
                    for (var g = e.data, n = t.data, o = 0; o < a.height; o++) {
                        for (var m = ((i.y + o) * e.width + i.x) * r, w = ((h.y + o) * t.width + h.x) * r, d = 0; d < a.width * r; d++) {
                            n[w + d] = g[m + d];
                        }
                    }
                    return t;
                }
                var ref = _dereq_('./web_worker_transfer'), register = ref.register, AlphaImage = function (e, t) {
                        createImage(this, e, 1, t);
                    };
                AlphaImage.prototype.resize = function (e) {
                    resizeImage(this, e, 1);
                }, AlphaImage.prototype.clone = function () {
                    return new AlphaImage({
                        width: this.width,
                        height: this.height
                    }, new Uint8Array(this.data));
                }, AlphaImage.copy = function (e, t, i, h, a) {
                    copyImage(e, t, i, h, a, 1);
                };
                var RGBAImage = function (e, t) {
                    createImage(this, e, 4, t);
                };
                RGBAImage.prototype.resize = function (e) {
                    resizeImage(this, e, 4);
                }, RGBAImage.prototype.clone = function () {
                    return new RGBAImage({
                        width: this.width,
                        height: this.height
                    }, new Uint8Array(this.data));
                }, RGBAImage.copy = function (e, t, i, h, a) {
                    copyImage(e, t, i, h, a, 4);
                }, register('AlphaImage', AlphaImage), register('RGBAImage', RGBAImage), module.exports = {
                    AlphaImage: AlphaImage,
                    RGBAImage: RGBAImage
                };
            },
            { './web_worker_transfer': 278 }
        ],
        264: [
            function (_dereq_, module, exports) {
                'use strict';
                function polygonIntersectsPolygon(n, t) {
                    for (var e = 0; e < n.length; e++) {
                        if (polygonContainsPoint(t, n[e])) {
                            return !0;
                        }
                    }
                    for (var r = 0; r < t.length; r++) {
                        if (polygonContainsPoint(n, t[r])) {
                            return !0;
                        }
                    }
                    return !!lineIntersectsLine(n, t);
                }
                function multiPolygonIntersectsBufferedMultiPoint(n, t, e) {
                    for (var r = 0; r < n.length; r++) {
                        for (var o = n[r], i = 0; i < t.length; i++) {
                            for (var l = t[i], u = 0; u < l.length; u++) {
                                var s = l[u];
                                if (polygonContainsPoint(o, s)) {
                                    return !0;
                                }
                                if (pointIntersectsBufferedLine(s, o, e)) {
                                    return !0;
                                }
                            }
                        }
                    }
                    return !1;
                }
                function multiPolygonIntersectsMultiPolygon(n, t) {
                    if (1 === n.length && 1 === n[0].length) {
                        return multiPolygonContainsPoint(t, n[0][0]);
                    }
                    for (var e = 0; e < t.length; e++) {
                        for (var r = t[e], o = 0; o < r.length; o++) {
                            if (multiPolygonContainsPoint(n, r[o])) {
                                return !0;
                            }
                        }
                    }
                    for (var i = 0; i < n.length; i++) {
                        for (var l = n[i], u = 0; u < l.length; u++) {
                            if (multiPolygonContainsPoint(t, l[u])) {
                                return !0;
                            }
                        }
                        for (var s = 0; s < t.length; s++) {
                            if (lineIntersectsLine(l, t[s])) {
                                return !0;
                            }
                        }
                    }
                    return !1;
                }
                function multiPolygonIntersectsBufferedMultiLine(n, t, e) {
                    for (var r = 0; r < t.length; r++) {
                        for (var o = t[r], i = 0; i < n.length; i++) {
                            var l = n[i];
                            if (l.length >= 3) {
                                for (var u = 0; u < o.length; u++) {
                                    if (polygonContainsPoint(l, o[u])) {
                                        return !0;
                                    }
                                }
                            }
                            if (lineIntersectsBufferedLine(l, o, e)) {
                                return !0;
                            }
                        }
                    }
                    return !1;
                }
                function lineIntersectsBufferedLine(n, t, e) {
                    if (n.length > 1) {
                        if (lineIntersectsLine(n, t)) {
                            return !0;
                        }
                        for (var r = 0; r < t.length; r++) {
                            if (pointIntersectsBufferedLine(t[r], n, e)) {
                                return !0;
                            }
                        }
                    }
                    for (var o = 0; o < n.length; o++) {
                        if (pointIntersectsBufferedLine(n[o], t, e)) {
                            return !0;
                        }
                    }
                    return !1;
                }
                function lineIntersectsLine(n, t) {
                    if (0 === n.length || 0 === t.length) {
                        return !1;
                    }
                    for (var e = 0; e < n.length - 1; e++) {
                        for (var r = n[e], o = n[e + 1], i = 0; i < t.length - 1; i++) {
                            var l = t[i], u = t[i + 1];
                            if (lineSegmentIntersectsLineSegment(r, o, l, u)) {
                                return !0;
                            }
                        }
                    }
                    return !1;
                }
                function lineSegmentIntersectsLineSegment(n, t, e, r) {
                    return isCounterClockwise(n, e, r) !== isCounterClockwise(t, e, r) && isCounterClockwise(n, t, e) !== isCounterClockwise(n, t, r);
                }
                function pointIntersectsBufferedLine(n, t, e) {
                    var r = e * e;
                    if (1 === t.length) {
                        return n.distSqr(t[0]) < r;
                    }
                    for (var o = 1; o < t.length; o++) {
                        if (distToSegmentSquared(n, t[o - 1], t[o]) < r) {
                            return !0;
                        }
                    }
                    return !1;
                }
                function distToSegmentSquared(n, t, e) {
                    var r = t.distSqr(e);
                    if (0 === r) {
                        return n.distSqr(t);
                    }
                    var o = ((n.x - t.x) * (e.x - t.x) + (n.y - t.y) * (e.y - t.y)) / r;
                    return o < 0 ? n.distSqr(t) : o > 1 ? n.distSqr(e) : n.distSqr(e.sub(t)._mult(o)._add(t));
                }
                function multiPolygonContainsPoint(n, t) {
                    for (var e, r, o, i = !1, l = 0; l < n.length; l++) {
                        e = n[l];
                        for (var u = 0, s = e.length - 1; u < e.length; s = u++) {
                            r = e[u], o = e[s], r.y > t.y != o.y > t.y && t.x < (o.x - r.x) * (t.y - r.y) / (o.y - r.y) + r.x && (i = !i);
                        }
                    }
                    return i;
                }
                function polygonContainsPoint(n, t) {
                    for (var e = !1, r = 0, o = n.length - 1; r < n.length; o = r++) {
                        var i = n[r], l = n[o];
                        i.y > t.y != l.y > t.y && t.x < (l.x - i.x) * (t.y - i.y) / (l.y - i.y) + i.x && (e = !e);
                    }
                    return e;
                }
                var ref = _dereq_('./util'), isCounterClockwise = ref.isCounterClockwise;
                module.exports = {
                    multiPolygonIntersectsBufferedMultiPoint: multiPolygonIntersectsBufferedMultiPoint,
                    multiPolygonIntersectsMultiPolygon: multiPolygonIntersectsMultiPolygon,
                    multiPolygonIntersectsBufferedMultiLine: multiPolygonIntersectsBufferedMultiLine,
                    polygonIntersectsPolygon: polygonIntersectsPolygon,
                    distToSegmentSquared: distToSegmentSquared
                };
            },
            { './util': 275 }
        ],
        265: [
            function (_dereq_, module, exports) {
                'use strict';
                var unicodeBlockLookup = {
                    'Latin-1 Supplement': function (n) {
                        return n >= 128 && n <= 255;
                    },
                    Arabic: function (n) {
                        return n >= 1536 && n <= 1791;
                    },
                    'Arabic Supplement': function (n) {
                        return n >= 1872 && n <= 1919;
                    },
                    'Arabic Extended-A': function (n) {
                        return n >= 2208 && n <= 2303;
                    },
                    'Hangul Jamo': function (n) {
                        return n >= 4352 && n <= 4607;
                    },
                    'Unified Canadian Aboriginal Syllabics': function (n) {
                        return n >= 5120 && n <= 5759;
                    },
                    'Unified Canadian Aboriginal Syllabics Extended': function (n) {
                        return n >= 6320 && n <= 6399;
                    },
                    'General Punctuation': function (n) {
                        return n >= 8192 && n <= 8303;
                    },
                    'Letterlike Symbols': function (n) {
                        return n >= 8448 && n <= 8527;
                    },
                    'Number Forms': function (n) {
                        return n >= 8528 && n <= 8591;
                    },
                    'Miscellaneous Technical': function (n) {
                        return n >= 8960 && n <= 9215;
                    },
                    'Control Pictures': function (n) {
                        return n >= 9216 && n <= 9279;
                    },
                    'Optical Character Recognition': function (n) {
                        return n >= 9280 && n <= 9311;
                    },
                    'Enclosed Alphanumerics': function (n) {
                        return n >= 9312 && n <= 9471;
                    },
                    'Geometric Shapes': function (n) {
                        return n >= 9632 && n <= 9727;
                    },
                    'Miscellaneous Symbols': function (n) {
                        return n >= 9728 && n <= 9983;
                    },
                    'Miscellaneous Symbols and Arrows': function (n) {
                        return n >= 11008 && n <= 11263;
                    },
                    'CJK Radicals Supplement': function (n) {
                        return n >= 11904 && n <= 12031;
                    },
                    'Kangxi Radicals': function (n) {
                        return n >= 12032 && n <= 12255;
                    },
                    'Ideographic Description Characters': function (n) {
                        return n >= 12272 && n <= 12287;
                    },
                    'CJK Symbols and Punctuation': function (n) {
                        return n >= 12288 && n <= 12351;
                    },
                    Hiragana: function (n) {
                        return n >= 12352 && n <= 12447;
                    },
                    Katakana: function (n) {
                        return n >= 12448 && n <= 12543;
                    },
                    Bopomofo: function (n) {
                        return n >= 12544 && n <= 12591;
                    },
                    'Hangul Compatibility Jamo': function (n) {
                        return n >= 12592 && n <= 12687;
                    },
                    Kanbun: function (n) {
                        return n >= 12688 && n <= 12703;
                    },
                    'Bopomofo Extended': function (n) {
                        return n >= 12704 && n <= 12735;
                    },
                    'CJK Strokes': function (n) {
                        return n >= 12736 && n <= 12783;
                    },
                    'Katakana Phonetic Extensions': function (n) {
                        return n >= 12784 && n <= 12799;
                    },
                    'Enclosed CJK Letters and Months': function (n) {
                        return n >= 12800 && n <= 13055;
                    },
                    'CJK Compatibility': function (n) {
                        return n >= 13056 && n <= 13311;
                    },
                    'CJK Unified Ideographs Extension A': function (n) {
                        return n >= 13312 && n <= 19903;
                    },
                    'Yijing Hexagram Symbols': function (n) {
                        return n >= 19904 && n <= 19967;
                    },
                    'CJK Unified Ideographs': function (n) {
                        return n >= 19968 && n <= 40959;
                    },
                    'Yi Syllables': function (n) {
                        return n >= 40960 && n <= 42127;
                    },
                    'Yi Radicals': function (n) {
                        return n >= 42128 && n <= 42191;
                    },
                    'Hangul Jamo Extended-A': function (n) {
                        return n >= 43360 && n <= 43391;
                    },
                    'Hangul Syllables': function (n) {
                        return n >= 44032 && n <= 55215;
                    },
                    'Hangul Jamo Extended-B': function (n) {
                        return n >= 55216 && n <= 55295;
                    },
                    'Private Use Area': function (n) {
                        return n >= 57344 && n <= 63743;
                    },
                    'CJK Compatibility Ideographs': function (n) {
                        return n >= 63744 && n <= 64255;
                    },
                    'Arabic Presentation Forms-A': function (n) {
                        return n >= 64336 && n <= 65023;
                    },
                    'Vertical Forms': function (n) {
                        return n >= 65040 && n <= 65055;
                    },
                    'CJK Compatibility Forms': function (n) {
                        return n >= 65072 && n <= 65103;
                    },
                    'Small Form Variants': function (n) {
                        return n >= 65104 && n <= 65135;
                    },
                    'Arabic Presentation Forms-B': function (n) {
                        return n >= 65136 && n <= 65279;
                    },
                    'Halfwidth and Fullwidth Forms': function (n) {
                        return n >= 65280 && n <= 65519;
                    }
                };
                module.exports = unicodeBlockLookup;
            },
            {}
        ],
        266: [
            function (_dereq_, module, exports) {
                'use strict';
                var LRUCache = function (t, e) {
                    this.max = t, this.onRemove = e, this.reset();
                };
                LRUCache.prototype.reset = function () {
                    var t = this;
                    for (var e in t.data) {
                        t.onRemove(t.data[e]);
                    }
                    return this.data = {}, this.order = [], this;
                }, LRUCache.prototype.add = function (t, e) {
                    if (this.has(t)) {
                        this.order.splice(this.order.indexOf(t), 1), this.data[t] = e, this.order.push(t);
                    } else if (this.data[t] = e, this.order.push(t), this.order.length > this.max) {
                        var r = this.getAndRemove(this.order[0]);
                        r && this.onRemove(r);
                    }
                    return this;
                }, LRUCache.prototype.has = function (t) {
                    return t in this.data;
                }, LRUCache.prototype.keys = function () {
                    return this.order;
                }, LRUCache.prototype.getAndRemove = function (t) {
                    if (!this.has(t)) {
                        return null;
                    }
                    var e = this.data[t];
                    return delete this.data[t], this.order.splice(this.order.indexOf(t), 1), e;
                }, LRUCache.prototype.get = function (t) {
                    return this.has(t) ? this.data[t] : null;
                }, LRUCache.prototype.remove = function (t) {
                    if (!this.has(t)) {
                        return this;
                    }
                    var e = this.data[t];
                    return delete this.data[t], this.onRemove(e), this.order.splice(this.order.indexOf(t), 1), this;
                }, LRUCache.prototype.setMaxSize = function (t) {
                    var e = this;
                    for (this.max = t; this.order.length > this.max;) {
                        var r = e.getAndRemove(e.order[0]);
                        r && e.onRemove(r);
                    }
                    return this;
                }, module.exports = LRUCache;
            },
            {}
        ],
        267: [
            function (_dereq_, module, exports) {
                'use strict';
                function makeAPIURL(r, e) {
                    var t = parseUrl(config.API_URL);
                    if (r.protocol = t.protocol, r.authority = t.authority, '/' !== t.path && (r.path = '' + t.path + r.path), !config.REQUIRE_ACCESS_TOKEN) {
                        return formatUrl(r);
                    }
                    if (!(e = e || config.ACCESS_TOKEN)) {
                        throw new Error('An API access token is required to use Mapbox GL. ' + help);
                    }
                    if ('s' === e[0]) {
                        throw new Error('Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ' + help);
                    }
                    return r.params.push('access_token=' + e), formatUrl(r);
                }
                function isMapboxURL(r) {
                    return 0 === r.indexOf('mapbox:');
                }
                function replaceTempAccessToken(r) {
                    for (var e = 0; e < r.length; e++) {
                        0 === r[e].indexOf('access_token=tk.') && (r[e] = 'access_token=' + (config.ACCESS_TOKEN || ''));
                    }
                }
                function parseUrl(r) {
                    var e = r.match(urlRe);
                    if (!e) {
                        throw new Error('Unable to parse URL object');
                    }
                    return {
                        protocol: e[1],
                        authority: e[2],
                        path: e[3] || '/',
                        params: e[4] ? e[4].split('&') : []
                    };
                }
                function formatUrl(r) {
                    var e = r.params.length ? '?' + r.params.join('&') : '';
                    return r.protocol + '://' + r.authority + r.path + e;
                }
                var config = _dereq_('./config'), browser = _dereq_('./browser'), help = 'See https://www.mapbox.com/api-documentation/#access-tokens';
                exports.isMapboxURL = isMapboxURL, exports.normalizeStyleURL = function (r, e) {
                    if (!isMapboxURL(r)) {
                        return r;
                    }
                    var t = parseUrl(r);
                    return t.path = '/styles/v1' + t.path, makeAPIURL(t, e);
                }, exports.normalizeGlyphsURL = function (r, e) {
                    if (!isMapboxURL(r)) {
                        return r;
                    }
                    var t = parseUrl(r);
                    return t.path = '/fonts/v1' + t.path, makeAPIURL(t, e);
                }, exports.normalizeSourceURL = function (r, e) {
                    if (!isMapboxURL(r)) {
                        return r;
                    }
                    var t = parseUrl(r);
                    return t.path = '/v4/' + t.authority + '.json', t.params.push('secure'), makeAPIURL(t, e);
                }, exports.normalizeSpriteURL = function (r, e, t, a) {
                    var o = parseUrl(r);
                    return isMapboxURL(r) ? (o.path = '/styles/v1' + o.path + '/sprite' + e + t, makeAPIURL(o, a)) : (o.path += '' + e + t, formatUrl(o));
                };
                var imageExtensionRe = /(\.(png|jpg)\d*)(?=$)/;
                exports.normalizeTileURL = function (r, e, t) {
                    if (!e || !isMapboxURL(e)) {
                        return r;
                    }
                    var a = parseUrl(r), o = browser.devicePixelRatio >= 2 || 512 === t ? '@2x' : '', p = browser.supportsWebp ? '.webp' : '$1';
                    return a.path = a.path.replace(imageExtensionRe, '' + o + p), replaceTempAccessToken(a.params), formatUrl(a);
                };
                var urlRe = /^(\w+):\/\/([^\/?]*)(\/[^?]+)?\??(.+)?/;
            },
            {
                './browser': 252,
                './config': 256
            }
        ],
        268: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = {
                    getEntriesByName: function (e) {
                        return !(!performance || !performance.getEntriesByName) && performance.getEntriesByName(e);
                    }
                };
            },
            {}
        ],
        269: [
            function (_dereq_, module, exports) {
                'use strict';
                var isChar = _dereq_('./is_char_in_unicode_block');
                module.exports.allowsIdeographicBreaking = function (a) {
                    for (var i = 0, r = a; i < r.length; i += 1) {
                        var s = r[i];
                        if (!exports.charAllowsIdeographicBreaking(s.charCodeAt(0))) {
                            return !1;
                        }
                    }
                    return !0;
                }, module.exports.allowsVerticalWritingMode = function (a) {
                    for (var i = 0, r = a; i < r.length; i += 1) {
                        var s = r[i];
                        if (exports.charHasUprightVerticalOrientation(s.charCodeAt(0))) {
                            return !0;
                        }
                    }
                    return !1;
                }, module.exports.allowsLetterSpacing = function (a) {
                    for (var i = 0, r = a; i < r.length; i += 1) {
                        var s = r[i];
                        if (!exports.charAllowsLetterSpacing(s.charCodeAt(0))) {
                            return !1;
                        }
                    }
                    return !0;
                }, module.exports.charAllowsLetterSpacing = function (a) {
                    return !isChar.Arabic(a) && (!isChar['Arabic Supplement'](a) && (!isChar['Arabic Extended-A'](a) && (!isChar['Arabic Presentation Forms-A'](a) && !isChar['Arabic Presentation Forms-B'](a))));
                }, module.exports.charAllowsIdeographicBreaking = function (a) {
                    return !(a < 11904) && (!!isChar['Bopomofo Extended'](a) || (!!isChar.Bopomofo(a) || (!!isChar['CJK Compatibility Forms'](a) || (!!isChar['CJK Compatibility Ideographs'](a) || (!!isChar['CJK Compatibility'](a) || (!!isChar['CJK Radicals Supplement'](a) || (!!isChar['CJK Strokes'](a) || (!!isChar['CJK Symbols and Punctuation'](a) || (!!isChar['CJK Unified Ideographs Extension A'](a) || (!!isChar['CJK Unified Ideographs'](a) || (!!isChar['Enclosed CJK Letters and Months'](a) || (!!isChar['Halfwidth and Fullwidth Forms'](a) || (!!isChar.Hiragana(a) || (!!isChar['Ideographic Description Characters'](a) || (!!isChar['Kangxi Radicals'](a) || (!!isChar['Katakana Phonetic Extensions'](a) || (!!isChar.Katakana(a) || (!!isChar['Vertical Forms'](a) || (!!isChar['Yi Radicals'](a) || !!isChar['Yi Syllables'](a))))))))))))))))))));
                }, exports.charHasUprightVerticalOrientation = function (a) {
                    return 746 === a || 747 === a || !(a < 4352) && (!!isChar['Bopomofo Extended'](a) || (!!isChar.Bopomofo(a) || (!(!isChar['CJK Compatibility Forms'](a) || a >= 65097 && a <= 65103) || (!!isChar['CJK Compatibility Ideographs'](a) || (!!isChar['CJK Compatibility'](a) || (!!isChar['CJK Radicals Supplement'](a) || (!!isChar['CJK Strokes'](a) || (!(!isChar['CJK Symbols and Punctuation'](a) || a >= 12296 && a <= 12305 || a >= 12308 && a <= 12319 || 12336 === a) || (!!isChar['CJK Unified Ideographs Extension A'](a) || (!!isChar['CJK Unified Ideographs'](a) || (!!isChar['Enclosed CJK Letters and Months'](a) || (!!isChar['Hangul Compatibility Jamo'](a) || (!!isChar['Hangul Jamo Extended-A'](a) || (!!isChar['Hangul Jamo Extended-B'](a) || (!!isChar['Hangul Jamo'](a) || (!!isChar['Hangul Syllables'](a) || (!!isChar.Hiragana(a) || (!!isChar['Ideographic Description Characters'](a) || (!!isChar.Kanbun(a) || (!!isChar['Kangxi Radicals'](a) || (!!isChar['Katakana Phonetic Extensions'](a) || (!(!isChar.Katakana(a) || 12540 === a) || (!(!isChar['Halfwidth and Fullwidth Forms'](a) || 65288 === a || 65289 === a || 65293 === a || a >= 65306 && a <= 65310 || 65339 === a || 65341 === a || 65343 === a || a >= 65371 && a <= 65503 || 65507 === a || a >= 65512 && a <= 65519) || (!(!isChar['Small Form Variants'](a) || a >= 65112 && a <= 65118 || a >= 65123 && a <= 65126) || (!!isChar['Unified Canadian Aboriginal Syllabics'](a) || (!!isChar['Unified Canadian Aboriginal Syllabics Extended'](a) || (!!isChar['Vertical Forms'](a) || (!!isChar['Yijing Hexagram Symbols'](a) || (!!isChar['Yi Syllables'](a) || !!isChar['Yi Radicals'](a))))))))))))))))))))))))))))));
                }, exports.charHasNeutralVerticalOrientation = function (a) {
                    return !(!isChar['Latin-1 Supplement'](a) || 167 !== a && 169 !== a && 174 !== a && 177 !== a && 188 !== a && 189 !== a && 190 !== a && 215 !== a && 247 !== a) || (!(!isChar['General Punctuation'](a) || 8214 !== a && 8224 !== a && 8225 !== a && 8240 !== a && 8241 !== a && 8251 !== a && 8252 !== a && 8258 !== a && 8263 !== a && 8264 !== a && 8265 !== a && 8273 !== a) || (!!isChar['Letterlike Symbols'](a) || (!!isChar['Number Forms'](a) || (!(!isChar['Miscellaneous Technical'](a) || !(a >= 8960 && a <= 8967 || a >= 8972 && a <= 8991 || a >= 8996 && a <= 9000 || 9003 === a || a >= 9085 && a <= 9114 || a >= 9150 && a <= 9165 || 9167 === a || a >= 9169 && a <= 9179 || a >= 9186 && a <= 9215)) || (!(!isChar['Control Pictures'](a) || 9251 === a) || (!!isChar['Optical Character Recognition'](a) || (!!isChar['Enclosed Alphanumerics'](a) || (!!isChar['Geometric Shapes'](a) || (!(!isChar['Miscellaneous Symbols'](a) || a >= 9754 && a <= 9759) || (!(!isChar['Miscellaneous Symbols and Arrows'](a) || !(a >= 11026 && a <= 11055 || a >= 11088 && a <= 11097 || a >= 11192 && a <= 11243)) || (!!isChar['CJK Symbols and Punctuation'](a) || (!!isChar.Katakana(a) || (!!isChar['Private Use Area'](a) || (!!isChar['CJK Compatibility Forms'](a) || (!!isChar['Small Form Variants'](a) || (!!isChar['Halfwidth and Fullwidth Forms'](a) || (8734 === a || 8756 === a || 8757 === a || a >= 9984 && a <= 10087 || a >= 10102 && a <= 10131 || 65532 === a || 65533 === a)))))))))))))))));
                }, exports.charHasRotatedVerticalOrientation = function (a) {
                    return !(exports.charHasUprightVerticalOrientation(a) || exports.charHasNeutralVerticalOrientation(a));
                };
            },
            { './is_char_in_unicode_block': 265 }
        ],
        270: [
            function (_dereq_, module, exports) {
                'use strict';
                var LngLat = _dereq_('../geo/lng_lat');
                module.exports = function (n, t, l) {
                    if (n = new LngLat(n.lng, n.lat), t) {
                        var a = new LngLat(n.lng - 360, n.lat), i = new LngLat(n.lng + 360, n.lat), o = l.locationPoint(n).distSqr(t);
                        l.locationPoint(a).distSqr(t) < o ? n = a : l.locationPoint(i).distSqr(t) < o && (n = i);
                    }
                    for (; Math.abs(n.lng - l.center.lng) > 180;) {
                        var e = l.locationPoint(n);
                        if (e.x >= 0 && e.y >= 0 && e.x <= l.width && e.y <= l.height) {
                            break;
                        }
                        n.lng > l.center.lng ? n.lng -= 360 : n.lng += 360;
                    }
                    return n;
                };
            },
            { '../geo/lng_lat': 62 }
        ],
        271: [
            function (_dereq_, module, exports) {
                'use strict';
                function createLayout(t, r) {
                    void 0 === r && (r = 1);
                    var e = 0, i = 0;
                    return {
                        members: t.map(function (t) {
                            var a = sizeOf(t.type), s = e = align(e, Math.max(r, a)), n = t.components || 1;
                            return i = Math.max(i, a), e += a * n, {
                                name: t.name,
                                type: t.type,
                                components: n,
                                offset: s
                            };
                        }),
                        size: align(e, Math.max(i, r)),
                        alignment: r
                    };
                }
                function sizeOf(t) {
                    return viewTypes[t].BYTES_PER_ELEMENT;
                }
                function align(t, r) {
                    return Math.ceil(t / r) * r;
                }
                var viewTypes = {
                        Int8: Int8Array,
                        Uint8: Uint8Array,
                        Int16: Int16Array,
                        Uint16: Uint16Array,
                        Int32: Int32Array,
                        Uint32: Uint32Array,
                        Float32: Float32Array
                    }, Struct = function (t, r) {
                        this._structArray = t, this._pos1 = r * this.size, this._pos2 = this._pos1 / 2, this._pos4 = this._pos1 / 4, this._pos8 = this._pos1 / 8;
                    }, DEFAULT_CAPACITY = 128, RESIZE_MULTIPLIER = 5, StructArray = function () {
                        this.isTransferred = !1, this.capacity = -1, this.resize(0);
                    };
                StructArray.serialize = function (t, r) {
                    return t._trim(), r && (t.isTransferred = !0, r.push(t.arrayBuffer)), {
                        length: t.length,
                        arrayBuffer: t.arrayBuffer
                    };
                }, StructArray.deserialize = function (t) {
                    var r = Object.create(this.prototype);
                    return r.arrayBuffer = t.arrayBuffer, r.length = t.length, r.capacity = t.arrayBuffer.byteLength / r.bytesPerElement, r._refreshViews(), r;
                }, StructArray.prototype._trim = function () {
                    this.length !== this.capacity && (this.capacity = this.length, this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement), this._refreshViews());
                }, StructArray.prototype.clear = function () {
                    this.length = 0;
                }, StructArray.prototype.resize = function (t) {
                    this.reserve(t), this.length = t;
                }, StructArray.prototype.reserve = function (t) {
                    if (t > this.capacity) {
                        this.capacity = Math.max(t, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY), this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);
                        var r = this.uint8;
                        this._refreshViews(), r && this.uint8.set(r);
                    }
                }, StructArray.prototype._refreshViews = function () {
                    throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');
                }, module.exports.StructArray = StructArray, module.exports.Struct = Struct, module.exports.viewTypes = viewTypes, module.exports.createLayout = createLayout;
            },
            {}
        ],
        272: [
            function (_dereq_, module, exports) {
                'use strict';
                module.exports = function (t, n) {
                    var u = !1, e = 0, r = function () {
                            e = 0, u && (t(), e = setTimeout(r, n), u = !1);
                        };
                    return function () {
                        return u = !0, e || r(), e;
                    };
                };
            },
            {}
        ],
        273: [
            function (_dereq_, module, exports) {
                'use strict';
                function tileCover(e, r, a, n) {
                    function d(r, d, t) {
                        var y, c, l, x;
                        if (t >= 0 && t <= o) {
                            for (y = r; y < d; y++) {
                                c = Math.floor(y / o), l = (y % o + o) % o, 0 !== c && !0 !== n || (x = new OverscaledTileID(a, c, e, l, t), i[x.key] = x);
                            }
                        }
                    }
                    void 0 === n && (n = !0);
                    var o = 1 << e, i = {};
                    return scanTriangle(r[0], r[1], r[2], 0, o, d), scanTriangle(r[2], r[3], r[0], 0, o, d), Object.keys(i).map(function (e) {
                        return i[e];
                    });
                }
                function edge(e, r) {
                    if (e.row > r.row) {
                        var a = e;
                        e = r, r = a;
                    }
                    return {
                        x0: e.column,
                        y0: e.row,
                        x1: r.column,
                        y1: r.row,
                        dx: r.column - e.column,
                        dy: r.row - e.row
                    };
                }
                function scanSpans(e, r, a, n, d) {
                    var o = Math.max(a, Math.floor(r.y0)), i = Math.min(n, Math.ceil(r.y1));
                    if (e.x0 === r.x0 && e.y0 === r.y0 ? e.x0 + r.dy / e.dy * e.dx < r.x1 : e.x1 - r.dy / e.dy * e.dx < r.x0) {
                        var t = e;
                        e = r, r = t;
                    }
                    for (var y = e.dx / e.dy, c = r.dx / r.dy, l = e.dx > 0, x = r.dx < 0, u = o; u < i; u++) {
                        var s = y * Math.max(0, Math.min(e.dy, u + l - e.y0)) + e.x0, f = c * Math.max(0, Math.min(r.dy, u + x - r.y0)) + r.x0;
                        d(Math.floor(f), Math.ceil(s), u);
                    }
                }
                function scanTriangle(e, r, a, n, d, o) {
                    var i, t = edge(e, r), y = edge(r, a), c = edge(a, e);
                    t.dy > y.dy && (i = t, t = y, y = i), t.dy > c.dy && (i = t, t = c, c = i), y.dy > c.dy && (i = y, y = c, c = i), t.dy && scanSpans(c, t, n, d, o), y.dy && scanSpans(c, y, n, d, o);
                }
                var Coordinate = _dereq_('../geo/coordinate'), ref = _dereq_('../source/tile_id'), OverscaledTileID = ref.OverscaledTileID;
                module.exports = tileCover;
            },
            {
                '../geo/coordinate': 61,
                '../source/tile_id': 114
            }
        ],
        274: [
            function (_dereq_, module, exports) {
                'use strict';
                function resolveTokens(e, n) {
                    return n.replace(/{([^{}]+)}/g, function (n, r) {
                        return r in e ? String(e[r]) : '';
                    });
                }
                module.exports = resolveTokens;
            },
            {}
        ],
        275: [
            function (_dereq_, module, exports) {
                'use strict';
                var UnitBezier = _dereq_('@mapbox/unitbezier'), Coordinate = _dereq_('../geo/coordinate'), Point = _dereq_('@mapbox/point-geometry');
                exports.easeCubicInOut = function (r) {
                    if (r <= 0) {
                        return 0;
                    }
                    if (r >= 1) {
                        return 1;
                    }
                    var e = r * r, n = e * r;
                    return 4 * (r < 0.5 ? n : 3 * (r - e) + n - 0.75);
                }, exports.bezier = function (r, e, n, t) {
                    var o = new UnitBezier(r, e, n, t);
                    return function (r) {
                        return o.solve(r);
                    };
                }, exports.ease = exports.bezier(0.25, 0.1, 0.25, 1), exports.clamp = function (r, e, n) {
                    return Math.min(n, Math.max(e, r));
                }, exports.wrap = function (r, e, n) {
                    var t = n - e, o = ((r - e) % t + t) % t + e;
                    return o === e ? n : o;
                }, exports.asyncAll = function (r, e, n) {
                    if (!r.length) {
                        return n(null, []);
                    }
                    var t = r.length, o = new Array(r.length), a = null;
                    r.forEach(function (r, i) {
                        e(r, function (r, e) {
                            r && (a = r), o[i] = e, 0 == --t && n(a, o);
                        });
                    });
                }, exports.values = function (r) {
                    var e = [];
                    for (var n in r) {
                        e.push(r[n]);
                    }
                    return e;
                }, exports.keysDifference = function (r, e) {
                    var n = [];
                    for (var t in r) {
                        t in e || n.push(t);
                    }
                    return n;
                }, exports.extend = function (r) {
                    var arguments$1 = arguments;
                    for (var e = [], n = arguments.length - 1; n-- > 0;) {
                        e[n] = arguments$1[n + 1];
                    }
                    for (var t = 0, o = e; t < o.length; t += 1) {
                        var a = o[t];
                        for (var i in a) {
                            r[i] = a[i];
                        }
                    }
                    return r;
                }, exports.pick = function (r, e) {
                    for (var n = {}, t = 0; t < e.length; t++) {
                        var o = e[t];
                        o in r && (n[o] = r[o]);
                    }
                    return n;
                };
                var id = 1;
                exports.uniqueId = function () {
                    return id++;
                }, exports.bindAll = function (r, e) {
                    r.forEach(function (r) {
                        e[r] && (e[r] = e[r].bind(e));
                    });
                }, exports.getCoordinatesCenter = function (r) {
                    for (var e = 1 / 0, n = 1 / 0, t = -1 / 0, o = -1 / 0, a = 0; a < r.length; a++) {
                        e = Math.min(e, r[a].column), n = Math.min(n, r[a].row), t = Math.max(t, r[a].column), o = Math.max(o, r[a].row);
                    }
                    var i = t - e, u = o - n, s = Math.max(i, u), c = Math.max(0, Math.floor(-Math.log(s) / Math.LN2));
                    return new Coordinate((e + t) / 2, (n + o) / 2, 0).zoomTo(c);
                }, exports.endsWith = function (r, e) {
                    return -1 !== r.indexOf(e, r.length - e.length);
                }, exports.mapObject = function (r, e, n) {
                    var t = this, o = {};
                    for (var a in r) {
                        o[a] = e.call(n || t, r[a], a, r);
                    }
                    return o;
                }, exports.filterObject = function (r, e, n) {
                    var t = this, o = {};
                    for (var a in r) {
                        e.call(n || t, r[a], a, r) && (o[a] = r[a]);
                    }
                    return o;
                }, exports.deepEqual = _dereq_('../style-spec/util/deep_equal'), exports.clone = function (r) {
                    return Array.isArray(r) ? r.map(exports.clone) : 'object' == typeof r && r ? exports.mapObject(r, exports.clone) : r;
                }, exports.arraysIntersect = function (r, e) {
                    for (var n = 0; n < r.length; n++) {
                        if (e.indexOf(r[n]) >= 0) {
                            return !0;
                        }
                    }
                    return !1;
                };
                var warnOnceHistory = {};
                exports.warnOnce = function (r) {
                    warnOnceHistory[r] || ('undefined' != typeof console && console.warn(r), warnOnceHistory[r] = !0);
                }, exports.isCounterClockwise = function (r, e, n) {
                    return (n.y - r.y) * (e.x - r.x) > (e.y - r.y) * (n.x - r.x);
                }, exports.calculateSignedArea = function (r) {
                    for (var e = 0, n = 0, t = r.length, o = t - 1, a = void 0, i = void 0; n < t; o = n++) {
                        a = r[n], i = r[o], e += (i.x - a.x) * (a.y + i.y);
                    }
                    return e;
                }, exports.isClosedPolygon = function (r) {
                    if (r.length < 4) {
                        return !1;
                    }
                    var e = r[0], n = r[r.length - 1];
                    return !(Math.abs(e.x - n.x) > 0 || Math.abs(e.y - n.y) > 0) && Math.abs(exports.calculateSignedArea(r)) > 0.01;
                }, exports.sphericalToCartesian = function (r) {
                    var e = r[0], n = r[1], t = r[2];
                    return n += 90, n *= Math.PI / 180, t *= Math.PI / 180, {
                        x: e * Math.cos(n) * Math.sin(t),
                        y: e * Math.sin(n) * Math.sin(t),
                        z: e * Math.cos(t)
                    };
                }, exports.parseCacheControl = function (r) {
                    var e = /(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g, n = {};
                    if (r.replace(e, function (r, e, t, o) {
                            var a = t || o;
                            return n[e] = !a || a.toLowerCase(), '';
                        }), n['max-age']) {
                        var t = parseInt(n['max-age'], 10);
                        isNaN(t) ? delete n['max-age'] : n['max-age'] = t;
                    }
                    return n;
                };
            },
            {
                '../geo/coordinate': 61,
                '../style-spec/util/deep_equal': 155,
                '@mapbox/point-geometry': 4,
                '@mapbox/unitbezier': 7
            }
        ],
        276: [
            function (_dereq_, module, exports) {
                'use strict';
                var Feature = function (e, t, r, o) {
                        this.type = 'Feature', this._vectorTileFeature = e, e._z = t, e._x = r, e._y = o, this.properties = e.properties, null != e.id && (this.id = e.id);
                    }, prototypeAccessors = { geometry: {} };
                prototypeAccessors.geometry.get = function () {
                    return void 0 === this._geometry && (this._geometry = this._vectorTileFeature.toGeoJSON(this._vectorTileFeature._x, this._vectorTileFeature._y, this._vectorTileFeature._z).geometry), this._geometry;
                }, prototypeAccessors.geometry.set = function (e) {
                    this._geometry = e;
                }, Feature.prototype.toJSON = function () {
                    var e = this, t = { geometry: this.geometry };
                    for (var r in e) {
                        '_geometry' !== r && '_vectorTileFeature' !== r && (t[r] = e[r]);
                    }
                    return t;
                }, Object.defineProperties(Feature.prototype, prototypeAccessors), module.exports = Feature;
            },
            {}
        ],
        277: [
            function (_dereq_, module, exports) {
                'use strict';
                var scriptDetection = _dereq_('./script_detection');
                module.exports = function (t) {
                    for (var o = '', e = 0; e < t.length; e++) {
                        var r = t.charCodeAt(e + 1) || null, l = t.charCodeAt(e - 1) || null;
                        (!r || !scriptDetection.charHasRotatedVerticalOrientation(r) || module.exports.lookup[t[e + 1]]) && (!l || !scriptDetection.charHasRotatedVerticalOrientation(l) || module.exports.lookup[t[e - 1]]) && module.exports.lookup[t[e]] ? o += module.exports.lookup[t[e]] : o += t[e];
                    }
                    return o;
                }, module.exports.lookup = {
                    '!': '\uFE15',
                    '#': '\uFF03',
                    $: '\uFF04',
                    '%': '\uFF05',
                    '&': '\uFF06',
                    '(': '\uFE35',
                    ')': '\uFE36',
                    '*': '\uFF0A',
                    '+': '\uFF0B',
                    ',': '\uFE10',
                    '-': '\uFE32',
                    '.': '\u30FB',
                    '/': '\uFF0F',
                    ':': '\uFE13',
                    ';': '\uFE14',
                    '<': '\uFE3F',
                    '=': '\uFF1D',
                    '>': '\uFE40',
                    '?': '\uFE16',
                    '@': '\uFF20',
                    '[': '\uFE47',
                    '\\': '\uFF3C',
                    ']': '\uFE48',
                    '^': '\uFF3E',
                    _: '︳',
                    '`': '\uFF40',
                    '{': '\uFE37',
                    '|': '\u2015',
                    '}': '\uFE38',
                    '~': '\uFF5E',
                    '\xA2': '\uFFE0',
                    '\xA3': '\uFFE1',
                    '\xA5': '\uFFE5',
                    '\xA6': '\uFFE4',
                    '\xAC': '\uFFE2',
                    '\xAF': '\uFFE3',
                    '\u2013': '\uFE32',
                    '\u2014': '\uFE31',
                    '\u2018': '\uFE43',
                    '\u2019': '\uFE44',
                    '\u201C': '\uFE41',
                    '\u201D': '\uFE42',
                    '\u2026': '\uFE19',
                    '\u2027': '\u30FB',
                    '\u20A9': '\uFFE6',
                    '\u3001': '\uFE11',
                    '\u3002': '\uFE12',
                    '\u3008': '\uFE3F',
                    '\u3009': '\uFE40',
                    '\u300A': '\uFE3D',
                    '\u300B': '\uFE3E',
                    '\u300C': '\uFE41',
                    '\u300D': '\uFE42',
                    '\u300E': '\uFE43',
                    '\u300F': '\uFE44',
                    '\u3010': '\uFE3B',
                    '\u3011': '\uFE3C',
                    '\u3014': '\uFE39',
                    '\u3015': '\uFE3A',
                    '\u3016': '\uFE17',
                    '\u3017': '\uFE18',
                    '\uFF01': '\uFE15',
                    '\uFF08': '\uFE35',
                    '\uFF09': '\uFE36',
                    '\uFF0C': '\uFE10',
                    '\uFF0D': '\uFE32',
                    '\uFF0E': '\u30FB',
                    '\uFF1A': '\uFE13',
                    '\uFF1B': '\uFE14',
                    '\uFF1C': '\uFE3F',
                    '\uFF1E': '\uFE40',
                    '\uFF1F': '\uFE16',
                    '\uFF3B': '\uFE47',
                    '\uFF3D': '\uFE48',
                    '＿': '︳',
                    '\uFF5B': '\uFE37',
                    '\uFF5C': '\u2015',
                    '\uFF5D': '\uFE38',
                    '\uFF5F': '\uFE35',
                    '\uFF60': '\uFE36',
                    '\uFF61': '\uFE12',
                    '\uFF62': '\uFE41',
                    '\uFF63': '\uFE42'
                };
            },
            { './script_detection': 269 }
        ],
        278: [
            function (_dereq_, module, exports) {
                'use strict';
                function register(e, r, i) {
                    void 0 === i && (i = {}), Object.defineProperty(r, '_classRegistryKey', {
                        value: e,
                        writeable: !1
                    }), registry[e] = {
                        klass: r,
                        omit: i.omit || [],
                        shallow: i.shallow || []
                    };
                }
                function serialize(e, r) {
                    if (null === e || void 0 === e || 'boolean' == typeof e || 'number' == typeof e || 'string' == typeof e || e instanceof Boolean || e instanceof Number || e instanceof String || e instanceof Date || e instanceof RegExp) {
                        return e;
                    }
                    if (e instanceof ArrayBuffer) {
                        return r && r.push(e), e;
                    }
                    if (ArrayBuffer.isView(e)) {
                        var i = e;
                        return r && r.push(i.buffer), i;
                    }
                    if (e instanceof ImageData) {
                        return r && r.push(e.data.buffer), e;
                    }
                    if (Array.isArray(e)) {
                        for (var s = [], o = 0, t = e; o < t.length; o += 1) {
                            var n = t[o];
                            s.push(serialize(n, r));
                        }
                        return s;
                    }
                    if ('object' == typeof e) {
                        var a = e.constructor, f = a._classRegistryKey;
                        if (!f) {
                            throw new Error('can\'t serialize object of unregistered class');
                        }
                        var l = {};
                        if (a.serialize) {
                            l._serialized = a.serialize(e, r);
                        } else {
                            for (var p in e) {
                                if (e.hasOwnProperty(p) && !(registry[f].omit.indexOf(p) >= 0)) {
                                    var u = e[p];
                                    l[p] = registry[f].shallow.indexOf(p) >= 0 ? u : serialize(u, r);
                                }
                            }
                        }
                        return {
                            name: f,
                            properties: l
                        };
                    }
                    throw new Error('can\'t serialize object of type ' + typeof e);
                }
                function deserialize(e) {
                    if (null === e || void 0 === e || 'boolean' == typeof e || 'number' == typeof e || 'string' == typeof e || e instanceof Boolean || e instanceof Number || e instanceof String || e instanceof Date || e instanceof RegExp || e instanceof ArrayBuffer || ArrayBuffer.isView(e) || e instanceof ImageData) {
                        return e;
                    }
                    if (Array.isArray(e)) {
                        return e.map(function (e) {
                            return deserialize(e);
                        });
                    }
                    if ('object' == typeof e) {
                        var r = e, i = r.name, s = r.properties;
                        if (!i) {
                            throw new Error('can\'t deserialize object of anonymous class');
                        }
                        var o = registry[i], t = o.klass;
                        if (!t) {
                            throw new Error('can\'t deserialize unregistered class ' + i);
                        }
                        if (t.deserialize) {
                            return t.deserialize(s._serialized);
                        }
                        for (var n = Object.create(t.prototype), a = 0, f = Object.keys(s); a < f.length; a += 1) {
                            var l = f[a];
                            n[l] = registry[i].shallow.indexOf(l) >= 0 ? s[l] : deserialize(s[l]);
                        }
                        return n;
                    }
                    throw new Error('can\'t deserialize object of type ' + typeof e);
                }
                var Grid = _dereq_('grid-index'), Color = _dereq_('../style-spec/util/color'), ref = _dereq_('../style-spec/expression'), StylePropertyFunction = ref.StylePropertyFunction, StyleExpression = ref.StyleExpression, StyleExpressionWithErrorHandling = ref.StyleExpressionWithErrorHandling, ZoomDependentExpression = ref.ZoomDependentExpression, ZoomConstantExpression = ref.ZoomConstantExpression, ref$1 = _dereq_('../style-spec/expression/compound_expression'), CompoundExpression = ref$1.CompoundExpression, expressions = _dereq_('../style-spec/expression/definitions'), ref$2 = _dereq_('./window'), ImageData = ref$2.ImageData, registry = {};
                register('Object', Object), Grid.serialize = function (e, r) {
                    var i = e.toArrayBuffer();
                    return r && r.push(i), i;
                }, Grid.deserialize = function (e) {
                    return new Grid(e);
                }, register('Grid', Grid), register('Color', Color), register('StylePropertyFunction', StylePropertyFunction), register('StyleExpression', StyleExpression, { omit: ['_evaluator'] }), register('StyleExpressionWithErrorHandling', StyleExpressionWithErrorHandling, { omit: ['_evaluator'] }), register('ZoomDependentExpression', ZoomDependentExpression), register('ZoomConstantExpression', ZoomConstantExpression), register('CompoundExpression', CompoundExpression, { omit: ['_evaluate'] });
                for (var name in expressions) {
                    expressions[name]._classRegistryKey || register('Expression_' + name, expressions[name]);
                }
                module.exports = {
                    register: register,
                    serialize: serialize,
                    deserialize: deserialize
                };
            },
            {
                '../style-spec/expression': 139,
                '../style-spec/expression/compound_expression': 123,
                '../style-spec/expression/definitions': 131,
                '../style-spec/util/color': 153,
                './window': 254,
                'grid-index': 24
            }
        ],
        279: [
            function (_dereq_, module, exports) {
                'use strict';
                var WebWorker = _dereq_('./web_worker'), WorkerPool = function () {
                        this.active = {};
                    };
                WorkerPool.prototype.acquire = function (r) {
                    var e = this;
                    if (!this.workers) {
                        var o = _dereq_('../').workerCount;
                        for (this.workers = []; this.workers.length < o;) {
                            e.workers.push(new WebWorker());
                        }
                    }
                    return this.active[r] = !0, this.workers.slice();
                }, WorkerPool.prototype.release = function (r) {
                    delete this.active[r], 0 === Object.keys(this.active).length && (this.workers.forEach(function (r) {
                        r.terminate();
                    }), this.workers = null);
                }, module.exports = WorkerPool;
            },
            {
                '../': 73,
                './web_worker': 253
            }
        ]
    }, {}, [73])(73);
}));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],15:[function(require,module,exports){
var rootPosition = { left: 0, top: 0 }

module.exports = mouseEventOffset
function mouseEventOffset (ev, target, out) {
  target = target || ev.currentTarget || ev.srcElement
  if (!Array.isArray(out)) {
    out = [ 0, 0 ]
  }
  var cx = ev.clientX || 0
  var cy = ev.clientY || 0
  var rect = getBoundingClientOffset(target)
  out[0] = cx - rect.left
  out[1] = cy - rect.top
  return out
}

function getBoundingClientOffset (element) {
  if (element === window ||
      element === document ||
      element === document.body) {
    return rootPosition
  } else {
    return element.getBoundingClientRect()
  }
}

},{}],16:[function(require,module,exports){
/*
 * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc
 * @license MIT
 * @preserve Project Home: https://github.com/voidqk/polybooljs
 */

var BuildLog = require('./lib/build-log');
var Epsilon = require('./lib/epsilon');
var Intersecter = require('./lib/intersecter');
var SegmentChainer = require('./lib/segment-chainer');
var SegmentSelector = require('./lib/segment-selector');
var GeoJSON = require('./lib/geojson');

var buildLog = false;
var epsilon = Epsilon();

var PolyBool;
PolyBool = {
	// getter/setter for buildLog
	buildLog: function(bl){
		if (bl === true)
			buildLog = BuildLog();
		else if (bl === false)
			buildLog = false;
		return buildLog === false ? false : buildLog.list;
	},
	// getter/setter for epsilon
	epsilon: function(v){
		return epsilon.epsilon(v);
	},

	// core API
	segments: function(poly){
		var i = Intersecter(true, epsilon, buildLog);
		poly.regions.forEach(i.addRegion);
		return {
			segments: i.calculate(poly.inverted),
			inverted: poly.inverted
		};
	},
	combine: function(segments1, segments2){
		var i3 = Intersecter(false, epsilon, buildLog);
		return {
			combined: i3.calculate(
				segments1.segments, segments1.inverted,
				segments2.segments, segments2.inverted
			),
			inverted1: segments1.inverted,
			inverted2: segments2.inverted
		};
	},
	selectUnion: function(combined){
		return {
			segments: SegmentSelector.union(combined.combined, buildLog),
			inverted: combined.inverted1 || combined.inverted2
		}
	},
	selectIntersect: function(combined){
		return {
			segments: SegmentSelector.intersect(combined.combined, buildLog),
			inverted: combined.inverted1 && combined.inverted2
		}
	},
	selectDifference: function(combined){
		return {
			segments: SegmentSelector.difference(combined.combined, buildLog),
			inverted: combined.inverted1 && !combined.inverted2
		}
	},
	selectDifferenceRev: function(combined){
		return {
			segments: SegmentSelector.differenceRev(combined.combined, buildLog),
			inverted: !combined.inverted1 && combined.inverted2
		}
	},
	selectXor: function(combined){
		return {
			segments: SegmentSelector.xor(combined.combined, buildLog),
			inverted: combined.inverted1 !== combined.inverted2
		}
	},
	polygon: function(segments){
		return {
			regions: SegmentChainer(segments.segments, epsilon, buildLog),
			inverted: segments.inverted
		};
	},

	// GeoJSON converters
	polygonFromGeoJSON: function(geojson){
		return GeoJSON.toPolygon(PolyBool, geojson);
	},
	polygonToGeoJSON: function(poly){
		return GeoJSON.fromPolygon(PolyBool, epsilon, poly);
	},

	// helper functions for common operations
	union: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectUnion);
	},
	intersect: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectIntersect);
	},
	difference: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectDifference);
	},
	differenceRev: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectDifferenceRev);
	},
	xor: function(poly1, poly2){
		return operate(poly1, poly2, PolyBool.selectXor);
	}
};

function operate(poly1, poly2, selector){
	var seg1 = PolyBool.segments(poly1);
	var seg2 = PolyBool.segments(poly2);
	var comb = PolyBool.combine(seg1, seg2);
	var seg3 = selector(comb);
	return PolyBool.polygon(seg3);
}

if (typeof window === 'object')
	window.PolyBool = PolyBool;

module.exports = PolyBool;

},{"./lib/build-log":17,"./lib/epsilon":18,"./lib/geojson":19,"./lib/intersecter":20,"./lib/segment-chainer":22,"./lib/segment-selector":23}],17:[function(require,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// used strictly for logging the processing of the algorithm... only useful if you intend on
// looking under the covers (for pretty UI's or debugging)
//

function BuildLog(){
	var my;
	var nextSegmentId = 0;
	var curVert = false;

	function push(type, data){
		my.list.push({
			type: type,
			data: data ? JSON.parse(JSON.stringify(data)) : void 0
		});
		return my;
	}

	my = {
		list: [],
		segmentId: function(){
			return nextSegmentId++;
		},
		checkIntersection: function(seg1, seg2){
			return push('check', { seg1: seg1, seg2: seg2 });
		},
		segmentChop: function(seg, end){
			push('div_seg', { seg: seg, pt: end });
			return push('chop', { seg: seg, pt: end });
		},
		statusRemove: function(seg){
			return push('pop_seg', { seg: seg });
		},
		segmentUpdate: function(seg){
			return push('seg_update', { seg: seg });
		},
		segmentNew: function(seg, primary){
			return push('new_seg', { seg: seg, primary: primary });
		},
		segmentRemove: function(seg){
			return push('rem_seg', { seg: seg });
		},
		tempStatus: function(seg, above, below){
			return push('temp_status', { seg: seg, above: above, below: below });
		},
		rewind: function(seg){
			return push('rewind', { seg: seg });
		},
		status: function(seg, above, below){
			return push('status', { seg: seg, above: above, below: below });
		},
		vert: function(x){
			if (x === curVert)
				return my;
			curVert = x;
			return push('vert', { x: x });
		},
		log: function(data){
			if (typeof data !== 'string')
				data = JSON.stringify(data, false, '  ');
			return push('log', { txt: data });
		},
		reset: function(){
			return push('reset');
		},
		selected: function(segs){
			return push('selected', { segs: segs });
		},
		chainStart: function(seg){
			return push('chain_start', { seg: seg });
		},
		chainRemoveHead: function(index, pt){
			return push('chain_rem_head', { index: index, pt: pt });
		},
		chainRemoveTail: function(index, pt){
			return push('chain_rem_tail', { index: index, pt: pt });
		},
		chainNew: function(pt1, pt2){
			return push('chain_new', { pt1: pt1, pt2: pt2 });
		},
		chainMatch: function(index){
			return push('chain_match', { index: index });
		},
		chainClose: function(index){
			return push('chain_close', { index: index });
		},
		chainAddHead: function(index, pt){
			return push('chain_add_head', { index: index, pt: pt });
		},
		chainAddTail: function(index, pt){
			return push('chain_add_tail', { index: index, pt: pt, });
		},
		chainConnect: function(index1, index2){
			return push('chain_con', { index1: index1, index2: index2 });
		},
		chainReverse: function(index){
			return push('chain_rev', { index: index });
		},
		chainJoin: function(index1, index2){
			return push('chain_join', { index1: index1, index2: index2 });
		},
		done: function(){
			return push('done');
		}
	};
	return my;
}

module.exports = BuildLog;

},{}],18:[function(require,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// provides the raw computation functions that takes epsilon into account
//
// zero is defined to be between (-epsilon, epsilon) exclusive
//

function Epsilon(eps){
	if (typeof eps !== 'number')
		eps = 0.0000000001; // sane default? sure why not
	var my = {
		epsilon: function(v){
			if (typeof v === 'number')
				eps = v;
			return eps;
		},
		pointAboveOrOnLine: function(pt, left, right){
			var Ax = left[0];
			var Ay = left[1];
			var Bx = right[0];
			var By = right[1];
			var Cx = pt[0];
			var Cy = pt[1];
			return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps;
		},
		pointBetween: function(p, left, right){
			// p must be collinear with left->right
			// returns false if p == left, p == right, or left == right
			var d_py_ly = p[1] - left[1];
			var d_rx_lx = right[0] - left[0];
			var d_px_lx = p[0] - left[0];
			var d_ry_ly = right[1] - left[1];

			var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly;
			// if `dot` is 0, then `p` == `left` or `left` == `right` (reject)
			// if `dot` is less than 0, then `p` is to the left of `left` (reject)
			if (dot < eps)
				return false;

			var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly;
			// if `dot` > `sqlen`, then `p` is to the right of `right` (reject)
			// therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject)
			if (dot - sqlen > -eps)
				return false;

			return true;
		},
		pointsSameX: function(p1, p2){
			return Math.abs(p1[0] - p2[0]) < eps;
		},
		pointsSameY: function(p1, p2){
			return Math.abs(p1[1] - p2[1]) < eps;
		},
		pointsSame: function(p1, p2){
			return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2);
		},
		pointsCompare: function(p1, p2){
			// returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal
			if (my.pointsSameX(p1, p2))
				return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1);
			return p1[0] < p2[0] ? -1 : 1;
		},
		pointsCollinear: function(pt1, pt2, pt3){
			// does pt1->pt2->pt3 make a straight line?
			// essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3)
			// if slopes are equal, then they must be collinear, because they share pt2
			var dx1 = pt1[0] - pt2[0];
			var dy1 = pt1[1] - pt2[1];
			var dx2 = pt2[0] - pt3[0];
			var dy2 = pt2[1] - pt3[1];
			return Math.abs(dx1 * dy2 - dx2 * dy1) < eps;
		},
		linesIntersect: function(a0, a1, b0, b1){
			// returns false if the lines are coincident (e.g., parallel or on top of each other)
			//
			// returns an object if the lines intersect:
			//   {
			//     pt: [x, y],    where the intersection point is at
			//     alongA: where intersection point is along A,
			//     alongB: where intersection point is along B
			//   }
			//
			//  alongA and alongB will each be one of: -2, -1, 0, 1, 2
			//
			//  with the following meaning:
			//
			//    -2   intersection point is before segment's first point
			//    -1   intersection point is directly on segment's first point
			//     0   intersection point is between segment's first and second points (exclusive)
			//     1   intersection point is directly on segment's second point
			//     2   intersection point is after segment's second point
			var adx = a1[0] - a0[0];
			var ady = a1[1] - a0[1];
			var bdx = b1[0] - b0[0];
			var bdy = b1[1] - b0[1];

			var axb = adx * bdy - ady * bdx;
			if (Math.abs(axb) < eps)
				return false; // lines are coincident

			var dx = a0[0] - b0[0];
			var dy = a0[1] - b0[1];

			var A = (bdx * dy - bdy * dx) / axb;
			var B = (adx * dy - ady * dx) / axb;

			var ret = {
				alongA: 0,
				alongB: 0,
				pt: [
					a0[0] + A * adx,
					a0[1] + A * ady
				]
			};

			// categorize where intersection point is along A and B

			if (A <= -eps)
				ret.alongA = -2;
			else if (A < eps)
				ret.alongA = -1;
			else if (A - 1 <= -eps)
				ret.alongA = 0;
			else if (A - 1 < eps)
				ret.alongA = 1;
			else
				ret.alongA = 2;

			if (B <= -eps)
				ret.alongB = -2;
			else if (B < eps)
				ret.alongB = -1;
			else if (B - 1 <= -eps)
				ret.alongB = 0;
			else if (B - 1 < eps)
				ret.alongB = 1;
			else
				ret.alongB = 2;

			return ret;
		},
		pointInsideRegion: function(pt, region){
			var x = pt[0];
			var y = pt[1];
			var last_x = region[region.length - 1][0];
			var last_y = region[region.length - 1][1];
			var inside = false;
			for (var i = 0; i < region.length; i++){
				var curr_x = region[i][0];
				var curr_y = region[i][1];

				// if y is between curr_y and last_y, and
				// x is to the right of the boundary created by the line
				if ((curr_y - y > eps) != (last_y - y > eps) &&
					(last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps)
					inside = !inside

				last_x = curr_x;
				last_y = curr_y;
			}
			return inside;
		}
	};
	return my;
}

module.exports = Epsilon;

},{}],19:[function(require,module,exports){
// (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon)
//

var GeoJSON = {
	// convert a GeoJSON object to a PolyBool polygon
	toPolygon: function(PolyBool, geojson){

		// converts list of LineString's to segments
		function GeoPoly(coords){
			// check for empty coords
			if (coords.length <= 0)
				return PolyBool.segments({ inverted: false, regions: [] });

			// convert LineString to segments
			function LineString(ls){
				// remove tail which should be the same as head
				var reg = ls.slice(0, ls.length - 1);
				return PolyBool.segments({ inverted: false, regions: [reg] });
			}

			// the first LineString is considered the outside
			var out = LineString(coords[0]);

			// the rest of the LineStrings are considered interior holes, so subtract them from the
			// current result
			for (var i = 1; i < coords.length; i++)
				out = PolyBool.selectDifference(PolyBool.combine(out, LineString(coords[i])));

			return out;
		}

		if (geojson.type === 'Polygon'){
			// single polygon, so just convert it and we're done
			return PolyBool.polygon(GeoPoly(geojson.coordinates));
		}
		else if (geojson.type === 'MultiPolygon'){
			// multiple polygons, so union all the polygons together
			var out = PolyBool.segments({ inverted: false, regions: [] });
			for (var i = 0; i < geojson.coordinates.length; i++)
				out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i])));
			return PolyBool.polygon(out);
		}
		throw new Error('PolyBool: Cannot convert GeoJSON object to PolyBool polygon');
	},

	// convert a PolyBool polygon to a GeoJSON object
	fromPolygon: function(PolyBool, eps, poly){
		// make sure out polygon is clean
		poly = PolyBool.polygon(PolyBool.segments(poly));

		// test if r1 is inside r2
		function regionInsideRegion(r1, r2){
			// we're guaranteed no lines intersect (because the polygon is clean), but a vertex
			// could be on the edge -- so we just average pt[0] and pt[1] to produce a point on the
			// edge of the first line, which cannot be on an edge
			return eps.pointInsideRegion([
				(r1[0][0] + r1[1][0]) * 0.5,
				(r1[0][1] + r1[1][1]) * 0.5
			], r2);
		}

		// calculate inside heirarchy
		//
		//  _____________________   _______    roots -> A       -> F
		// |          A          | |   F   |            |          |
		// |  _______   _______  | |  ___  |            +-- B      +-- G
		// | |   B   | |   C   | | | |   | |            |   |
		// | |  ___  | |  ___  | | | |   | |            |   +-- D
		// | | | D | | | | E | | | | | G | |            |
		// | | |___| | | |___| | | | |   | |            +-- C
		// | |_______| |_______| | | |___| |                |
		// |_____________________| |_______|                +-- E

		function newNode(region){
			return {
				region: region,
				children: []
			};
		}

		var roots = newNode(null);

		function addChild(root, region){
			// first check if we're inside any children
			for (var i = 0; i < root.children.length; i++){
				var child = root.children[i];
				if (regionInsideRegion(region, child.region)){
					// we are, so insert inside them instead
					addChild(child, region);
					return;
				}
			}

			// not inside any children, so check to see if any children are inside us
			var node = newNode(region);
			for (var i = 0; i < root.children.length; i++){
				var child = root.children[i];
				if (regionInsideRegion(child.region, region)){
					// oops... move the child beneath us, and remove them from root
					node.children.push(child);
					root.children.splice(i, 1);
					i--;
				}
			}

			// now we can add ourselves
			root.children.push(node);
		}

		// add all regions to the root
		for (var i = 0; i < poly.regions.length; i++){
			var region = poly.regions[i];
			if (region.length < 3) // regions must have at least 3 points (sanity check)
				continue;
			addChild(roots, region);
		}

		// with our heirarchy, we can distinguish between exterior borders, and interior holes
		// the root nodes are exterior, children are interior, children's children are exterior,
		// children's children's children are interior, etc

		// while we're at it, exteriors are counter-clockwise, and interiors are clockwise

		function forceWinding(region, clockwise){
			// first, see if we're clockwise or counter-clockwise
			// https://en.wikipedia.org/wiki/Shoelace_formula
			var winding = 0;
			var last_x = region[region.length - 1][0];
			var last_y = region[region.length - 1][1];
			var copy = [];
			for (var i = 0; i < region.length; i++){
				var curr_x = region[i][0];
				var curr_y = region[i][1];
				copy.push([curr_x, curr_y]); // create a copy while we're at it
				winding += curr_y * last_x - curr_x * last_y;
				last_x = curr_x;
				last_y = curr_y;
			}
			// this assumes Cartesian coordinates (Y is positive going up)
			var isclockwise = winding < 0;
			if (isclockwise !== clockwise)
				copy.reverse();
			// while we're here, the last point must be the first point...
			copy.push([copy[0][0], copy[0][1]]);
			return copy;
		}

		var geopolys = [];

		function addExterior(node){
			var poly = [forceWinding(node.region, false)];
			geopolys.push(poly);
			// children of exteriors are interior
			for (var i = 0; i < node.children.length; i++)
				poly.push(getInterior(node.children[i]));
		}

		function getInterior(node){
			// children of interiors are exterior
			for (var i = 0; i < node.children.length; i++)
				addExterior(node.children[i]);
			// return the clockwise interior
			return forceWinding(node.region, true);
		}

		// root nodes are exterior
		for (var i = 0; i < roots.children.length; i++)
			addExterior(roots.children[i]);

		// lastly, construct the approrpriate GeoJSON object

		if (geopolys.length <= 0) // empty GeoJSON Polygon
			return { type: 'Polygon', coordinates: [] };
		if (geopolys.length == 1) // use a GeoJSON Polygon
			return { type: 'Polygon', coordinates: geopolys[0] };
		return { // otherwise, use a GeoJSON MultiPolygon
			type: 'MultiPolygon',
			coordinates: geopolys
		};
	}
};

module.exports = GeoJSON;

},{}],20:[function(require,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// this is the core work-horse
//

var LinkedList = require('./linked-list');

function Intersecter(selfIntersection, eps, buildLog){
	// selfIntersection is true/false depending on the phase of the overall algorithm

	//
	// segment creation
	//

	function segmentNew(start, end){
		return {
			id: buildLog ? buildLog.segmentId() : -1,
			start: start,
			end: end,
			myFill: {
				above: null, // is there fill above us?
				below: null  // is there fill below us?
			},
			otherFill: null
		};
	}

	function segmentCopy(start, end, seg){
		return {
			id: buildLog ? buildLog.segmentId() : -1,
			start: start,
			end: end,
			myFill: {
				above: seg.myFill.above,
				below: seg.myFill.below
			},
			otherFill: null
		};
	}

	//
	// event logic
	//

	var event_root = LinkedList.create();

	function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){
		// compare the selected points first
		var comp = eps.pointsCompare(p1_1, p2_1);
		if (comp !== 0)
			return comp;
		// the selected points are the same

		if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too...
			return 0; // then the segments are equal

		if (p1_isStart !== p2_isStart) // if one is a start and the other isn't...
			return p1_isStart ? 1 : -1; // favor the one that isn't the start

		// otherwise, we'll have to calculate which one is below the other manually
		return eps.pointAboveOrOnLine(p1_2,
			p2_isStart ? p2_1 : p2_2, // order matters
			p2_isStart ? p2_2 : p2_1
		) ? 1 : -1;
	}

	function eventAdd(ev, other_pt){
		event_root.insertBefore(ev, function(here){
			// should ev be inserted before here?
			var comp = eventCompare(
				ev  .isStart, ev  .pt,      other_pt,
				here.isStart, here.pt, here.other.pt
			);
			return comp < 0;
		});
	}

	function eventAddSegmentStart(seg, primary){
		var ev_start = LinkedList.node({
			isStart: true,
			pt: seg.start,
			seg: seg,
			primary: primary,
			other: null,
			status: null
		});
		eventAdd(ev_start, seg.end);
		return ev_start;
	}

	function eventAddSegmentEnd(ev_start, seg, primary){
		var ev_end = LinkedList.node({
			isStart: false,
			pt: seg.end,
			seg: seg,
			primary: primary,
			other: ev_start,
			status: null
		});
		ev_start.other = ev_end;
		eventAdd(ev_end, ev_start.pt);
	}

	function eventAddSegment(seg, primary){
		var ev_start = eventAddSegmentStart(seg, primary);
		eventAddSegmentEnd(ev_start, seg, primary);
		return ev_start;
	}

	function eventUpdateEnd(ev, end){
		// slides an end backwards
		//   (start)------------(end)    to:
		//   (start)---(end)

		if (buildLog)
			buildLog.segmentChop(ev.seg, end);

		ev.other.remove();
		ev.seg.end = end;
		ev.other.pt = end;
		eventAdd(ev.other, ev.pt);
	}

	function eventDivide(ev, pt){
		var ns = segmentCopy(pt, ev.seg.end, ev.seg);
		eventUpdateEnd(ev, pt);
		return eventAddSegment(ns, ev.primary);
	}

	function calculate(primaryPolyInverted, secondaryPolyInverted){
		// if selfIntersection is true then there is no secondary polygon, so that isn't used

		//
		// status logic
		//

		var status_root = LinkedList.create();

		function statusCompare(ev1, ev2){
			var a1 = ev1.seg.start;
			var a2 = ev1.seg.end;
			var b1 = ev2.seg.start;
			var b2 = ev2.seg.end;

			if (eps.pointsCollinear(a1, b1, b2)){
				if (eps.pointsCollinear(a2, b1, b2))
					return 1;//eventCompare(true, a1, a2, true, b1, b2);
				return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1;
			}
			return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1;
		}

		function statusFindSurrounding(ev){
			return status_root.findTransition(function(here){
				var comp = statusCompare(ev, here.ev);
				return comp > 0;
			});
		}

		function checkIntersection(ev1, ev2){
			// returns the segment equal to ev1, or false if nothing equal

			var seg1 = ev1.seg;
			var seg2 = ev2.seg;
			var a1 = seg1.start;
			var a2 = seg1.end;
			var b1 = seg2.start;
			var b2 = seg2.end;

			if (buildLog)
				buildLog.checkIntersection(seg1, seg2);

			var i = eps.linesIntersect(a1, a2, b1, b2);

			if (i === false){
				// segments are parallel or coincident

				// if points aren't collinear, then the segments are parallel, so no intersections
				if (!eps.pointsCollinear(a1, a2, b1))
					return false;
				// otherwise, segments are on top of each other somehow (aka coincident)

				if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1))
					return false; // segments touch at endpoints... no intersection

				var a1_equ_b1 = eps.pointsSame(a1, b1);
				var a2_equ_b2 = eps.pointsSame(a2, b2);

				if (a1_equ_b1 && a2_equ_b2)
					return ev2; // segments are exactly equal

				var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2);
				var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2);

				// handy for debugging:
				// buildLog.log({
				//	a1_equ_b1: a1_equ_b1,
				//	a2_equ_b2: a2_equ_b2,
				//	a1_between: a1_between,
				//	a2_between: a2_between
				// });

				if (a1_equ_b1){
					if (a2_between){
						//  (a1)---(a2)
						//  (b1)----------(b2)
						eventDivide(ev2, a2);
					}
					else{
						//  (a1)----------(a2)
						//  (b1)---(b2)
						eventDivide(ev1, b2);
					}
					return ev2;
				}
				else if (a1_between){
					if (!a2_equ_b2){
						// make a2 equal to b2
						if (a2_between){
							//         (a1)---(a2)
							//  (b1)-----------------(b2)
							eventDivide(ev2, a2);
						}
						else{
							//         (a1)----------(a2)
							//  (b1)----------(b2)
							eventDivide(ev1, b2);
						}
					}

					//         (a1)---(a2)
					//  (b1)----------(b2)
					eventDivide(ev2, a1);
				}
			}
			else{
				// otherwise, lines intersect at i.pt, which may or may not be between the endpoints

				// is A divided between its endpoints? (exclusive)
				if (i.alongA === 0){
					if (i.alongB === -1) // yes, at exactly b1
						eventDivide(ev1, b1);
					else if (i.alongB === 0) // yes, somewhere between B's endpoints
						eventDivide(ev1, i.pt);
					else if (i.alongB === 1) // yes, at exactly b2
						eventDivide(ev1, b2);
				}

				// is B divided between its endpoints? (exclusive)
				if (i.alongB === 0){
					if (i.alongA === -1) // yes, at exactly a1
						eventDivide(ev2, a1);
					else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive)
						eventDivide(ev2, i.pt);
					else if (i.alongA === 1) // yes, at exactly a2
						eventDivide(ev2, a2);
				}
			}
			return false;
		}

		//
		// main event loop
		//
		var segments = [];
		while (!event_root.isEmpty()){
			var ev = event_root.getHead();

			if (buildLog)
				buildLog.vert(ev.pt[0]);

			if (ev.isStart){

				if (buildLog)
					buildLog.segmentNew(ev.seg, ev.primary);

				var surrounding = statusFindSurrounding(ev);
				var above = surrounding.before ? surrounding.before.ev : null;
				var below = surrounding.after ? surrounding.after.ev : null;

				if (buildLog){
					buildLog.tempStatus(
						ev.seg,
						above ? above.seg : false,
						below ? below.seg : false
					);
				}

				function checkBothIntersections(){
					if (above){
						var eve = checkIntersection(ev, above);
						if (eve)
							return eve;
					}
					if (below)
						return checkIntersection(ev, below);
					return false;
				}

				var eve = checkBothIntersections();
				if (eve){
					// ev and eve are equal
					// we'll keep eve and throw away ev

					// merge ev.seg's fill information into eve.seg

					if (selfIntersection){
						var toggle; // are we a toggling edge?
						if (ev.seg.myFill.below === null)
							toggle = true;
						else
							toggle = ev.seg.myFill.above !== ev.seg.myFill.below;

						// merge two segments that belong to the same polygon
						// think of this as sandwiching two segments together, where `eve.seg` is
						// the bottom -- this will cause the above fill flag to toggle
						if (toggle)
							eve.seg.myFill.above = !eve.seg.myFill.above;
					}
					else{
						// merge two segments that belong to different polygons
						// each segment has distinct knowledge, so no special logic is needed
						// note that this can only happen once per segment in this phase, because we
						// are guaranteed that all self-intersections are gone
						eve.seg.otherFill = ev.seg.myFill;
					}

					if (buildLog)
						buildLog.segmentUpdate(eve.seg);

					ev.other.remove();
					ev.remove();
				}

				if (event_root.getHead() !== ev){
					// something was inserted before us in the event queue, so loop back around and
					// process it before continuing
					if (buildLog)
						buildLog.rewind(ev.seg);
					continue;
				}

				//
				// calculate fill flags
				//
				if (selfIntersection){
					var toggle; // are we a toggling edge?
					if (ev.seg.myFill.below === null) // if we are a new segment...
						toggle = true; // then we toggle
					else // we are a segment that has previous knowledge from a division
						toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle

					// next, calculate whether we are filled below us
					if (!below){ // if nothing is below us...
						// we are filled below us if the polygon is inverted
						ev.seg.myFill.below = primaryPolyInverted;
					}
					else{
						// otherwise, we know the answer -- it's the same if whatever is below
						// us is filled above it
						ev.seg.myFill.below = below.seg.myFill.above;
					}

					// since now we know if we're filled below us, we can calculate whether
					// we're filled above us by applying toggle to whatever is below us
					if (toggle)
						ev.seg.myFill.above = !ev.seg.myFill.below;
					else
						ev.seg.myFill.above = ev.seg.myFill.below;
				}
				else{
					// now we fill in any missing transition information, since we are all-knowing
					// at this point

					if (ev.seg.otherFill === null){
						// if we don't have other information, then we need to figure out if we're
						// inside the other polygon
						var inside;
						if (!below){
							// if nothing is below us, then we're inside if the other polygon is
							// inverted
							inside =
								ev.primary ? secondaryPolyInverted : primaryPolyInverted;
						}
						else{ // otherwise, something is below us
							// so copy the below segment's other polygon's above
							if (ev.primary === below.primary)
								inside = below.seg.otherFill.above;
							else
								inside = below.seg.myFill.above;
						}
						ev.seg.otherFill = {
							above: inside,
							below: inside
						};
					}
				}

				if (buildLog){
					buildLog.status(
						ev.seg,
						above ? above.seg : false,
						below ? below.seg : false
					);
				}

				// insert the status and remember it for later removal
				ev.other.status = surrounding.insert(LinkedList.node({ ev: ev }));
			}
			else{
				var st = ev.status;

				if (st === null){
					throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' +
						'probably too small or too large');
				}

				// removing the status will create two new adjacent edges, so we'll need to check
				// for those
				if (status_root.exists(st.prev) && status_root.exists(st.next))
					checkIntersection(st.prev.ev, st.next.ev);

				if (buildLog)
					buildLog.statusRemove(st.ev.seg);

				// remove the status
				st.remove();

				// if we've reached this point, we've calculated everything there is to know, so
				// save the segment for reporting
				if (!ev.primary){
					// make sure `seg.myFill` actually points to the primary polygon though
					var s = ev.seg.myFill;
					ev.seg.myFill = ev.seg.otherFill;
					ev.seg.otherFill = s;
				}
				segments.push(ev.seg);
			}

			// remove the event and continue
			event_root.getHead().remove();
		}

		if (buildLog)
			buildLog.done();

		return segments;
	}

	// return the appropriate API depending on what we're doing
	if (!selfIntersection){
		// performing combination of polygons, so only deal with already-processed segments
		return {
			calculate: function(segments1, inverted1, segments2, inverted2){
				// segmentsX come from the self-intersection API, or this API
				// invertedX is whether we treat that list of segments as an inverted polygon or not
				// returns segments that can be used for further operations
				segments1.forEach(function(seg){
					eventAddSegment(segmentCopy(seg.start, seg.end, seg), true);
				});
				segments2.forEach(function(seg){
					eventAddSegment(segmentCopy(seg.start, seg.end, seg), false);
				});
				return calculate(inverted1, inverted2);
			}
		};
	}

	// otherwise, performing self-intersection, so deal with regions
	return {
		addRegion: function(region){
			// regions are a list of points:
			//  [ [0, 0], [100, 0], [50, 100] ]
			// you can add multiple regions before running calculate
			var pt1;
			var pt2 = region[region.length - 1];
			for (var i = 0; i < region.length; i++){
				pt1 = pt2;
				pt2 = region[i];

				var forward = eps.pointsCompare(pt1, pt2);
				if (forward === 0) // points are equal, so we have a zero-length segment
					continue; // just skip it

				eventAddSegment(
					segmentNew(
						forward < 0 ? pt1 : pt2,
						forward < 0 ? pt2 : pt1
					),
					true
				);
			}
		},
		calculate: function(inverted){
			// is the polygon inverted?
			// returns segments
			return calculate(inverted, false);
		}
	};
}

module.exports = Intersecter;

},{"./linked-list":21}],21:[function(require,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// simple linked list implementation that allows you to traverse down nodes and save positions
//

var LinkedList = {
	create: function(){
		var my = {
			root: { root: true, next: null },
			exists: function(node){
				if (node === null || node === my.root)
					return false;
				return true;
			},
			isEmpty: function(){
				return my.root.next === null;
			},
			getHead: function(){
				return my.root.next;
			},
			insertBefore: function(node, check){
				var last = my.root;
				var here = my.root.next;
				while (here !== null){
					if (check(here)){
						node.prev = here.prev;
						node.next = here;
						here.prev.next = node;
						here.prev = node;
						return;
					}
					last = here;
					here = here.next;
				}
				last.next = node;
				node.prev = last;
				node.next = null;
			},
			findTransition: function(check){
				var prev = my.root;
				var here = my.root.next;
				while (here !== null){
					if (check(here))
						break;
					prev = here;
					here = here.next;
				}
				return {
					before: prev === my.root ? null : prev,
					after: here,
					insert: function(node){
						node.prev = prev;
						node.next = here;
						prev.next = node;
						if (here !== null)
							here.prev = node;
						return node;
					}
				};
			}
		};
		return my;
	},
	node: function(data){
		data.prev = null;
		data.next = null;
		data.remove = function(){
			data.prev.next = data.next;
			if (data.next)
				data.next.prev = data.prev;
			data.prev = null;
			data.next = null;
		};
		return data;
	}
};

module.exports = LinkedList;

},{}],22:[function(require,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// converts a list of segments into a list of regions, while also removing unnecessary verticies
//

function SegmentChainer(segments, eps, buildLog){
	var chains = [];
	var regions = [];

	segments.forEach(function(seg){
		var pt1 = seg.start;
		var pt2 = seg.end;
		if (eps.pointsSame(pt1, pt2)){
			console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' +
				'probably too small or too large');
			return;
		}

		if (buildLog)
			buildLog.chainStart(seg);

		// search for two chains that this segment matches
		var first_match = {
			index: 0,
			matches_head: false,
			matches_pt1: false
		};
		var second_match = {
			index: 0,
			matches_head: false,
			matches_pt1: false
		};
		var next_match = first_match;
		function setMatch(index, matches_head, matches_pt1){
			// return true if we've matched twice
			next_match.index = index;
			next_match.matches_head = matches_head;
			next_match.matches_pt1 = matches_pt1;
			if (next_match === first_match){
				next_match = second_match;
				return false;
			}
			next_match = null;
			return true; // we've matched twice, we're done here
		}
		for (var i = 0; i < chains.length; i++){
			var chain = chains[i];
			var head  = chain[0];
			var head2 = chain[1];
			var tail  = chain[chain.length - 1];
			var tail2 = chain[chain.length - 2];
			if (eps.pointsSame(head, pt1)){
				if (setMatch(i, true, true))
					break;
			}
			else if (eps.pointsSame(head, pt2)){
				if (setMatch(i, true, false))
					break;
			}
			else if (eps.pointsSame(tail, pt1)){
				if (setMatch(i, false, true))
					break;
			}
			else if (eps.pointsSame(tail, pt2)){
				if (setMatch(i, false, false))
					break;
			}
		}

		if (next_match === first_match){
			// we didn't match anything, so create a new chain
			chains.push([ pt1, pt2 ]);
			if (buildLog)
				buildLog.chainNew(pt1, pt2);
			return;
		}

		if (next_match === second_match){
			// we matched a single chain

			if (buildLog)
				buildLog.chainMatch(first_match.index);

			// add the other point to the apporpriate end, and check to see if we've closed the
			// chain into a loop

			var index = first_match.index;
			var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc
			var addToHead = first_match.matches_head; // if we matched at head, then add to the head

			var chain = chains[index];
			var grow  = addToHead ? chain[0] : chain[chain.length - 1];
			var grow2 = addToHead ? chain[1] : chain[chain.length - 2];
			var oppo  = addToHead ? chain[chain.length - 1] : chain[0];
			var oppo2 = addToHead ? chain[chain.length - 2] : chain[1];

			if (eps.pointsCollinear(grow2, grow, pt)){
				// grow isn't needed because it's directly between grow2 and pt:
				// grow2 ---grow---> pt
				if (addToHead){
					if (buildLog)
						buildLog.chainRemoveHead(first_match.index, pt);
					chain.shift();
				}
				else{
					if (buildLog)
						buildLog.chainRemoveTail(first_match.index, pt);
					chain.pop();
				}
				grow = grow2; // old grow is gone... new grow is what grow2 was
			}

			if (eps.pointsSame(oppo, pt)){
				// we're closing the loop, so remove chain from chains
				chains.splice(index, 1);

				if (eps.pointsCollinear(oppo2, oppo, grow)){
					// oppo isn't needed because it's directly between oppo2 and grow:
					// oppo2 ---oppo--->grow
					if (addToHead){
						if (buildLog)
							buildLog.chainRemoveTail(first_match.index, grow);
						chain.pop();
					}
					else{
						if (buildLog)
							buildLog.chainRemoveHead(first_match.index, grow);
						chain.shift();
					}
				}

				if (buildLog)
					buildLog.chainClose(first_match.index);

				// we have a closed chain!
				regions.push(chain);
				return;
			}

			// not closing a loop, so just add it to the apporpriate side
			if (addToHead){
				if (buildLog)
					buildLog.chainAddHead(first_match.index, pt);
				chain.unshift(pt);
			}
			else{
				if (buildLog)
					buildLog.chainAddTail(first_match.index, pt);
				chain.push(pt);
			}
			return;
		}

		// otherwise, we matched two chains, so we need to combine those chains together

		function reverseChain(index){
			if (buildLog)
				buildLog.chainReverse(index);
			chains[index].reverse(); // gee, that's easy
		}

		function appendChain(index1, index2){
			// index1 gets index2 appended to it, and index2 is removed
			var chain1 = chains[index1];
			var chain2 = chains[index2];
			var tail  = chain1[chain1.length - 1];
			var tail2 = chain1[chain1.length - 2];
			var head  = chain2[0];
			var head2 = chain2[1];

			if (eps.pointsCollinear(tail2, tail, head)){
				// tail isn't needed because it's directly between tail2 and head
				// tail2 ---tail---> head
				if (buildLog)
					buildLog.chainRemoveTail(index1, tail);
				chain1.pop();
				tail = tail2; // old tail is gone... new tail is what tail2 was
			}

			if (eps.pointsCollinear(tail, head, head2)){
				// head isn't needed because it's directly between tail and head2
				// tail ---head---> head2
				if (buildLog)
					buildLog.chainRemoveHead(index2, head);
				chain2.shift();
			}

			if (buildLog)
				buildLog.chainJoin(index1, index2);
			chains[index1] = chain1.concat(chain2);
			chains.splice(index2, 1);
		}

		var F = first_match.index;
		var S = second_match.index;

		if (buildLog)
			buildLog.chainConnect(F, S);

		var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed
		if (first_match.matches_head){
			if (second_match.matches_head){
				if (reverseF){
					// <<<< F <<<< --- >>>> S >>>>
					reverseChain(F);
					// >>>> F >>>> --- >>>> S >>>>
					appendChain(F, S);
				}
				else{
					// <<<< F <<<< --- >>>> S >>>>
					reverseChain(S);
					// <<<< F <<<< --- <<<< S <<<<   logically same as:
					// >>>> S >>>> --- >>>> F >>>>
					appendChain(S, F);
				}
			}
			else{
				// <<<< F <<<< --- <<<< S <<<<   logically same as:
				// >>>> S >>>> --- >>>> F >>>>
				appendChain(S, F);
			}
		}
		else{
			if (second_match.matches_head){
				// >>>> F >>>> --- >>>> S >>>>
				appendChain(F, S);
			}
			else{
				if (reverseF){
					// >>>> F >>>> --- <<<< S <<<<
					reverseChain(F);
					// <<<< F <<<< --- <<<< S <<<<   logically same as:
					// >>>> S >>>> --- >>>> F >>>>
					appendChain(S, F);
				}
				else{
					// >>>> F >>>> --- <<<< S <<<<
					reverseChain(S);
					// >>>> F >>>> --- >>>> S >>>>
					appendChain(F, S);
				}
			}
		}
	});

	return regions;
}

module.exports = SegmentChainer;

},{}],23:[function(require,module,exports){
// (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
// MIT License
// Project Home: https://github.com/voidqk/polybooljs

//
// filter a list of segments based on boolean operations
//

function select(segments, selection, buildLog){
	var result = [];
	segments.forEach(function(seg){
		var index =
			(seg.myFill.above ? 8 : 0) +
			(seg.myFill.below ? 4 : 0) +
			((seg.otherFill && seg.otherFill.above) ? 2 : 0) +
			((seg.otherFill && seg.otherFill.below) ? 1 : 0);
		if (selection[index] !== 0){
			// copy the segment to the results, while also calculating the fill status
			result.push({
				id: buildLog ? buildLog.segmentId() : -1,
				start: seg.start,
				end: seg.end,
				myFill: {
					above: selection[index] === 1, // 1 if filled above
					below: selection[index] === 2  // 2 if filled below
				},
				otherFill: null
			});
		}
	});

	if (buildLog)
		buildLog.selected(result);

	return result;
}

var SegmentSelector = {
	union: function(segments, buildLog){ // primary | secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   yes filled below    2
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   no                  0
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   yes filled above    1
		//    1      0      1      1   =>   no                  0
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   no                  0
		//    1      1      1      0   =>   no                  0
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			2, 2, 0, 0,
			1, 0, 1, 0,
			0, 0, 0, 0
		], buildLog);
	},
	intersect: function(segments, buildLog){ // primary & secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   no                  0
		//    0      0      1      0   =>   no                  0
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   no                  0
		//    0      1      0      1   =>   yes filled below    2
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   yes filled below    2
		//    1      0      0      0   =>   no                  0
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   yes filled above    1
		//    1      0      1      1   =>   yes filled above    1
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled below    2
		//    1      1      1      0   =>   yes filled above    1
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 0, 0, 0,
			0, 2, 0, 2,
			0, 0, 1, 1,
			0, 2, 1, 0
		], buildLog);
	},
	difference: function(segments, buildLog){ // primary - secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   no                  0
		//    0      0      1      0   =>   no                  0
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   yes filled below    2
		//    0      1      1      1   =>   no                  0
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   yes filled above    1
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   no                  0
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled above    1
		//    1      1      1      0   =>   yes filled below    2
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 0, 0, 0,
			2, 0, 2, 0,
			1, 1, 0, 0,
			0, 1, 2, 0
		], buildLog);
	},
	differenceRev: function(segments, buildLog){ // secondary - primary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   no                  0
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   yes filled above    1
		//    0      1      1      1   =>   yes filled above    1
		//    1      0      0      0   =>   no                  0
		//    1      0      0      1   =>   yes filled below    2
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   yes filled below    2
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   no                  0
		//    1      1      1      0   =>   no                  0
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			0, 0, 1, 1,
			0, 2, 0, 2,
			0, 0, 0, 0
		], buildLog);
	},
	xor: function(segments, buildLog){ // primary ^ secondary
		// above1 below1 above2 below2    Keep?               Value
		//    0      0      0      0   =>   no                  0
		//    0      0      0      1   =>   yes filled below    2
		//    0      0      1      0   =>   yes filled above    1
		//    0      0      1      1   =>   no                  0
		//    0      1      0      0   =>   yes filled below    2
		//    0      1      0      1   =>   no                  0
		//    0      1      1      0   =>   no                  0
		//    0      1      1      1   =>   yes filled above    1
		//    1      0      0      0   =>   yes filled above    1
		//    1      0      0      1   =>   no                  0
		//    1      0      1      0   =>   no                  0
		//    1      0      1      1   =>   yes filled below    2
		//    1      1      0      0   =>   no                  0
		//    1      1      0      1   =>   yes filled above    1
		//    1      1      1      0   =>   yes filled below    2
		//    1      1      1      1   =>   no                  0
		return select(segments, [
			0, 2, 1, 0,
			2, 0, 0, 1,
			1, 0, 0, 2,
			0, 1, 2, 0
		], buildLog);
	}
};

module.exports = SegmentSelector;

},{}],24:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

},{}],25:[function(require,module,exports){
// TinyColor v1.4.1
// https://github.com/bgrins/TinyColor
// Brian Grinstead, MIT License

(function(Math) {

var trimLeft = /^\s+/,
    trimRight = /\s+$/,
    tinyCounter = 0,
    mathRound = Math.round,
    mathMin = Math.min,
    mathMax = Math.max,
    mathRandom = Math.random;

function tinycolor (color, opts) {

    color = (color) ? color : '';
    opts = opts || { };

    // If input is already a tinycolor, return itself
    if (color instanceof tinycolor) {
       return color;
    }
    // If we are called as a function, call using new instead
    if (!(this instanceof tinycolor)) {
        return new tinycolor(color, opts);
    }

    var rgb = inputToRGB(color);
    this._originalInput = color,
    this._r = rgb.r,
    this._g = rgb.g,
    this._b = rgb.b,
    this._a = rgb.a,
    this._roundA = mathRound(100*this._a) / 100,
    this._format = opts.format || rgb.format;
    this._gradientType = opts.gradientType;

    // Don't let the range of [0,255] come back in [0,1].
    // Potentially lose a little bit of precision here, but will fix issues where
    // .5 gets interpreted as half of the total, instead of half of 1
    // If it was supposed to be 128, this was already taken care of by `inputToRgb`
    if (this._r < 1) { this._r = mathRound(this._r); }
    if (this._g < 1) { this._g = mathRound(this._g); }
    if (this._b < 1) { this._b = mathRound(this._b); }

    this._ok = rgb.ok;
    this._tc_id = tinyCounter++;
}

tinycolor.prototype = {
    isDark: function() {
        return this.getBrightness() < 128;
    },
    isLight: function() {
        return !this.isDark();
    },
    isValid: function() {
        return this._ok;
    },
    getOriginalInput: function() {
      return this._originalInput;
    },
    getFormat: function() {
        return this._format;
    },
    getAlpha: function() {
        return this._a;
    },
    getBrightness: function() {
        //http://www.w3.org/TR/AERT#color-contrast
        var rgb = this.toRgb();
        return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
    },
    getLuminance: function() {
        //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
        var rgb = this.toRgb();
        var RsRGB, GsRGB, BsRGB, R, G, B;
        RsRGB = rgb.r/255;
        GsRGB = rgb.g/255;
        BsRGB = rgb.b/255;

        if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
        if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
        if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
        return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
    },
    setAlpha: function(value) {
        this._a = boundAlpha(value);
        this._roundA = mathRound(100*this._a) / 100;
        return this;
    },
    toHsv: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
    },
    toHsvString: function() {
        var hsv = rgbToHsv(this._r, this._g, this._b);
        var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
        return (this._a == 1) ?
          "hsv("  + h + ", " + s + "%, " + v + "%)" :
          "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
    },
    toHsl: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
    },
    toHslString: function() {
        var hsl = rgbToHsl(this._r, this._g, this._b);
        var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
        return (this._a == 1) ?
          "hsl("  + h + ", " + s + "%, " + l + "%)" :
          "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
    },
    toHex: function(allow3Char) {
        return rgbToHex(this._r, this._g, this._b, allow3Char);
    },
    toHexString: function(allow3Char) {
        return '#' + this.toHex(allow3Char);
    },
    toHex8: function(allow4Char) {
        return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
    },
    toHex8String: function(allow4Char) {
        return '#' + this.toHex8(allow4Char);
    },
    toRgb: function() {
        return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
    },
    toRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
          "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
    },
    toPercentageRgb: function() {
        return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
    },
    toPercentageRgbString: function() {
        return (this._a == 1) ?
          "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
          "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
    },
    toName: function() {
        if (this._a === 0) {
            return "transparent";
        }

        if (this._a < 1) {
            return false;
        }

        return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
    },
    toFilter: function(secondColor) {
        var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
        var secondHex8String = hex8String;
        var gradientType = this._gradientType ? "GradientType = 1, " : "";

        if (secondColor) {
            var s = tinycolor(secondColor);
            secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
        }

        return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
    },
    toString: function(format) {
        var formatSet = !!format;
        format = format || this._format;

        var formattedString = false;
        var hasAlpha = this._a < 1 && this._a >= 0;
        var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");

        if (needsAlphaFormat) {
            // Special case for "transparent", all other non-alpha formats
            // will return rgba when there is transparency.
            if (format === "name" && this._a === 0) {
                return this.toName();
            }
            return this.toRgbString();
        }
        if (format === "rgb") {
            formattedString = this.toRgbString();
        }
        if (format === "prgb") {
            formattedString = this.toPercentageRgbString();
        }
        if (format === "hex" || format === "hex6") {
            formattedString = this.toHexString();
        }
        if (format === "hex3") {
            formattedString = this.toHexString(true);
        }
        if (format === "hex4") {
            formattedString = this.toHex8String(true);
        }
        if (format === "hex8") {
            formattedString = this.toHex8String();
        }
        if (format === "name") {
            formattedString = this.toName();
        }
        if (format === "hsl") {
            formattedString = this.toHslString();
        }
        if (format === "hsv") {
            formattedString = this.toHsvString();
        }

        return formattedString || this.toHexString();
    },
    clone: function() {
        return tinycolor(this.toString());
    },

    _applyModification: function(fn, args) {
        var color = fn.apply(null, [this].concat([].slice.call(args)));
        this._r = color._r;
        this._g = color._g;
        this._b = color._b;
        this.setAlpha(color._a);
        return this;
    },
    lighten: function() {
        return this._applyModification(lighten, arguments);
    },
    brighten: function() {
        return this._applyModification(brighten, arguments);
    },
    darken: function() {
        return this._applyModification(darken, arguments);
    },
    desaturate: function() {
        return this._applyModification(desaturate, arguments);
    },
    saturate: function() {
        return this._applyModification(saturate, arguments);
    },
    greyscale: function() {
        return this._applyModification(greyscale, arguments);
    },
    spin: function() {
        return this._applyModification(spin, arguments);
    },

    _applyCombination: function(fn, args) {
        return fn.apply(null, [this].concat([].slice.call(args)));
    },
    analogous: function() {
        return this._applyCombination(analogous, arguments);
    },
    complement: function() {
        return this._applyCombination(complement, arguments);
    },
    monochromatic: function() {
        return this._applyCombination(monochromatic, arguments);
    },
    splitcomplement: function() {
        return this._applyCombination(splitcomplement, arguments);
    },
    triad: function() {
        return this._applyCombination(triad, arguments);
    },
    tetrad: function() {
        return this._applyCombination(tetrad, arguments);
    }
};

// If input is an object, force 1 into "1.0" to handle ratios properly
// String input requires "1.0" as input, so 1 will be treated as 1
tinycolor.fromRatio = function(color, opts) {
    if (typeof color == "object") {
        var newColor = {};
        for (var i in color) {
            if (color.hasOwnProperty(i)) {
                if (i === "a") {
                    newColor[i] = color[i];
                }
                else {
                    newColor[i] = convertToPercentage(color[i]);
                }
            }
        }
        color = newColor;
    }

    return tinycolor(color, opts);
};

// Given a string or object, convert that input to RGB
// Possible string inputs:
//
//     "red"
//     "#f00" or "f00"
//     "#ff0000" or "ff0000"
//     "#ff000000" or "ff000000"
//     "rgb 255 0 0" or "rgb (255, 0, 0)"
//     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
//     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
//     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
//     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
//     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
//     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
//
function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;
    var s = null;
    var v = null;
    var l = null;
    var ok = false;
    var format = false;

    if (typeof color == "string") {
        color = stringInputToObject(color);
    }

    if (typeof color == "object") {
        if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
            rgb = rgbToRgb(color.r, color.g, color.b);
            ok = true;
            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
            s = convertToPercentage(color.s);
            v = convertToPercentage(color.v);
            rgb = hsvToRgb(color.h, s, v);
            ok = true;
            format = "hsv";
        }
        else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
            s = convertToPercentage(color.s);
            l = convertToPercentage(color.l);
            rgb = hslToRgb(color.h, s, l);
            ok = true;
            format = "hsl";
        }

        if (color.hasOwnProperty("a")) {
            a = color.a;
        }
    }

    a = boundAlpha(a);

    return {
        ok: ok,
        format: color.format || format,
        r: mathMin(255, mathMax(rgb.r, 0)),
        g: mathMin(255, mathMax(rgb.g, 0)),
        b: mathMin(255, mathMax(rgb.b, 0)),
        a: a
    };
}


// Conversion Functions
// --------------------

// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>

// `rgbToRgb`
// Handle bounds / percentage checking to conform to CSS color spec
// <http://www.w3.org/TR/css3-color/>
// *Assumes:* r, g, b in [0, 255] or [0, 1]
// *Returns:* { r, g, b } in [0, 255]
function rgbToRgb(r, g, b){
    return {
        r: bound01(r, 255) * 255,
        g: bound01(g, 255) * 255,
        b: bound01(b, 255) * 255
    };
}

// `rgbToHsl`
// Converts an RGB color value to HSL.
// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
// *Returns:* { h, s, l } in [0,1]
function rgbToHsl(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min) {
        h = s = 0; // achromatic
    }
    else {
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }

        h /= 6;
    }

    return { h: h, s: s, l: l };
}

// `hslToRgb`
// Converts an HSL color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
function hslToRgb(h, s, l) {
    var r, g, b;

    h = bound01(h, 360);
    s = bound01(s, 100);
    l = bound01(l, 100);

    function hue2rgb(p, q, t) {
        if(t < 0) t += 1;
        if(t > 1) t -= 1;
        if(t < 1/6) return p + (q - p) * 6 * t;
        if(t < 1/2) return q;
        if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
        return p;
    }

    if(s === 0) {
        r = g = b = l; // achromatic
    }
    else {
        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHsv`
// Converts an RGB color value to HSV
// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
// *Returns:* { h, s, v } in [0,1]
function rgbToHsv(r, g, b) {

    r = bound01(r, 255);
    g = bound01(g, 255);
    b = bound01(b, 255);

    var max = mathMax(r, g, b), min = mathMin(r, g, b);
    var h, s, v = max;

    var d = max - min;
    s = max === 0 ? 0 : d / max;

    if(max == min) {
        h = 0; // achromatic
    }
    else {
        switch(max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }
    return { h: h, s: s, v: v };
}

// `hsvToRgb`
// Converts an HSV color value to RGB.
// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
// *Returns:* { r, g, b } in the set [0, 255]
 function hsvToRgb(h, s, v) {

    h = bound01(h, 360) * 6;
    s = bound01(s, 100);
    v = bound01(v, 100);

    var i = Math.floor(h),
        f = h - i,
        p = v * (1 - s),
        q = v * (1 - f * s),
        t = v * (1 - (1 - f) * s),
        mod = i % 6,
        r = [v, q, p, p, t, v][mod],
        g = [t, v, v, q, p, p][mod],
        b = [p, p, t, v, v, q][mod];

    return { r: r * 255, g: g * 255, b: b * 255 };
}

// `rgbToHex`
// Converts an RGB color to hex
// Assumes r, g, and b are contained in the set [0, 255]
// Returns a 3 or 6 character hex
function rgbToHex(r, g, b, allow3Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    // Return a 3 character hex if possible
    if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
    }

    return hex.join("");
}

// `rgbaToHex`
// Converts an RGBA color plus alpha transparency to hex
// Assumes r, g, b are contained in the set [0, 255] and
// a in [0, 1]. Returns a 4 or 8 character rgba hex
function rgbaToHex(r, g, b, a, allow4Char) {

    var hex = [
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16)),
        pad2(convertDecimalToHex(a))
    ];

    // Return a 4 character hex if possible
    if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
    }

    return hex.join("");
}

// `rgbaToArgbHex`
// Converts an RGBA color to an ARGB Hex8 string
// Rarely used, but required for "toFilter()"
function rgbaToArgbHex(r, g, b, a) {

    var hex = [
        pad2(convertDecimalToHex(a)),
        pad2(mathRound(r).toString(16)),
        pad2(mathRound(g).toString(16)),
        pad2(mathRound(b).toString(16))
    ];

    return hex.join("");
}

// `equals`
// Can be called with any tinycolor input
tinycolor.equals = function (color1, color2) {
    if (!color1 || !color2) { return false; }
    return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
};

tinycolor.random = function() {
    return tinycolor.fromRatio({
        r: mathRandom(),
        g: mathRandom(),
        b: mathRandom()
    });
};


// Modification Functions
// ----------------------
// Thanks to less.js for some of the basics here
// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>

function desaturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s -= amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function saturate(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.s += amount / 100;
    hsl.s = clamp01(hsl.s);
    return tinycolor(hsl);
}

function greyscale(color) {
    return tinycolor(color).desaturate(100);
}

function lighten (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l += amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

function brighten(color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var rgb = tinycolor(color).toRgb();
    rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
    rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
    rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
    return tinycolor(rgb);
}

function darken (color, amount) {
    amount = (amount === 0) ? 0 : (amount || 10);
    var hsl = tinycolor(color).toHsl();
    hsl.l -= amount / 100;
    hsl.l = clamp01(hsl.l);
    return tinycolor(hsl);
}

// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
// Values outside of this range will be wrapped into this range.
function spin(color, amount) {
    var hsl = tinycolor(color).toHsl();
    var hue = (hsl.h + amount) % 360;
    hsl.h = hue < 0 ? 360 + hue : hue;
    return tinycolor(hsl);
}

// Combination Functions
// ---------------------
// Thanks to jQuery xColor for some of the ideas behind these
// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>

function complement(color) {
    var hsl = tinycolor(color).toHsl();
    hsl.h = (hsl.h + 180) % 360;
    return tinycolor(hsl);
}

function triad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
    ];
}

function tetrad(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
        tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
    ];
}

function splitcomplement(color) {
    var hsl = tinycolor(color).toHsl();
    var h = hsl.h;
    return [
        tinycolor(color),
        tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
        tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
    ];
}

function analogous(color, results, slices) {
    results = results || 6;
    slices = slices || 30;

    var hsl = tinycolor(color).toHsl();
    var part = 360 / slices;
    var ret = [tinycolor(color)];

    for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
        hsl.h = (hsl.h + part) % 360;
        ret.push(tinycolor(hsl));
    }
    return ret;
}

function monochromatic(color, results) {
    results = results || 6;
    var hsv = tinycolor(color).toHsv();
    var h = hsv.h, s = hsv.s, v = hsv.v;
    var ret = [];
    var modification = 1 / results;

    while (results--) {
        ret.push(tinycolor({ h: h, s: s, v: v}));
        v = (v + modification) % 1;
    }

    return ret;
}

// Utility Functions
// ---------------------

tinycolor.mix = function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
};


// Readability Functions
// ---------------------
// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)

// `contrast`
// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
tinycolor.readability = function(color1, color2) {
    var c1 = tinycolor(color1);
    var c2 = tinycolor(color2);
    return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
};

// `isReadable`
// Ensure that foreground and background color combinations meet WCAG2 guidelines.
// The third argument is an optional Object.
//      the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
//      the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.

// *Example*
//    tinycolor.isReadable("#000", "#111") => false
//    tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
tinycolor.isReadable = function(color1, color2, wcag2) {
    var readability = tinycolor.readability(color1, color2);
    var wcag2Parms, out;

    out = false;

    wcag2Parms = validateWCAG2Parms(wcag2);
    switch (wcag2Parms.level + wcag2Parms.size) {
        case "AAsmall":
        case "AAAlarge":
            out = readability >= 4.5;
            break;
        case "AAlarge":
            out = readability >= 3;
            break;
        case "AAAsmall":
            out = readability >= 7;
            break;
    }
    return out;

};

// `mostReadable`
// Given a base color and a list of possible foreground or background
// colors for that base, returns the most readable color.
// Optionally returns Black or White if the most readable color is unreadable.
// *Example*
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
tinycolor.mostReadable = function(baseColor, colorList, args) {
    var bestColor = null;
    var bestScore = 0;
    var readability;
    var includeFallbackColors, level, size ;
    args = args || {};
    includeFallbackColors = args.includeFallbackColors ;
    level = args.level;
    size = args.size;

    for (var i= 0; i < colorList.length ; i++) {
        readability = tinycolor.readability(baseColor, colorList[i]);
        if (readability > bestScore) {
            bestScore = readability;
            bestColor = tinycolor(colorList[i]);
        }
    }

    if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
        return bestColor;
    }
    else {
        args.includeFallbackColors=false;
        return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
    }
};


// Big List of Colors
// ------------------
// <http://www.w3.org/TR/css3-color/#svg-color>
var names = tinycolor.names = {
    aliceblue: "f0f8ff",
    antiquewhite: "faebd7",
    aqua: "0ff",
    aquamarine: "7fffd4",
    azure: "f0ffff",
    beige: "f5f5dc",
    bisque: "ffe4c4",
    black: "000",
    blanchedalmond: "ffebcd",
    blue: "00f",
    blueviolet: "8a2be2",
    brown: "a52a2a",
    burlywood: "deb887",
    burntsienna: "ea7e5d",
    cadetblue: "5f9ea0",
    chartreuse: "7fff00",
    chocolate: "d2691e",
    coral: "ff7f50",
    cornflowerblue: "6495ed",
    cornsilk: "fff8dc",
    crimson: "dc143c",
    cyan: "0ff",
    darkblue: "00008b",
    darkcyan: "008b8b",
    darkgoldenrod: "b8860b",
    darkgray: "a9a9a9",
    darkgreen: "006400",
    darkgrey: "a9a9a9",
    darkkhaki: "bdb76b",
    darkmagenta: "8b008b",
    darkolivegreen: "556b2f",
    darkorange: "ff8c00",
    darkorchid: "9932cc",
    darkred: "8b0000",
    darksalmon: "e9967a",
    darkseagreen: "8fbc8f",
    darkslateblue: "483d8b",
    darkslategray: "2f4f4f",
    darkslategrey: "2f4f4f",
    darkturquoise: "00ced1",
    darkviolet: "9400d3",
    deeppink: "ff1493",
    deepskyblue: "00bfff",
    dimgray: "696969",
    dimgrey: "696969",
    dodgerblue: "1e90ff",
    firebrick: "b22222",
    floralwhite: "fffaf0",
    forestgreen: "228b22",
    fuchsia: "f0f",
    gainsboro: "dcdcdc",
    ghostwhite: "f8f8ff",
    gold: "ffd700",
    goldenrod: "daa520",
    gray: "808080",
    green: "008000",
    greenyellow: "adff2f",
    grey: "808080",
    honeydew: "f0fff0",
    hotpink: "ff69b4",
    indianred: "cd5c5c",
    indigo: "4b0082",
    ivory: "fffff0",
    khaki: "f0e68c",
    lavender: "e6e6fa",
    lavenderblush: "fff0f5",
    lawngreen: "7cfc00",
    lemonchiffon: "fffacd",
    lightblue: "add8e6",
    lightcoral: "f08080",
    lightcyan: "e0ffff",
    lightgoldenrodyellow: "fafad2",
    lightgray: "d3d3d3",
    lightgreen: "90ee90",
    lightgrey: "d3d3d3",
    lightpink: "ffb6c1",
    lightsalmon: "ffa07a",
    lightseagreen: "20b2aa",
    lightskyblue: "87cefa",
    lightslategray: "789",
    lightslategrey: "789",
    lightsteelblue: "b0c4de",
    lightyellow: "ffffe0",
    lime: "0f0",
    limegreen: "32cd32",
    linen: "faf0e6",
    magenta: "f0f",
    maroon: "800000",
    mediumaquamarine: "66cdaa",
    mediumblue: "0000cd",
    mediumorchid: "ba55d3",
    mediumpurple: "9370db",
    mediumseagreen: "3cb371",
    mediumslateblue: "7b68ee",
    mediumspringgreen: "00fa9a",
    mediumturquoise: "48d1cc",
    mediumvioletred: "c71585",
    midnightblue: "191970",
    mintcream: "f5fffa",
    mistyrose: "ffe4e1",
    moccasin: "ffe4b5",
    navajowhite: "ffdead",
    navy: "000080",
    oldlace: "fdf5e6",
    olive: "808000",
    olivedrab: "6b8e23",
    orange: "ffa500",
    orangered: "ff4500",
    orchid: "da70d6",
    palegoldenrod: "eee8aa",
    palegreen: "98fb98",
    paleturquoise: "afeeee",
    palevioletred: "db7093",
    papayawhip: "ffefd5",
    peachpuff: "ffdab9",
    peru: "cd853f",
    pink: "ffc0cb",
    plum: "dda0dd",
    powderblue: "b0e0e6",
    purple: "800080",
    rebeccapurple: "663399",
    red: "f00",
    rosybrown: "bc8f8f",
    royalblue: "4169e1",
    saddlebrown: "8b4513",
    salmon: "fa8072",
    sandybrown: "f4a460",
    seagreen: "2e8b57",
    seashell: "fff5ee",
    sienna: "a0522d",
    silver: "c0c0c0",
    skyblue: "87ceeb",
    slateblue: "6a5acd",
    slategray: "708090",
    slategrey: "708090",
    snow: "fffafa",
    springgreen: "00ff7f",
    steelblue: "4682b4",
    tan: "d2b48c",
    teal: "008080",
    thistle: "d8bfd8",
    tomato: "ff6347",
    turquoise: "40e0d0",
    violet: "ee82ee",
    wheat: "f5deb3",
    white: "fff",
    whitesmoke: "f5f5f5",
    yellow: "ff0",
    yellowgreen: "9acd32"
};

// Make it easy to access colors via `hexNames[hex]`
var hexNames = tinycolor.hexNames = flip(names);


// Utilities
// ---------

// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
function flip(o) {
    var flipped = { };
    for (var i in o) {
        if (o.hasOwnProperty(i)) {
            flipped[o[i]] = i;
        }
    }
    return flipped;
}

// Return a valid alpha value [0,1] with all invalid values being set to 1
function boundAlpha(a) {
    a = parseFloat(a);

    if (isNaN(a) || a < 0 || a > 1) {
        a = 1;
    }

    return a;
}

// Take input from [0, n] and return it as [0, 1]
function bound01(n, max) {
    if (isOnePointZero(n)) { n = "100%"; }

    var processPercent = isPercentage(n);
    n = mathMin(max, mathMax(0, parseFloat(n)));

    // Automatically convert percentage into number
    if (processPercent) {
        n = parseInt(n * max, 10) / 100;
    }

    // Handle floating point rounding errors
    if ((Math.abs(n - max) < 0.000001)) {
        return 1;
    }

    // Convert into [0, 1] range if it isn't already
    return (n % max) / parseFloat(max);
}

// Force a number between 0 and 1
function clamp01(val) {
    return mathMin(1, mathMax(0, val));
}

// Parse a base-16 hex value into a base-10 integer
function parseIntFromHex(val) {
    return parseInt(val, 16);
}

// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
function isOnePointZero(n) {
    return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
}

// Check to see if string passed in is a percentage
function isPercentage(n) {
    return typeof n === "string" && n.indexOf('%') != -1;
}

// Force a hex value to have 2 characters
function pad2(c) {
    return c.length == 1 ? '0' + c : '' + c;
}

// Replace a decimal with it's percentage value
function convertToPercentage(n) {
    if (n <= 1) {
        n = (n * 100) + "%";
    }

    return n;
}

// Converts a decimal to a hex value
function convertDecimalToHex(d) {
    return Math.round(parseFloat(d) * 255).toString(16);
}
// Converts a hex value to a decimal
function convertHexToDecimal(h) {
    return (parseIntFromHex(h) / 255);
}

var matchers = (function() {

    // <http://www.w3.org/TR/css3-values/#integers>
    var CSS_INTEGER = "[-\\+]?\\d+%?";

    // <http://www.w3.org/TR/css3-values/#number-value>
    var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";

    // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
    var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";

    // Actual matching.
    // Parentheses and commas are optional, but not required.
    // Whitespace can take the place of commas or opening paren
    var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
    var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";

    return {
        CSS_UNIT: new RegExp(CSS_UNIT),
        rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
        rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
        hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
        hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
        hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
        hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
        hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
        hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
        hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
    };
})();

// `isValidCSSUnit`
// Take in a single string / number and check to see if it looks like a CSS unit
// (see `matchers` above for definition).
function isValidCSSUnit(color) {
    return !!matchers.CSS_UNIT.exec(color);
}

// `stringInputToObject`
// Permissive string parsing.  Take in a number of formats, and output an object
// based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
function stringInputToObject(color) {

    color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
    var named = false;
    if (names[color]) {
        color = names[color];
        named = true;
    }
    else if (color == 'transparent') {
        return { r: 0, g: 0, b: 0, a: 0, format: "name" };
    }

    // Try to match string input using regular expressions.
    // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
    // Just return an object and let the conversion functions handle that.
    // This way the result will be the same whether the tinycolor is initialized with string or object.
    var match;
    if ((match = matchers.rgb.exec(color))) {
        return { r: match[1], g: match[2], b: match[3] };
    }
    if ((match = matchers.rgba.exec(color))) {
        return { r: match[1], g: match[2], b: match[3], a: match[4] };
    }
    if ((match = matchers.hsl.exec(color))) {
        return { h: match[1], s: match[2], l: match[3] };
    }
    if ((match = matchers.hsla.exec(color))) {
        return { h: match[1], s: match[2], l: match[3], a: match[4] };
    }
    if ((match = matchers.hsv.exec(color))) {
        return { h: match[1], s: match[2], v: match[3] };
    }
    if ((match = matchers.hsva.exec(color))) {
        return { h: match[1], s: match[2], v: match[3], a: match[4] };
    }
    if ((match = matchers.hex8.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            a: convertHexToDecimal(match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex6.exec(color))) {
        return {
            r: parseIntFromHex(match[1]),
            g: parseIntFromHex(match[2]),
            b: parseIntFromHex(match[3]),
            format: named ? "name" : "hex"
        };
    }
    if ((match = matchers.hex4.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            a: convertHexToDecimal(match[4] + '' + match[4]),
            format: named ? "name" : "hex8"
        };
    }
    if ((match = matchers.hex3.exec(color))) {
        return {
            r: parseIntFromHex(match[1] + '' + match[1]),
            g: parseIntFromHex(match[2] + '' + match[2]),
            b: parseIntFromHex(match[3] + '' + match[3]),
            format: named ? "name" : "hex"
        };
    }

    return false;
}

function validateWCAG2Parms(parms) {
    // return valid WCAG2 parms for isReadable.
    // If input parms are invalid, return {"level":"AA", "size":"small"}
    var level, size;
    parms = parms || {"level":"AA", "size":"small"};
    level = (parms.level || "AA").toUpperCase();
    size = (parms.size || "small").toLowerCase();
    if (level !== "AA" && level !== "AAA") {
        level = "AA";
    }
    if (size !== "small" && size !== "large") {
        size = "small";
    }
    return {"level":level, "size":size};
}

// Node: Export function
if (typeof module !== "undefined" && module.exports) {
    module.exports = tinycolor;
}
// AMD/requirejs: Define the module
else if (typeof define === 'function' && define.amd) {
    define(function () {return tinycolor;});
}
// Browser: Expose to window
else {
    window.tinycolor = tinycolor;
}

})(Math);

},{}],26:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var handleAnnotationCommonDefaults = require('./common_defaults');
var attributes = require('./attributes');


module.exports = function handleAnnotationDefaults(annIn, annOut, fullLayout, opts, itemOpts) {
    opts = opts || {};
    itemOpts = itemOpts || {};

    function coerce(attr, dflt) {
        return Lib.coerce(annIn, annOut, attributes, attr, dflt);
    }

    var visible = coerce('visible', !itemOpts.itemIsNotPlainObject);
    var clickToShow = coerce('clicktoshow');

    if(!(visible || clickToShow)) return annOut;

    handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce);

    var showArrow = annOut.showarrow;

    // positioning
    var axLetters = ['x', 'y'],
        arrowPosDflt = [-10, -30],
        gdMock = {_fullLayout: fullLayout};
    for(var i = 0; i < 2; i++) {
        var axLetter = axLetters[i];

        // xref, yref
        var axRef = Axes.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper');

        // x, y
        Axes.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5);

        if(showArrow) {
            var arrowPosAttr = 'a' + axLetter,
                // axref, ayref
                aaxRef = Axes.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel');

            // for now the arrow can only be on the same axis or specified as pixels
            // TODO: sometime it might be interesting to allow it to be on *any* axis
            // but that would require updates to drawing & autorange code and maybe more
            if(aaxRef !== 'pixel' && aaxRef !== axRef) {
                aaxRef = annOut[arrowPosAttr] = 'pixel';
            }

            // ax, ay
            var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4;
            Axes.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt);
        }

        // xanchor, yanchor
        coerce(axLetter + 'anchor');

        // xshift, yshift
        coerce(axLetter + 'shift');
    }

    // if you have one coordinate you should have both
    Lib.noneOrAll(annIn, annOut, ['x', 'y']);

    // if you have one part of arrow length you should have both
    if(showArrow) {
        Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
    }

    if(clickToShow) {
        var xClick = coerce('xclick');
        var yClick = coerce('yclick');

        // put the actual click data to bind to into private attributes
        // so we don't have to do this little bit of logic on every hover event
        annOut._xclick = (xClick === undefined) ?
            annOut.x :
            Axes.cleanPosition(xClick, gdMock, annOut.xref);
        annOut._yclick = (yClick === undefined) ?
            annOut.y :
            Axes.cleanPosition(yClick, gdMock, annOut.yref);
    }

    return annOut;
};

},{"../../lib":164,"../../plots/cartesian/axes":206,"./attributes":28,"./common_defaults":31}],27:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * All paths are tuned for maximum scalability of the arrowhead,
 * ie throughout arrowwidth=0.3..3 the head is joined smoothly
 * to the line, with the line coming from the left and ending at (0, 0).
 *
 * `backoff` is the distance to move the arrowhead and the end of the line,
 * in order that the arrowhead points to the desired place, either at
 * the tip of the arrow or (in the case of circle or square)
 * the center of the symbol.
 *
 * `noRotate`, if truthy, says that this arrowhead should not rotate with the
 * arrow. That's the case for squares, which should always be straight, and
 * circles, for which it's irrelevant.
 */

module.exports = [
    // no arrow
    {
        path: '',
        backoff: 0
    },
    // wide with flat back
    {
        path: 'M-2.4,-3V3L0.6,0Z',
        backoff: 0.6
    },
    // narrower with flat back
    {
        path: 'M-3.7,-2.5V2.5L1.3,0Z',
        backoff: 1.3
    },
    // barbed
    {
        path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
        backoff: 1.55
    },
    // wide line-drawn
    {
        path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
        backoff: 1.6
    },
    // narrower line-drawn
    {
        path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
        backoff: 2
    },
    // circle
    {
        path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
        backoff: 0,
        noRotate: true
    },
    // square
    {
        path: 'M2,2V-2H-2V2Z',
        backoff: 0,
        noRotate: true
    }
];

},{}],28:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var ARROWPATHS = require('./arrow_paths');
var fontAttrs = require('../../plots/font_attributes');
var cartesianConstants = require('../../plots/cartesian/constants');


module.exports = {
    _isLinkedToArray: 'annotation',

    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calcIfAutorange+arraydraw',
        
    },

    text: {
        valType: 'string',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    textangle: {
        valType: 'angle',
        dflt: 0,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    font: fontAttrs({
        editType: 'calcIfAutorange+arraydraw',
        colorEditType: 'arraydraw',
        
    }),
    width: {
        valType: 'number',
        min: 1,
        dflt: null,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    height: {
        valType: 'number',
        min: 1,
        dflt: null,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    align: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'center',
        
        editType: 'arraydraw',
        
    },
    valign: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'middle',
        
        editType: 'arraydraw',
        
    },
    bgcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    borderpad: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    // arrow
    showarrow: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    arrowcolor: {
        valType: 'color',
        
        editType: 'arraydraw',
        
    },
    arrowhead: {
        valType: 'integer',
        min: 0,
        max: ARROWPATHS.length,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    startarrowhead: {
        valType: 'integer',
        min: 0,
        max: ARROWPATHS.length,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    arrowside: {
        valType: 'flaglist',
        flags: ['end', 'start'],
        extras: ['none'],
        dflt: 'end',
        
        editType: 'arraydraw',
        
    },
    arrowsize: {
        valType: 'number',
        min: 0.3,
        dflt: 1,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    startarrowsize: {
        valType: 'number',
        min: 0.3,
        dflt: 1,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    arrowwidth: {
        valType: 'number',
        min: 0.1,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    standoff: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    startstandoff: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    ax: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    ay: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    axref: {
        valType: 'enumerated',
        dflt: 'pixel',
        values: [
            'pixel',
            cartesianConstants.idRegex.x.toString()
        ],
        
        editType: 'calc',
        
    },
    ayref: {
        valType: 'enumerated',
        dflt: 'pixel',
        values: [
            'pixel',
            cartesianConstants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    // positioning
    xref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.x.toString()
        ],
        
        editType: 'calc',
        
    },
    x: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'auto',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    xshift: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    yref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.y.toString()
        ],
        
        editType: 'calc',
        
    },
    y: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'auto',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    yshift: {
        valType: 'number',
        dflt: 0,
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    clicktoshow: {
        valType: 'enumerated',
        values: [false, 'onoff', 'onout'],
        dflt: false,
        
        editType: 'arraydraw',
        
    },
    xclick: {
        valType: 'any',
        
        editType: 'arraydraw',
        
    },
    yclick: {
        valType: 'any',
        
        editType: 'arraydraw',
        
    },
    hovertext: {
        valType: 'string',
        
        editType: 'arraydraw',
        
    },
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            editType: 'arraydraw',
            
        },
        bordercolor: {
            valType: 'color',
            
            editType: 'arraydraw',
            
        },
        font: fontAttrs({
            editType: 'arraydraw',
            
        }),
        editType: 'arraydraw'
    },
    captureevents: {
        valType: 'boolean',
        
        editType: 'arraydraw',
        
    },
    editType: 'calc',

    _deprecated: {
        ref: {
            valType: 'string',
            
            editType: 'calc',
            
        }
    }
};

},{"../../plots/cartesian/constants":211,"../../plots/font_attributes":232,"./arrow_paths":27}],29:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');

var draw = require('./draw').draw;


module.exports = function calcAutorange(gd) {
    var fullLayout = gd._fullLayout,
        annotationList = Lib.filterVisible(fullLayout.annotations);

    if(!annotationList.length || !gd._fullData.length) return;

    var annotationAxes = {};
    annotationList.forEach(function(ann) {
        annotationAxes[ann.xref] = 1;
        annotationAxes[ann.yref] = 1;
    });

    for(var axId in annotationAxes) {
        var ax = Axes.getFromId(gd, axId);
        if(ax && ax.autorange) {
            return Lib.syncOrAsync([
                draw,
                annAutorange
            ], gd);
        }
    }
};

function annAutorange(gd) {
    var fullLayout = gd._fullLayout;

    // find the bounding boxes for each of these annotations'
    // relative to their anchor points
    // use the arrow and the text bg rectangle,
    // as the whole anno may include hidden text in its bbox
    Lib.filterVisible(fullLayout.annotations).forEach(function(ann) {
        var xa = Axes.getFromId(gd, ann.xref),
            ya = Axes.getFromId(gd, ann.yref),
            headSize = 3 * ann.arrowsize * ann.arrowwidth || 0,
            startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0;

        var headPlus, headMinus, startHeadPlus, startHeadMinus;

        if(xa && xa.autorange) {
            headPlus = headSize + ann.xshift;
            headMinus = headSize - ann.xshift;
            startHeadPlus = startHeadSize + ann.xshift;
            startHeadMinus = startHeadSize - ann.xshift;

            if(ann.axref === ann.xref) {
                // expand for the arrowhead (padded by arrowhead)
                Axes.expand(xa, [xa.r2c(ann.x)], {
                    ppadplus: headPlus,
                    ppadminus: headMinus
                });
                // again for the textbox (padded by textbox)
                Axes.expand(xa, [xa.r2c(ann.ax)], {
                    ppadplus: Math.max(ann._xpadplus, startHeadPlus),
                    ppadminus: Math.max(ann._xpadminus, startHeadMinus)
                });
            }
            else {
                startHeadPlus = ann.ax ? startHeadPlus + ann.ax : startHeadPlus;
                startHeadMinus = ann.ax ? startHeadMinus - ann.ax : startHeadMinus;
                Axes.expand(xa, [xa.r2c(ann.x)], {
                    ppadplus: Math.max(ann._xpadplus, headPlus, startHeadPlus),
                    ppadminus: Math.max(ann._xpadminus, headMinus, startHeadMinus)
                });
            }
        }

        if(ya && ya.autorange) {
            headPlus = headSize - ann.yshift;
            headMinus = headSize + ann.yshift;
            startHeadPlus = startHeadSize - ann.yshift;
            startHeadMinus = startHeadSize + ann.yshift;

            if(ann.ayref === ann.yref) {
                Axes.expand(ya, [ya.r2c(ann.y)], {
                    ppadplus: headPlus,
                    ppadminus: headMinus
                });
                Axes.expand(ya, [ya.r2c(ann.ay)], {
                    ppadplus: Math.max(ann._ypadplus, startHeadPlus),
                    ppadminus: Math.max(ann._ypadminus, startHeadMinus)
                });
            }
            else {
                startHeadPlus = ann.ay ? startHeadPlus + ann.ay : startHeadPlus;
                startHeadMinus = ann.ay ? startHeadMinus - ann.ay : startHeadMinus;
                Axes.expand(ya, [ya.r2c(ann.y)], {
                    ppadplus: Math.max(ann._ypadplus, headPlus, startHeadPlus),
                    ppadminus: Math.max(ann._ypadminus, headMinus, startHeadMinus)
                });
            }
        }
    });
}

},{"../../lib":164,"../../plots/cartesian/axes":206,"./draw":34}],30:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');

module.exports = {
    hasClickToShow: hasClickToShow,
    onClick: onClick
};

/*
 * hasClickToShow: does the given hoverData have ANY annotations which will
 * turn ON if we click here? (used by hover events to set cursor)
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: boolean
 */
function hasClickToShow(gd, hoverData) {
    var sets = getToggleSets(gd, hoverData);
    return sets.on.length > 0 || sets.explicitOff.length > 0;
}

/*
 * onClick: perform the toggling (via Plotly.update) implied by clicking
 * at this hoverData
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: Promise that the update is complete
 */
function onClick(gd, hoverData) {
    var toggleSets = getToggleSets(gd, hoverData),
        onSet = toggleSets.on,
        offSet = toggleSets.off.concat(toggleSets.explicitOff),
        update = {},
        i;

    if(!(onSet.length || offSet.length)) return;

    for(i = 0; i < onSet.length; i++) {
        update['annotations[' + onSet[i] + '].visible'] = true;
    }

    for(i = 0; i < offSet.length; i++) {
        update['annotations[' + offSet[i] + '].visible'] = false;
    }

    return Registry.call('update', gd, {}, update);
}

/*
 * getToggleSets: find the annotations which will turn on or off at this
 * hoverData
 *
 * gd: graphDiv
 * hoverData: a hoverData array, as included with the *plotly_hover* or
 *     *plotly_click* events in the `points` attribute
 *
 * returns: {
 *   on: Array (indices of annotations to turn on),
 *   off: Array (indices to turn off because you're not hovering on them),
 *   explicitOff: Array (indices to turn off because you *are* hovering on them)
 * }
 */
function getToggleSets(gd, hoverData) {
    var annotations = gd._fullLayout.annotations,
        onSet = [],
        offSet = [],
        explicitOffSet = [],
        hoverLen = (hoverData || []).length;

    var i, j, anni, showMode, pointj, xa, ya, toggleType;

    for(i = 0; i < annotations.length; i++) {
        anni = annotations[i];
        showMode = anni.clicktoshow;

        if(showMode) {
            for(j = 0; j < hoverLen; j++) {
                pointj = hoverData[j];
                xa = pointj.xaxis;
                ya = pointj.yaxis;

                if(xa._id === anni.xref &&
                    ya._id === anni.yref &&
                    xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) &&
                    ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)
                ) {
                    // match! toggle this annotation
                    // regardless of its clicktoshow mode
                    // but if it's onout mode, off is implicit
                    if(anni.visible) {
                        if(showMode === 'onout') toggleType = offSet;
                        else toggleType = explicitOffSet;
                    }
                    else {
                        toggleType = onSet;
                    }
                    toggleType.push(i);
                    break;
                }
            }

            if(j === hoverLen) {
                // no match - only turn this annotation OFF, and only if
                // showmode is 'onout'
                if(anni.visible && showMode === 'onout') offSet.push(i);
            }
        }
    }

    return {on: onSet, off: offSet, explicitOff: explicitOffSet};
}

// to handle log axes until v2
function clickData2r(d, ax) {
    return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d);
}

},{"../../registry":254}],31:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Color = require('../color');

// defaults common to 'annotations' and 'annotations3d'
module.exports = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) {
    coerce('opacity');
    var bgColor = coerce('bgcolor');

    var borderColor = coerce('bordercolor');
    var borderOpacity = Color.opacity(borderColor);

    coerce('borderpad');

    var borderWidth = coerce('borderwidth');
    var showArrow = coerce('showarrow');

    coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation);
    coerce('textangle');
    Lib.coerceFont(coerce, 'font', fullLayout.font);

    coerce('width');
    coerce('align');

    var h = coerce('height');
    if(h) coerce('valign');

    if(showArrow) {
        var arrowside = coerce('arrowside');
        var arrowhead;
        var arrowsize;

        if(arrowside.indexOf('end') !== -1) {
            arrowhead = coerce('arrowhead');
            arrowsize = coerce('arrowsize');
        }

        if(arrowside.indexOf('start') !== -1) {
            coerce('startarrowhead', arrowhead);
            coerce('startarrowsize', arrowsize);
        }
        coerce('arrowcolor', borderOpacity ? annOut.bordercolor : Color.defaultLine);
        coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2);
        coerce('standoff');
        coerce('startstandoff');

    }

    var hoverText = coerce('hovertext');
    var globalHoverLabel = fullLayout.hoverlabel || {};

    if(hoverText) {
        var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor ||
            (Color.opacity(bgColor) ? Color.rgb(bgColor) : Color.defaultLine)
        );

        var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor ||
            Color.contrast(hoverBG)
        );

        Lib.coerceFont(coerce, 'hoverlabel.font', {
            family: globalHoverLabel.font.family,
            size: globalHoverLabel.font.size,
            color: globalHoverLabel.font.color || hoverBorder
        });
    }

    coerce('captureevents', !!hoverText);
};

},{"../../lib":164,"../color":43}],32:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var toLogRange = require('../../lib/to_log_range');

/*
 * convertCoords: when converting an axis between log and linear
 * you need to alter any annotations on that axis to keep them
 * pointing at the same data point.
 * In v2.0 this will become obsolete
 *
 * gd: the plot div
 * ax: the axis being changed
 * newType: the type it's getting
 * doExtra: function(attr, val) from inside relayout that sets the attribute.
 *     Use this to make the changes as it's aware if any other changes in the
 *     same relayout call should override this conversion.
 */
module.exports = function convertCoords(gd, ax, newType, doExtra) {
    ax = ax || {};

    var toLog = (newType === 'log') && (ax.type === 'linear'),
        fromLog = (newType === 'linear') && (ax.type === 'log');

    if(!(toLog || fromLog)) return;

    var annotations = gd._fullLayout.annotations,
        axLetter = ax._id.charAt(0),
        ann,
        attrPrefix;

    function convert(attr) {
        var currentVal = ann[attr],
            newVal = null;

        if(toLog) newVal = toLogRange(currentVal, ax.range);
        else newVal = Math.pow(10, currentVal);

        // if conversion failed, delete the value so it gets a default value
        if(!isNumeric(newVal)) newVal = null;

        doExtra(attrPrefix + attr, newVal);
    }

    for(var i = 0; i < annotations.length; i++) {
        ann = annotations[i];
        attrPrefix = 'annotations[' + i + '].';

        if(ann[axLetter + 'ref'] === ax._id) convert(axLetter);
        if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter);
    }
};

},{"../../lib/to_log_range":187,"fast-isnumeric":9}],33:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var handleArrayContainerDefaults = require('../../plots/array_container_defaults');
var handleAnnotationDefaults = require('./annotation_defaults');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var opts = {
        name: 'annotations',
        handleItemDefaults: handleAnnotationDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};

},{"../../plots/array_container_defaults":202,"./annotation_defaults":26}],34:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Plots = require('../../plots/plots');
var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var Color = require('../color');
var Drawing = require('../drawing');
var Fx = require('../fx');
var svgTextUtils = require('../../lib/svg_text_utils');
var setCursor = require('../../lib/setcursor');
var dragElement = require('../dragelement');
var drawArrowHead = require('./draw_arrow_head');

// Annotations are stored in gd.layout.annotations, an array of objects
// index can point to one item in this array,
//  or non-numeric to simply add a new one
//  or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
//  or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
//  annotation at that point in the array, or 'remove' to delete this one

module.exports = {
    draw: draw,
    drawOne: drawOne,
    drawRaw: drawRaw
};

/*
 * draw: draw all annotations without any new modifications
 */
function draw(gd) {
    var fullLayout = gd._fullLayout;

    fullLayout._infolayer.selectAll('.annotation').remove();

    for(var i = 0; i < fullLayout.annotations.length; i++) {
        if(fullLayout.annotations[i].visible) {
            drawOne(gd, i);
        }
    }

    return Plots.previousPromises(gd);
}

/*
 * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications
 *
 * index (int): the annotation to draw
 */
function drawOne(gd, index) {
    var fullLayout = gd._fullLayout;
    var options = fullLayout.annotations[index] || {};
    var xa = Axes.getFromId(gd, options.xref);
    var ya = Axes.getFromId(gd, options.yref);

    drawRaw(gd, options, index, false, xa, ya);
}

/**
 * drawRaw: draw a single annotation, potentially with modifications
 *
 * @param {DOM element} gd
 * @param {object} options : this annotation's fullLayout options
 * @param {integer} index : index in 'annotations' container of the annotation to draw
 * @param {string} subplotId : id of the annotation's subplot
 *  - use false for 2d (i.e. cartesian or paper-ref) annotations
 * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px
 * @param {object | undefined} ya : ... y-axis
 */
function drawRaw(gd, options, index, subplotId, xa, ya) {
    var fullLayout = gd._fullLayout;
    var gs = gd._fullLayout._size;
    var edits = gd._context.edits;

    var className;
    var annbase;

    if(subplotId) {
        className = 'annotation-' + subplotId;
        annbase = subplotId + '.annotations[' + index + ']';
    } else {
        className = 'annotation';
        annbase = 'annotations[' + index + ']';
    }

    // remove the existing annotation if there is one
    fullLayout._infolayer
        .selectAll('.' + className + '[data-index="' + index + '"]')
        .remove();

    var annClipID = 'clip' + fullLayout._uid + '_ann' + index;

    // this annotation is gone - quit now after deleting it
    // TODO: use d3 idioms instead of deleting and redrawing every time
    if(!options._input || options.visible === false) {
        d3.selectAll('#' + annClipID).remove();
        return;
    }

    // calculated pixel positions
    // x & y each will get text, head, and tail as appropriate
    var annPosPx = {x: {}, y: {}},
        textangle = +options.textangle || 0;

    // create the components
    // made a single group to contain all, so opacity can work right
    // with border/arrow together this could handle a whole bunch of
    // cleanup at this point, but works for now
    var annGroup = fullLayout._infolayer.append('g')
        .classed(className, true)
        .attr('data-index', String(index))
        .style('opacity', options.opacity);

    // another group for text+background so that they can rotate together
    var annTextGroup = annGroup.append('g')
        .classed('annotation-text-g', true);

    var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition'];
    var textEvents = options.captureevents || edits.annotationText || editTextPosition;

    var annTextGroupInner = annTextGroup.append('g')
        .style('pointer-events', textEvents ? 'all' : null)
        .call(setCursor, 'default')
        .on('click', function() {
            gd._dragging = false;

            var eventData = {
                index: index,
                annotation: options._input,
                fullAnnotation: options,
                event: d3.event
            };

            if(subplotId) {
                eventData.subplotId = subplotId;
            }

            gd.emit('plotly_clickannotation', eventData);
        });

    if(options.hovertext) {
        annTextGroupInner
        .on('mouseover', function() {
            var hoverOptions = options.hoverlabel;
            var hoverFont = hoverOptions.font;
            var bBox = this.getBoundingClientRect();
            var bBoxRef = gd.getBoundingClientRect();

            Fx.loneHover({
                x0: bBox.left - bBoxRef.left,
                x1: bBox.right - bBoxRef.left,
                y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top,
                text: options.hovertext,
                color: hoverOptions.bgcolor,
                borderColor: hoverOptions.bordercolor,
                fontFamily: hoverFont.family,
                fontSize: hoverFont.size,
                fontColor: hoverFont.color
            }, {
                container: fullLayout._hoverlayer.node(),
                outerContainer: fullLayout._paper.node(),
                gd: gd
            });
        })
        .on('mouseout', function() {
            Fx.loneUnhover(fullLayout._hoverlayer.node());
        });
    }

    var borderwidth = options.borderwidth,
        borderpad = options.borderpad,
        borderfull = borderwidth + borderpad;

    var annTextBG = annTextGroupInner.append('rect')
        .attr('class', 'bg')
        .style('stroke-width', borderwidth + 'px')
        .call(Color.stroke, options.bordercolor)
        .call(Color.fill, options.bgcolor);

    var isSizeConstrained = options.width || options.height;

    var annTextClip = fullLayout._topclips
        .selectAll('#' + annClipID)
        .data(isSizeConstrained ? [0] : []);

    annTextClip.enter().append('clipPath')
        .classed('annclip', true)
        .attr('id', annClipID)
      .append('rect');
    annTextClip.exit().remove();

    var font = options.font;

    var annText = annTextGroupInner.append('text')
        .classed('annotation-text', true)
        .text(options.text);

    function textLayout(s) {
        s.call(Drawing.font, font)
        .attr({
            'text-anchor': {
                left: 'start',
                right: 'end'
            }[options.align] || 'middle'
        });

        svgTextUtils.convertToTspans(s, gd, drawGraphicalElements);
        return s;
    }

    function drawGraphicalElements() {
        // if the text has *only* a link, make the whole box into a link
        var anchor3 = annText.selectAll('a');
        if(anchor3.size() === 1 && anchor3.text() === annText.text()) {
            var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({
                'xlink:xlink:href': anchor3.attr('xlink:href'),
                'xlink:xlink:show': anchor3.attr('xlink:show')
            })
            .style({cursor: 'pointer'});

            wholeLink.node().appendChild(annTextBG.node());
        }

        var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group');
        var hasMathjax = !mathjaxGroup.empty();
        var anntextBB = Drawing.bBox(
                (hasMathjax ? mathjaxGroup : annText).node());
        var textWidth = anntextBB.width;
        var textHeight = anntextBB.height;
        var annWidth = options.width || textWidth;
        var annHeight = options.height || textHeight;
        var outerWidth = Math.round(annWidth + 2 * borderfull);
        var outerHeight = Math.round(annHeight + 2 * borderfull);


        // save size in the annotation object for use by autoscale
        options._w = annWidth;
        options._h = annHeight;

        function shiftFraction(v, anchor) {
            if(anchor === 'auto') {
                if(v < 1 / 3) anchor = 'left';
                else if(v > 2 / 3) anchor = 'right';
                else anchor = 'center';
            }
            return {
                center: 0,
                middle: 0,
                left: 0.5,
                bottom: -0.5,
                right: -0.5,
                top: 0.5
            }[anchor];
        }

        var annotationIsOffscreen = false;
        var letters = ['x', 'y'];

        for(var i = 0; i < letters.length; i++) {
            var axLetter = letters[i],
                axRef = options[axLetter + 'ref'] || axLetter,
                tailRef = options['a' + axLetter + 'ref'],
                ax = {x: xa, y: ya}[axLetter],
                dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180,
                // note that these two can be either positive or negative
                annSizeFromWidth = outerWidth * Math.cos(dimAngle),
                annSizeFromHeight = outerHeight * Math.sin(dimAngle),
                // but this one is the positive total size
                annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight),
                anchor = options[axLetter + 'anchor'],
                overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1),
                posPx = annPosPx[axLetter],
                basePx,
                textPadShift,
                alignPosition,
                autoAlignFraction,
                textShift;

            /*
             * calculate the *primary* pixel position
             * which is the arrowhead if there is one,
             * otherwise the text anchor point
             */
            if(ax) {
                /*
                 * hide the annotation if it's pointing outside the visible plot
                 * as long as the axis isn't autoranged - then we need to draw it
                 * anyway to get its bounding box. When we're dragging, an axis can
                 * still look autoranged even though it won't be when the drag finishes.
                 */
                var posFraction = ax.r2fraction(options[axLetter]);
                if((gd._dragging || !ax.autorange) && (posFraction < 0 || posFraction > 1)) {
                    if(tailRef === axRef) {
                        posFraction = ax.r2fraction(options['a' + axLetter]);
                        if(posFraction < 0 || posFraction > 1) {
                            annotationIsOffscreen = true;
                        }
                    }
                    else {
                        annotationIsOffscreen = true;
                    }

                    if(annotationIsOffscreen) continue;
                }
                basePx = ax._offset + ax.r2p(options[axLetter]);
                autoAlignFraction = 0.5;
            }
            else {
                if(axLetter === 'x') {
                    alignPosition = options[axLetter];
                    basePx = gs.l + gs.w * alignPosition;
                }
                else {
                    alignPosition = 1 - options[axLetter];
                    basePx = gs.t + gs.h * alignPosition;
                }
                autoAlignFraction = options.showarrow ? 0.5 : alignPosition;
            }

            // now translate this into pixel positions of head, tail, and text
            // as well as paddings for autorange
            if(options.showarrow) {
                posPx.head = basePx;

                var arrowLength = options['a' + axLetter];

                // with an arrow, the text rotates around the anchor point
                textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) -
                    annSizeFromHeight * shiftFraction(0.5, options.yanchor);

                if(tailRef === axRef) {
                    posPx.tail = ax._offset + ax.r2p(arrowLength);
                    // tail is data-referenced: autorange pads the text in px from the tail
                    textPadShift = textShift;
                }
                else {
                    posPx.tail = basePx + arrowLength;
                    // tail is specified in px from head, so autorange also pads vs head
                    textPadShift = textShift + arrowLength;
                }

                posPx.text = posPx.tail + textShift;

                // constrain pixel/paper referenced so the draggers are at least
                // partially visible
                var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height'];
                if(axRef === 'paper') {
                    posPx.head = Lib.constrain(posPx.head, 1, maxPx - 1);
                }
                if(tailRef === 'pixel') {
                    var shiftPlus = -Math.max(posPx.tail - 3, posPx.text),
                        shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx;
                    if(shiftPlus > 0) {
                        posPx.tail += shiftPlus;
                        posPx.text += shiftPlus;
                    }
                    else if(shiftMinus > 0) {
                        posPx.tail -= shiftMinus;
                        posPx.text -= shiftMinus;
                    }
                }

                posPx.tail += overallShift;
                posPx.head += overallShift;
            }
            else {
                // with no arrow, the text rotates and *then* we put the anchor
                // relative to the new bounding box
                textShift = annSize * shiftFraction(autoAlignFraction, anchor);
                textPadShift = textShift;
                posPx.text = basePx + textShift;
            }

            posPx.text += overallShift;
            textShift += overallShift;
            textPadShift += overallShift;

            // padplus/minus are used by autorange
            options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift;
            options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift;

            // size/shift are used during dragging
            options['_' + axLetter + 'size'] = annSize;
            options['_' + axLetter + 'shift'] = textShift;
        }

        if(annotationIsOffscreen) {
            annTextGroupInner.remove();
            return;
        }

        var xShift = 0;
        var yShift = 0;

        if(options.align !== 'left') {
            xShift = (annWidth - textWidth) * (options.align === 'center' ? 0.5 : 1);
        }
        if(options.valign !== 'top') {
            yShift = (annHeight - textHeight) * (options.valign === 'middle' ? 0.5 : 1);
        }

        if(hasMathjax) {
            mathjaxGroup.select('svg').attr({
                x: borderfull + xShift - 1,
                y: borderfull + yShift
            })
            .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null);
        }
        else {
            var texty = borderfull + yShift - anntextBB.top;
            var textx = borderfull + xShift - anntextBB.left;

            annText.call(svgTextUtils.positionText, textx, texty)
                .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null);
        }

        annTextClip.select('rect').call(Drawing.setRect, borderfull, borderfull,
            annWidth, annHeight);

        annTextBG.call(Drawing.setRect, borderwidth / 2, borderwidth / 2,
            outerWidth - borderwidth, outerHeight - borderwidth);

        annTextGroupInner.call(Drawing.setTranslate,
            Math.round(annPosPx.x.text - outerWidth / 2),
            Math.round(annPosPx.y.text - outerHeight / 2));

        /*
         * rotate text and background
         * we already calculated the text center position *as rotated*
         * because we needed that for autoranging anyway, so now whether
         * we have an arrow or not, we rotate about the text center.
         */
        annTextGroup.attr({transform: 'rotate(' + textangle + ',' +
                            annPosPx.x.text + ',' + annPosPx.y.text + ')'});

        /*
         * add the arrow
         * uses options[arrowwidth,arrowcolor,arrowhead] for styling
         * dx and dy are normally zero, but when you are dragging the textbox
         * while the head stays put, dx and dy are the pixel offsets
         */
        var drawArrow = function(dx, dy) {
            annGroup
                .selectAll('.annotation-arrow-g')
                .remove();

            var headX = annPosPx.x.head,
                headY = annPosPx.y.head,
                tailX = annPosPx.x.tail + dx,
                tailY = annPosPx.y.tail + dy,
                textX = annPosPx.x.text + dx,
                textY = annPosPx.y.text + dy,

                // find the edge of the text box, where we'll start the arrow:
                // create transform matrix to rotate the text box corners
                transform = Lib.rotationXYMatrix(textangle, textX, textY),
                applyTransform = Lib.apply2DTransform(transform),
                applyTransform2 = Lib.apply2DTransform2(transform),

                // calculate and transform bounding box
                width = +annTextBG.attr('width'),
                height = +annTextBG.attr('height'),
                xLeft = textX - 0.5 * width,
                xRight = xLeft + width,
                yTop = textY - 0.5 * height,
                yBottom = yTop + height,
                edges = [
                    [xLeft, yTop, xLeft, yBottom],
                    [xLeft, yBottom, xRight, yBottom],
                    [xRight, yBottom, xRight, yTop],
                    [xRight, yTop, xLeft, yTop]
                ].map(applyTransform2);

            // Remove the line if it ends inside the box.  Use ray
            // casting for rotated boxes: see which edges intersect a
            // line from the arrowhead to far away and reduce with xor
            // to get the parity of the number of intersections.
            if(edges.reduce(function(a, x) {
                return a ^
                    !!Lib.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6,
                            x[0], x[1], x[2], x[3]);
            }, false)) {
                // no line or arrow - so quit drawArrow now
                return;
            }

            edges.forEach(function(x) {
                var p = Lib.segmentsIntersect(tailX, tailY, headX, headY,
                            x[0], x[1], x[2], x[3]);
                if(p) {
                    tailX = p.x;
                    tailY = p.y;
                }
            });

            var strokewidth = options.arrowwidth,
                arrowColor = options.arrowcolor,
                arrowSide = options.arrowside;

            var arrowGroup = annGroup.append('g')
                .style({opacity: Color.opacity(arrowColor)})
                .classed('annotation-arrow-g', true);

            var arrow = arrowGroup.append('path')
                .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY)
                .style('stroke-width', strokewidth + 'px')
                .call(Color.stroke, Color.rgb(arrowColor));

            drawArrowHead(arrow, arrowSide, options);

            // the arrow dragger is a small square right at the head, then a line to the tail,
            // all expanded by a stroke width of 6px plus the arrow line width
            if(edits.annotationPosition && arrow.node().parentNode && !subplotId) {
                var arrowDragHeadX = headX;
                var arrowDragHeadY = headY;
                if(options.standoff) {
                    var arrowLength = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2));
                    arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength;
                    arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength;
                }
                var arrowDrag = arrowGroup.append('path')
                    .classed('annotation-arrow', true)
                    .classed('anndrag', true)
                    .attr({
                        d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY),
                        transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')'
                    })
                    .style('stroke-width', (strokewidth + 6) + 'px')
                    .call(Color.stroke, 'rgba(0,0,0,0)')
                    .call(Color.fill, 'rgba(0,0,0,0)');

                var update,
                    annx0,
                    anny0;

                // dragger for the arrow & head: translates the whole thing
                // (head/tail/text) all together
                dragElement.init({
                    element: arrowDrag.node(),
                    gd: gd,
                    prepFn: function() {
                        var pos = Drawing.getTranslate(annTextGroupInner);

                        annx0 = pos.x;
                        anny0 = pos.y;
                        update = {};
                        if(xa && xa.autorange) {
                            update[xa._name + '.autorange'] = true;
                        }
                        if(ya && ya.autorange) {
                            update[ya._name + '.autorange'] = true;
                        }
                    },
                    moveFn: function(dx, dy) {
                        var annxy0 = applyTransform(annx0, anny0),
                            xcenter = annxy0[0] + dx,
                            ycenter = annxy0[1] + dy;
                        annTextGroupInner.call(Drawing.setTranslate, xcenter, ycenter);

                        update[annbase + '.x'] = xa ?
                            xa.p2r(xa.r2p(options.x) + dx) :
                            (options.x + (dx / gs.w));
                        update[annbase + '.y'] = ya ?
                            ya.p2r(ya.r2p(options.y) + dy) :
                            (options.y - (dy / gs.h));

                        if(options.axref === options.xref) {
                            update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx);
                        }

                        if(options.ayref === options.yref) {
                            update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy);
                        }

                        arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')');
                        annTextGroup.attr({
                            transform: 'rotate(' + textangle + ',' +
                                   xcenter + ',' + ycenter + ')'
                        });
                    },
                    doneFn: function() {
                        Registry.call('relayout', gd, update);
                        var notesBox = document.querySelector('.js-notes-box-panel');
                        if(notesBox) notesBox.redraw(notesBox.selectedObj);
                    }
                });
            }
        };

        if(options.showarrow) drawArrow(0, 0);

        // user dragging the annotation (text, not arrow)
        if(editTextPosition) {
            var update,
                baseTextTransform;

            // dragger for the textbox: if there's an arrow, just drag the
            // textbox and tail, leave the head untouched
            dragElement.init({
                element: annTextGroupInner.node(),
                gd: gd,
                prepFn: function() {
                    baseTextTransform = annTextGroup.attr('transform');
                    update = {};
                },
                moveFn: function(dx, dy) {
                    var csr = 'pointer';
                    if(options.showarrow) {
                        if(options.axref === options.xref) {
                            update[annbase + '.ax'] = xa.p2r(xa.r2p(options.ax) + dx);
                        } else {
                            update[annbase + '.ax'] = options.ax + dx;
                        }

                        if(options.ayref === options.yref) {
                            update[annbase + '.ay'] = ya.p2r(ya.r2p(options.ay) + dy);
                        } else {
                            update[annbase + '.ay'] = options.ay + dy;
                        }

                        drawArrow(dx, dy);
                    }
                    else if(!subplotId) {
                        if(xa) {
                            update[annbase + '.x'] = xa.p2r(xa.r2p(options.x) + dx);

                        } else {
                            var widthFraction = options._xsize / gs.w,
                                xLeft = options.x + (options._xshift - options.xshift) / gs.w -
                                    widthFraction / 2;

                            update[annbase + '.x'] = dragElement.align(xLeft + dx / gs.w,
                                widthFraction, 0, 1, options.xanchor);
                        }

                        if(ya) {
                            update[annbase + '.y'] = ya.p2r(ya.r2p(options.y) + dy);
                        } else {
                            var heightFraction = options._ysize / gs.h,
                                yBottom = options.y - (options._yshift + options.yshift) / gs.h -
                                    heightFraction / 2;

                            update[annbase + '.y'] = dragElement.align(yBottom - dy / gs.h,
                                heightFraction, 0, 1, options.yanchor);
                        }
                        if(!xa || !ya) {
                            csr = dragElement.getCursor(
                                xa ? 0.5 : update[annbase + '.x'],
                                ya ? 0.5 : update[annbase + '.y'],
                                options.xanchor, options.yanchor
                            );
                        }
                    }
                    else return;

                    annTextGroup.attr({
                        transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform
                    });

                    setCursor(annTextGroupInner, csr);
                },
                doneFn: function() {
                    setCursor(annTextGroupInner);
                    Registry.call('relayout', gd, update);
                    var notesBox = document.querySelector('.js-notes-box-panel');
                    if(notesBox) notesBox.redraw(notesBox.selectedObj);
                }
            });
        }
    }

    if(edits.annotationText) {
        annText.call(svgTextUtils.makeEditable, {delegate: annTextGroupInner, gd: gd})
            .call(textLayout)
            .on('edit', function(_text) {
                options.text = _text;
                this.call(textLayout);

                var update = {};
                update[annbase + '.text'] = options.text;

                if(xa && xa.autorange) {
                    update[xa._name + '.autorange'] = true;
                }
                if(ya && ya.autorange) {
                    update[ya._name + '.autorange'] = true;
                }

                Registry.call('relayout', gd, update);
            });
    }
    else annText.call(textLayout);
}

},{"../../lib":164,"../../lib/setcursor":183,"../../lib/svg_text_utils":185,"../../plots/cartesian/axes":206,"../../plots/plots":245,"../../registry":254,"../color":43,"../dragelement":65,"../drawing":68,"../fx":85,"./draw_arrow_head":35,"d3":6}],35:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Color = require('../color');

var ARROWPATHS = require('./arrow_paths');

/**
 * Add arrowhead(s) to a path or line element
 *
 * @param {d3.selection} el3: a d3-selected line or path element
 *
 * @param {string} ends: 'none', 'start', 'end', or 'start+end' for which ends get arrowheads
 *
 * @param {object} options: style information. Must have all the following:
 * @param {number} options.arrowhead: end head style - see ./arrow_paths
 * @param {number} options.startarrowhead: start head style - see ./arrow_paths
 * @param {number} options.arrowsize: relative size of the end head vs line width
 * @param {number} options.startarrowsize: relative size of the start head vs line width
 * @param {number} options.standoff: distance in px to move the end arrow point from its target
 * @param {number} options.startstandoff: distance in px to move the start arrow point from its target
 * @param {number} options.arrowwidth: width of the arrow line
 * @param {string} options.arrowcolor: color of the arrow line, for the head to match
 *     Note that the opacity of this color is ignored, as it's assumed the container
 *     of both the line and head has opacity applied to it so there isn't greater opacity
 *     where they overlap.
 */
module.exports = function drawArrowHead(el3, ends, options) {
    var el = el3.node();
    var headStyle = ARROWPATHS[options.arrowhead || 0];
    var startHeadStyle = ARROWPATHS[options.startarrowhead || 0];
    var scale = (options.arrowwidth || 1) * (options.arrowsize || 1);
    var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1);
    var doStart = ends.indexOf('start') >= 0;
    var doEnd = ends.indexOf('end') >= 0;
    var backOff = headStyle.backoff * scale + options.standoff;
    var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff;

    var start, end, startRot, endRot;

    if(el.nodeName === 'line') {
        start = {x: +el3.attr('x1'), y: +el3.attr('y1')};
        end = {x: +el3.attr('x2'), y: +el3.attr('y2')};

        var dx = start.x - end.x;
        var dy = start.y - end.y;

        startRot = Math.atan2(dy, dx);
        endRot = startRot + Math.PI;
        if(backOff && startBackOff) {
            if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) {
                hideLine();
                return;
            }
        }

        if(backOff) {
            if(backOff * backOff > dx * dx + dy * dy) {
                hideLine();
                return;
            }
            var backOffX = backOff * Math.cos(startRot),
                backOffY = backOff * Math.sin(startRot);

            end.x += backOffX;
            end.y += backOffY;
            el3.attr({x2: end.x, y2: end.y});

        }

        if(startBackOff) {
            if(startBackOff * startBackOff > dx * dx + dy * dy) {
                hideLine();
                return;
            }
            var startBackOffX = startBackOff * Math.cos(startRot),
                startbackOffY = startBackOff * Math.sin(startRot);

            start.x -= startBackOffX;
            start.y -= startbackOffY;
            el3.attr({x1: start.x, y1: start.y});

        }
    }
    else if(el.nodeName === 'path') {
        var pathlen = el.getTotalLength(),
            // using dash to hide the backOff region of the path.
            // if we ever allow dash for the arrow we'll have to
            // do better than this hack... maybe just manually
            // combine the two
            dashArray = '';

        if(pathlen < backOff + startBackOff) {
            hideLine();
            return;
        }


        var start0 = el.getPointAtLength(0);
        var dstart = el.getPointAtLength(0.1);

        startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
        start = el.getPointAtLength(Math.min(startBackOff, pathlen));

        dashArray = '0px,' + startBackOff + 'px,';

        var end0 = el.getPointAtLength(pathlen);
        var dend = el.getPointAtLength(pathlen - 0.1);

        endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
        end = el.getPointAtLength(Math.max(0, pathlen - backOff));

        var shortening = dashArray ? startBackOff + backOff : backOff;
        dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px';

        el3.style('stroke-dasharray', dashArray);
    }

    function hideLine() { el3.style('stroke-dasharray', '0px,100px'); }

    function drawhead(arrowHeadStyle, p, rot, arrowScale) {
        if(!arrowHeadStyle.path) return;
        if(arrowHeadStyle.noRotate) rot = 0;

        d3.select(el.parentNode).append('path')
            .attr({
                'class': el3.attr('class'),
                d: arrowHeadStyle.path,
                transform:
                    'translate(' + p.x + ',' + p.y + ')' +
                    (rot ? 'rotate(' + (rot * 180 / Math.PI) + ')' : '') +
                    'scale(' + arrowScale + ')'
            })
            .style({
                fill: Color.rgb(options.arrowcolor),
                'stroke-width': 0
            });
    }

    if(doStart) drawhead(startHeadStyle, start, startRot, startScale);
    if(doEnd) drawhead(headStyle, end, endRot, scale);
};

},{"../color":43,"./arrow_paths":27,"d3":6}],36:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawModule = require('./draw');
var clickModule = require('./click');

module.exports = {
    moduleType: 'component',
    name: 'annotations',

    layoutAttributes: require('./attributes'),
    supplyLayoutDefaults: require('./defaults'),
    includeBasePlot: require('../../plots/cartesian/include_components')('annotations'),

    calcAutorange: require('./calc_autorange'),
    draw: drawModule.draw,
    drawOne: drawModule.drawOne,
    drawRaw: drawModule.drawRaw,

    hasClickToShow: clickModule.hasClickToShow,
    onClick: clickModule.onClick,

    convertCoords: require('./convert_coords')
};

},{"../../plots/cartesian/include_components":216,"./attributes":28,"./calc_autorange":29,"./click":30,"./convert_coords":32,"./defaults":33,"./draw":34}],37:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var annAtts = require('../annotations/attributes');
var overrideAll = require('../../plot_api/edit_types').overrideAll;

module.exports = overrideAll({
    _isLinkedToArray: 'annotation',

    visible: annAtts.visible,
    x: {
        valType: 'any',
        
        
    },
    y: {
        valType: 'any',
        
        
    },
    z: {
        valType: 'any',
        
        
    },
    ax: {
        valType: 'number',
        
        
    },
    ay: {
        valType: 'number',
        
        
    },

    xanchor: annAtts.xanchor,
    xshift: annAtts.xshift,
    yanchor: annAtts.yanchor,
    yshift: annAtts.yshift,

    text: annAtts.text,
    textangle: annAtts.textangle,
    font: annAtts.font,
    width: annAtts.width,
    height: annAtts.height,
    opacity: annAtts.opacity,
    align: annAtts.align,
    valign: annAtts.valign,
    bgcolor: annAtts.bgcolor,
    bordercolor: annAtts.bordercolor,
    borderpad: annAtts.borderpad,
    borderwidth: annAtts.borderwidth,
    showarrow: annAtts.showarrow,
    arrowcolor: annAtts.arrowcolor,
    arrowhead: annAtts.arrowhead,
    startarrowhead: annAtts.startarrowhead,
    arrowside: annAtts.arrowside,
    arrowsize: annAtts.arrowsize,
    startarrowsize: annAtts.startarrowsize,
    arrowwidth: annAtts.arrowwidth,
    standoff: annAtts.standoff,
    startstandoff: annAtts.startstandoff,
    hovertext: annAtts.hovertext,
    hoverlabel: annAtts.hoverlabel,
    captureevents: annAtts.captureevents,

    // maybes later?
    // clicktoshow: annAtts.clicktoshow,
    // xclick: annAtts.xclick,
    // yclick: annAtts.yclick,

    // not needed!
    // axref: 'pixel'
    // ayref: 'pixel'
    // xref: 'x'
    // yref: 'y
    // zref: 'z'
}, 'calc', 'from-root');

},{"../../plot_api/edit_types":191,"../annotations/attributes":28}],38:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');

module.exports = function convert(scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var anns = fullSceneLayout.annotations;

    for(var i = 0; i < anns.length; i++) {
        mockAnnAxes(anns[i], scene);
    }

    scene.fullLayout._infolayer
        .selectAll('.annotation-' + scene.id)
        .remove();
};

function mockAnnAxes(ann, scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var domain = fullSceneLayout.domain;
    var size = scene.fullLayout._size;

    var base = {
        // this gets fill in on render
        pdata: null,

        // to get setConvert to not execute cleanly
        type: 'linear',

        // don't try to update them on `editable: true`
        autorange: false,

        // set infinite range so that annotation draw routine
        // does not try to remove 'outside-range' annotations,
        // this case is handled in the render loop
        range: [-Infinity, Infinity]
    };

    ann._xa = {};
    Lib.extendFlat(ann._xa, base);
    Axes.setConvert(ann._xa);
    ann._xa._offset = size.l + domain.x[0] * size.w;
    ann._xa.l2p = function() {
        return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]);
    };

    ann._ya = {};
    Lib.extendFlat(ann._ya, base);
    Axes.setConvert(ann._ya);
    ann._ya._offset = size.t + (1 - domain.y[1]) * size.h;
    ann._ya.l2p = function() {
        return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]);
    };
}

},{"../../lib":164,"../../plots/cartesian/axes":206}],39:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var handleArrayContainerDefaults = require('../../plots/array_container_defaults');
var handleAnnotationCommonDefaults = require('../annotations/common_defaults');
var attributes = require('./attributes');

module.exports = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) {
    handleArrayContainerDefaults(sceneLayoutIn, sceneLayoutOut, {
        name: 'annotations',
        handleItemDefaults: handleAnnotationDefaults,
        fullLayout: opts.fullLayout
    });
};

function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts, itemOpts) {
    function coerce(attr, dflt) {
        return Lib.coerce(annIn, annOut, attributes, attr, dflt);
    }

    function coercePosition(axLetter) {
        var axName = axLetter + 'axis';

        // mock in such way that getFromId grabs correct 3D axis
        var gdMock = { _fullLayout: {} };
        gdMock._fullLayout[axName] = sceneLayout[axName];

        return Axes.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5);
    }


    var visible = coerce('visible', !itemOpts.itemIsNotPlainObject);
    if(!visible) return annOut;

    handleAnnotationCommonDefaults(annIn, annOut, opts.fullLayout, coerce);

    coercePosition('x');
    coercePosition('y');
    coercePosition('z');

    // if you have one coordinate you should all three
    Lib.noneOrAll(annIn, annOut, ['x', 'y', 'z']);

    // hard-set here for completeness
    annOut.xref = 'x';
    annOut.yref = 'y';
    annOut.zref = 'z';

    coerce('xanchor');
    coerce('yanchor');
    coerce('xshift');
    coerce('yshift');

    if(annOut.showarrow) {
        annOut.axref = 'pixel';
        annOut.ayref = 'pixel';

        // TODO maybe default values should be bigger than the 2D case?
        coerce('ax', -10);
        coerce('ay', -30);

        // if you have one part of arrow length you should have both
        Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
    }

    return annOut;
}

},{"../../lib":164,"../../plots/array_container_defaults":202,"../../plots/cartesian/axes":206,"../annotations/common_defaults":31,"./attributes":37}],40:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var drawRaw = require('../annotations/draw').drawRaw;
var project = require('../../plots/gl3d/project');
var axLetters = ['x', 'y', 'z'];

module.exports = function draw(scene) {
    var fullSceneLayout = scene.fullSceneLayout;
    var dataScale = scene.dataScale;
    var anns = fullSceneLayout.annotations;

    for(var i = 0; i < anns.length; i++) {
        var ann = anns[i];
        var annotationIsOffscreen = false;

        for(var j = 0; j < 3; j++) {
            var axLetter = axLetters[j];
            var pos = ann[axLetter];
            var ax = fullSceneLayout[axLetter + 'axis'];
            var posFraction = ax.r2fraction(pos);

            if(posFraction < 0 || posFraction > 1) {
                annotationIsOffscreen = true;
                break;
            }
        }

        if(annotationIsOffscreen) {
            scene.fullLayout._infolayer
                .select('.annotation-' + scene.id + '[data-index="' + i + '"]')
                .remove();
        } else {
            ann._pdata = project(scene.glplot.cameraParams, [
                fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0],
                fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1],
                fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2]
            ]);

            drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya);
        }
    }
};

},{"../../plots/gl3d/project":235,"../annotations/draw":34}],41:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');

module.exports = {
    moduleType: 'component',
    name: 'annotations3d',

    schema: {
        subplots: {
            scene: {annotations: require('./attributes')}
        }
    },

    layoutAttributes: require('./attributes'),
    handleDefaults: require('./defaults'),
    includeBasePlot: includeGL3D,

    convert: require('./convert'),
    draw: require('./draw')
};

function includeGL3D(layoutIn, layoutOut) {
    var GL3D = Registry.subplotsRegistry.gl3d;
    if(!GL3D) return;

    var attrRegex = GL3D.attrRegex;

    var keys = Object.keys(layoutIn);
    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];
        if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) {
            Lib.pushUnique(layoutOut._basePlotModules, GL3D);
            Lib.pushUnique(layoutOut._subplots.gl3d, k);
        }
    }
}

},{"../../lib":164,"../../registry":254,"./attributes":37,"./convert":38,"./defaults":39,"./draw":40}],42:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


// IMPORTANT - default colors should be in hex for compatibility
exports.defaults = [
    '#1f77b4',  // muted blue
    '#ff7f0e',  // safety orange
    '#2ca02c',  // cooked asparagus green
    '#d62728',  // brick red
    '#9467bd',  // muted purple
    '#8c564b',  // chestnut brown
    '#e377c2',  // raspberry yogurt pink
    '#7f7f7f',  // middle gray
    '#bcbd22',  // curry yellow-green
    '#17becf'   // blue-teal
];

exports.defaultLine = '#444';

exports.lightLine = '#eee';

exports.background = '#fff';

exports.borderLine = '#BEC8D9';

// with axis.color and Color.interp we aren't using lightLine
// itself anymore, instead interpolating between axis.color
// and the background color using tinycolor.mix. lightFraction
// gives back exactly lightLine if the other colors are defaults.
exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);

},{}],43:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var tinycolor = require('tinycolor2');
var isNumeric = require('fast-isnumeric');

var color = module.exports = {};

var colorAttrs = require('./attributes');
color.defaults = colorAttrs.defaults;
var defaultLine = color.defaultLine = colorAttrs.defaultLine;
color.lightLine = colorAttrs.lightLine;
var background = color.background = colorAttrs.background;

/*
 * tinyRGB: turn a tinycolor into an rgb string, but
 * unlike the built-in tinycolor.toRgbString this never includes alpha
 */
color.tinyRGB = function(tc) {
    var c = tc.toRgb();
    return 'rgb(' + Math.round(c.r) + ', ' +
        Math.round(c.g) + ', ' + Math.round(c.b) + ')';
};

color.rgb = function(cstr) { return color.tinyRGB(tinycolor(cstr)); };

color.opacity = function(cstr) { return cstr ? tinycolor(cstr).getAlpha() : 0; };

color.addOpacity = function(cstr, op) {
    var c = tinycolor(cstr).toRgb();
    return 'rgba(' + Math.round(c.r) + ', ' +
        Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')';
};

// combine two colors into one apparent color
// if back has transparency or is missing,
// color.background is assumed behind it
color.combine = function(front, back) {
    var fc = tinycolor(front).toRgb();
    if(fc.a === 1) return tinycolor(front).toRgbString();

    var bc = tinycolor(back || background).toRgb(),
        bcflat = bc.a === 1 ? bc : {
            r: 255 * (1 - bc.a) + bc.r * bc.a,
            g: 255 * (1 - bc.a) + bc.g * bc.a,
            b: 255 * (1 - bc.a) + bc.b * bc.a
        },
        fcflat = {
            r: bcflat.r * (1 - fc.a) + fc.r * fc.a,
            g: bcflat.g * (1 - fc.a) + fc.g * fc.a,
            b: bcflat.b * (1 - fc.a) + fc.b * fc.a
        };
    return tinycolor(fcflat).toRgbString();
};

/*
 * Create a color that contrasts with cstr.
 *
 * If cstr is a dark color, we lighten it; if it's light, we darken.
 *
 * If lightAmount / darkAmount are used, we adjust by these percentages,
 * otherwise we go all the way to white or black.
 */
color.contrast = function(cstr, lightAmount, darkAmount) {
    var tc = tinycolor(cstr);

    if(tc.getAlpha() !== 1) tc = tinycolor(color.combine(cstr, background));

    var newColor = tc.isDark() ?
        (lightAmount ? tc.lighten(lightAmount) : background) :
        (darkAmount ? tc.darken(darkAmount) : defaultLine);

    return newColor.toString();
};

color.stroke = function(s, c) {
    var tc = tinycolor(c);
    s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()});
};

color.fill = function(s, c) {
    var tc = tinycolor(c);
    s.style({
        'fill': color.tinyRGB(tc),
        'fill-opacity': tc.getAlpha()
    });
};

// search container for colors with the deprecated rgb(fractions) format
// and convert them to rgb(0-255 values)
color.clean = function(container) {
    if(!container || typeof container !== 'object') return;

    var keys = Object.keys(container),
        i,
        j,
        key,
        val;

    for(i = 0; i < keys.length; i++) {
        key = keys[i];
        val = container[key];

        // only sanitize keys that end in "color" or "colorscale"
        if(key.substr(key.length - 5) === 'color') {
            if(Array.isArray(val)) {
                for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
            }
            else container[key] = cleanOne(val);
        }
        else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) {
            // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]]
            for(j = 0; j < val.length; j++) {
                if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
            }
        }
        // recurse into arrays of objects, and plain objects
        else if(Array.isArray(val)) {
            var el0 = val[0];
            if(!Array.isArray(el0) && el0 && typeof el0 === 'object') {
                for(j = 0; j < val.length; j++) color.clean(val[j]);
            }
        }
        else if(val && typeof val === 'object') color.clean(val);
    }
};

function cleanOne(val) {
    if(isNumeric(val) || typeof val !== 'string') return val;

    var valTrim = val.trim();
    if(valTrim.substr(0, 3) !== 'rgb') return val;

    var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
    if(!match) return val;

    var parts = match[1].trim().split(/\s*[\s,]\s*/),
        rgba = valTrim.charAt(3) === 'a' && parts.length === 4;
    if(!rgba && parts.length !== 3) return val;

    for(var i = 0; i < parts.length; i++) {
        if(!parts[i].length) return val;
        parts[i] = Number(parts[i]);

        // all parts must be non-negative numbers
        if(!(parts[i] >= 0)) return val;
        // alpha>1 gets clipped to 1
        if(i === 3) {
            if(parts[i] > 1) parts[i] = 1;
        }
        // r, g, b must be < 1 (ie 1 itself is not allowed)
        else if(parts[i] >= 1) return val;
    }

    var rgbStr = Math.round(parts[0] * 255) + ', ' +
        Math.round(parts[1] * 255) + ', ' +
        Math.round(parts[2] * 255);

    if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')';
    return 'rgb(' + rgbStr + ')';
}

},{"./attributes":42,"fast-isnumeric":9,"tinycolor2":25}],44:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var axesAttrs = require('../../plots/cartesian/layout_attributes');
var fontAttrs = require('../../plots/font_attributes');
var extendFlat = require('../../lib/extend').extendFlat;
var overrideAll = require('../../plot_api/edit_types').overrideAll;


module.exports = overrideAll({
// TODO: only right is supported currently
//     orient: {
//         valType: 'enumerated',
//         
//         values: ['left', 'right', 'top', 'bottom'],
//         dflt: 'right',
//         
//     },
    thicknessmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'pixels',
        
    },
    thickness: {
        valType: 'number',
        
        min: 0,
        dflt: 30,
        
    },
    lenmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'fraction',
        
    },
    len: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    x: {
        valType: 'number',
        dflt: 1.02,
        min: -2,
        max: 3,
        
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'left',
        
        
    },
    xpad: {
        valType: 'number',
        
        min: 0,
        dflt: 10,
        
    },
    y: {
        valType: 'number',
        
        dflt: 0.5,
        min: -2,
        max: 3,
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        
        dflt: 'middle',
        
    },
    ypad: {
        valType: 'number',
        
        min: 0,
        dflt: 10,
        
    },
    // a possible line around the bar itself
    outlinecolor: axesAttrs.linecolor,
    outlinewidth: axesAttrs.linewidth,
    // Should outlinewidth have {dflt: 0} ?
    // another possible line outside the padding and tick labels
    bordercolor: axesAttrs.linecolor,
    borderwidth: {
        valType: 'number',
        
        min: 0,
        dflt: 0,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: 'rgba(0,0,0,0)',
        
    },
    // tick and title properties named and function exactly as in axes
    tickmode: axesAttrs.tickmode,
    nticks: axesAttrs.nticks,
    tick0: axesAttrs.tick0,
    dtick: axesAttrs.dtick,
    tickvals: axesAttrs.tickvals,
    ticktext: axesAttrs.ticktext,
    ticks: extendFlat({}, axesAttrs.ticks, {dflt: ''}),
    ticklen: axesAttrs.ticklen,
    tickwidth: axesAttrs.tickwidth,
    tickcolor: axesAttrs.tickcolor,
    showticklabels: axesAttrs.showticklabels,
    tickfont: fontAttrs({
        
    }),
    tickangle: axesAttrs.tickangle,
    tickformat: axesAttrs.tickformat,
    tickformatstops: axesAttrs.tickformatstops,
    tickprefix: axesAttrs.tickprefix,
    showtickprefix: axesAttrs.showtickprefix,
    ticksuffix: axesAttrs.ticksuffix,
    showticksuffix: axesAttrs.showticksuffix,
    separatethousands: axesAttrs.separatethousands,
    exponentformat: axesAttrs.exponentformat,
    showexponent: axesAttrs.showexponent,
    title: {
        valType: 'string',
        
        
    },
    titlefont: fontAttrs({
        
    }),
    titleside: {
        valType: 'enumerated',
        values: ['right', 'top', 'bottom'],
        
        dflt: 'top',
        
    }
}, 'colorbars', 'from-root');

},{"../../lib/extend":157,"../../plot_api/edit_types":191,"../../plots/cartesian/layout_attributes":218,"../../plots/font_attributes":232}],45:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    cn: {
        colorbar: 'colorbar',
        cbbg: 'cbbg',
        cbfill: 'cbfill',
        cbfills: 'cbfills',
        cbline: 'cbline',
        cblines: 'cblines',
        cbaxis: 'cbaxis',
        cbtitleunshift: 'cbtitleunshift',
        cbtitle: 'cbtitle',
        cboutline: 'cboutline',
        crisp: 'crisp',
        jsPlaceholder: 'js-placeholder'
    }
};

},{}],46:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var handleTickValueDefaults = require('../../plots/cartesian/tick_value_defaults');
var handleTickMarkDefaults = require('../../plots/cartesian/tick_mark_defaults');
var handleTickLabelDefaults = require('../../plots/cartesian/tick_label_defaults');

var attributes = require('./attributes');


module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
    var colorbarOut = containerOut.colorbar = {},
        colorbarIn = containerIn.colorbar || {};

    function coerce(attr, dflt) {
        return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
    }

    var thicknessmode = coerce('thicknessmode');
    coerce('thickness', (thicknessmode === 'fraction') ?
        30 / (layout.width - layout.margin.l - layout.margin.r) :
        30
    );

    var lenmode = coerce('lenmode');
    coerce('len', (lenmode === 'fraction') ?
        1 :
        layout.height - layout.margin.t - layout.margin.b
    );

    coerce('x');
    coerce('xanchor');
    coerce('xpad');
    coerce('y');
    coerce('yanchor');
    coerce('ypad');
    Lib.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']);

    coerce('outlinecolor');
    coerce('outlinewidth');
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('bgcolor');

    handleTickValueDefaults(colorbarIn, colorbarOut, coerce, 'linear');

    var opts = {outerTicks: false, font: layout.font};
    handleTickLabelDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
    handleTickMarkDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);

    coerce('title', layout._dfltTitle.colorbar);
    Lib.coerceFont(coerce, 'titlefont', layout.font);
    coerce('titleside');
};

},{"../../lib":164,"../../plots/cartesian/tick_label_defaults":225,"../../plots/cartesian/tick_mark_defaults":226,"../../plots/cartesian/tick_value_defaults":227,"./attributes":44}],47:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var tinycolor = require('tinycolor2');

var Plots = require('../../plots/plots');
var Registry = require('../../registry');
var Axes = require('../../plots/cartesian/axes');
var dragElement = require('../dragelement');
var Lib = require('../../lib');
var extendFlat = require('../../lib/extend').extendFlat;
var setCursor = require('../../lib/setcursor');
var Drawing = require('../drawing');
var Color = require('../color');
var Titles = require('../titles');
var svgTextUtils = require('../../lib/svg_text_utils');
var LINE_SPACING = require('../../constants/alignment').LINE_SPACING;

var handleAxisDefaults = require('../../plots/cartesian/axis_defaults');
var handleAxisPositionDefaults = require('../../plots/cartesian/position_defaults');
var axisLayoutAttrs = require('../../plots/cartesian/layout_attributes');

var attributes = require('./attributes');
var cn = require('./constants').cn;

module.exports = function draw(gd, id) {
    // opts: options object, containing everything from attributes
    // plus a few others that are the equivalent of the colorbar "data"
    var opts = {};
    Object.keys(attributes).forEach(function(k) {
        opts[k] = null;
    });
    // fillcolor can be a d3 scale, domain is z values, range is colors
    // or leave it out for no fill,
    // or set to a string constant for single-color fill
    opts.fillcolor = null;
    // line.color has the same options as fillcolor
    opts.line = {color: null, width: null, dash: null};
    // levels of lines to draw.
    // note that this DOES NOT determine the extent of the bar
    // that's given by the domain of fillcolor
    // (or line.color if no fillcolor domain)
    opts.levels = {start: null, end: null, size: null};
    // separate fill levels (for example, heatmap coloring of a
    // contour map) if this is omitted, fillcolors will be
    // evaluated halfway between levels
    opts.filllevels = null;

    function component() {
        var fullLayout = gd._fullLayout,
            gs = fullLayout._size;
        if((typeof opts.fillcolor !== 'function') &&
                (typeof opts.line.color !== 'function')) {
            fullLayout._infolayer.selectAll('g.' + id).remove();
            return;
        }
        var zrange = d3.extent(((typeof opts.fillcolor === 'function') ?
            opts.fillcolor : opts.line.color).domain());
        var linelevels = [];
        var filllevels = [];
        var linecolormap = typeof opts.line.color === 'function' ?
            opts.line.color : function() { return opts.line.color; };
        var fillcolormap = typeof opts.fillcolor === 'function' ?
            opts.fillcolor : function() { return opts.fillcolor; };
        var l;
        var i;

        var l0 = opts.levels.end + opts.levels.size / 100,
            ls = opts.levels.size,
            zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]),
            zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]);
        for(i = 0; i < 1e5; i++) {
            l = opts.levels.start + i * ls;
            if(ls > 0 ? (l >= l0) : (l <= l0)) break;
            if(l > zr0 && l < zr1) linelevels.push(l);
        }

        if(typeof opts.fillcolor === 'function') {
            if(opts.filllevels) {
                l0 = opts.filllevels.end + opts.filllevels.size / 100;
                ls = opts.filllevels.size;
                for(i = 0; i < 1e5; i++) {
                    l = opts.filllevels.start + i * ls;
                    if(ls > 0 ? (l >= l0) : (l <= l0)) break;
                    if(l > zrange[0] && l < zrange[1]) filllevels.push(l);
                }
            }
            else {
                filllevels = linelevels.map(function(v) {
                    return v - opts.levels.size / 2;
                });
                filllevels.push(filllevels[filllevels.length - 1] +
                    opts.levels.size);
            }
        }
        else if(opts.fillcolor && typeof opts.fillcolor === 'string') {
            // doesn't matter what this value is, with a single value
            // we'll make a single fill rect covering the whole bar
            filllevels = [0];
        }

        if(opts.levels.size < 0) {
            linelevels.reverse();
            filllevels.reverse();
        }

        // now make a Plotly Axes object to scale with and draw ticks
        // TODO: does not support orientation other than right

        // we calculate pixel sizes based on the specified graph size,
        // not the actual (in case something pushed the margins around)
        // which is a little odd but avoids an odd iterative effect
        // when the colorbar itself is pushing the margins.
        // but then the fractional size is calculated based on the
        // actual graph size, so that the axes will size correctly.
        var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b,
            originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r,
            thickPx = Math.round(opts.thickness *
                (opts.thicknessmode === 'fraction' ? originalPlotWidth : 1)),
            thickFrac = thickPx / gs.w,
            lenPx = Math.round(opts.len *
                (opts.lenmode === 'fraction' ? originalPlotHeight : 1)),
            lenFrac = lenPx / gs.h,
            xpadFrac = opts.xpad / gs.w,
            yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2,
            ypadFrac = opts.ypad / gs.h,

            // x positioning: do it initially just for left anchor,
            // then fix at the end (since we don't know the width yet)
            xLeft = Math.round(opts.x * gs.w + opts.xpad),
            // for dragging... this is getting a little muddled...
            xLeftFrac = opts.x - thickFrac *
                ({middle: 0.5, right: 1}[opts.xanchor]||0),

            // y positioning we can do correctly from the start
            yBottomFrac = opts.y + lenFrac *
                (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5),
            yBottomPx = Math.round(gs.h * (1 - yBottomFrac)),
            yTopPx = yBottomPx - lenPx,
            titleEl,
            cbAxisIn = {
                type: 'linear',
                range: zrange,
                tickmode: opts.tickmode,
                nticks: opts.nticks,
                tick0: opts.tick0,
                dtick: opts.dtick,
                tickvals: opts.tickvals,
                ticktext: opts.ticktext,
                ticks: opts.ticks,
                ticklen: opts.ticklen,
                tickwidth: opts.tickwidth,
                tickcolor: opts.tickcolor,
                showticklabels: opts.showticklabels,
                tickfont: opts.tickfont,
                tickangle: opts.tickangle,
                tickformat: opts.tickformat,
                exponentformat: opts.exponentformat,
                separatethousands: opts.separatethousands,
                showexponent: opts.showexponent,
                showtickprefix: opts.showtickprefix,
                tickprefix: opts.tickprefix,
                showticksuffix: opts.showticksuffix,
                ticksuffix: opts.ticksuffix,
                title: opts.title,
                titlefont: opts.titlefont,
                showline: true,
                anchor: 'free',
                position: 1
            },
            cbAxisOut = {
                type: 'linear',
                _id: 'y' + id
            },
            axisOptions = {
                letter: 'y',
                font: fullLayout.font,
                noHover: true,
                calendar: fullLayout.calendar  // not really necessary (yet?)
            };

        // Coerce w.r.t. Axes layoutAttributes:
        // re-use axes.js logic without updating _fullData
        function coerce(attr, dflt) {
            return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
        }

        // Prepare the Plotly axis object
        handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout);
        handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);

        // position can't go in through supplyDefaults
        // because that restricts it to [0,1]
        cbAxisOut.position = opts.x + xpadFrac + thickFrac;

        // save for other callers to access this axis
        component.axis = cbAxisOut;

        if(['top', 'bottom'].indexOf(opts.titleside) !== -1) {
            cbAxisOut.titleside = opts.titleside;
            cbAxisOut.titlex = opts.x + xpadFrac;
            cbAxisOut.titley = yBottomFrac +
                (opts.titleside === 'top' ? lenFrac - ypadFrac : ypadFrac);
        }

        if(opts.line.color && opts.tickmode === 'auto') {
            cbAxisOut.tickmode = 'linear';
            cbAxisOut.tick0 = opts.levels.start;
            var dtick = opts.levels.size;
            // expand if too many contours, so we don't get too many ticks
            var autoNtick = Lib.constrain(
                    (yBottomPx - yTopPx) / 50, 4, 15) + 1,
                dtFactor = (zrange[1] - zrange[0]) /
                    ((opts.nticks || autoNtick) * dtick);
            if(dtFactor > 1) {
                var dtexp = Math.pow(10, Math.floor(
                    Math.log(dtFactor) / Math.LN10));
                dtick *= dtexp * Lib.roundUp(dtFactor / dtexp, [2, 5, 10]);
                // if the contours are at round multiples, reset tick0
                // so they're still at round multiples. Otherwise,
                // keep the first label on the first contour level
                if((Math.abs(opts.levels.start) /
                        opts.levels.size + 1e-6) % 1 < 2e-6) {
                    cbAxisOut.tick0 = 0;
                }
            }
            cbAxisOut.dtick = dtick;
        }

        // set domain after init, because we may want to
        // allow it outside [0,1]
        cbAxisOut.domain = [
            yBottomFrac + ypadFrac,
            yBottomFrac + lenFrac - ypadFrac
        ];
        cbAxisOut.setScale();

        // now draw the elements
        var container = Lib.ensureSingle(fullLayout._infolayer, 'g', id, function(s) {
            s.classed(cn.colorbar, true)
                .each(function() {
                    var s = d3.select(this);
                    s.append('rect').classed(cn.cbbg, true);
                    s.append('g').classed(cn.cbfills, true);
                    s.append('g').classed(cn.cblines, true);
                    s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true);
                    s.append('g').classed(cn.cbtitleunshift, true)
                        .append('g').classed(cn.cbtitle, true);
                    s.append('rect').classed(cn.cboutline, true);
                    s.select('.cbtitle').datum(0);
                });
        });

        container.attr('transform', 'translate(' + Math.round(gs.l) +
            ',' + Math.round(gs.t) + ')');
        // TODO: this opposite transform is a hack until we make it
        // more rational which items get this offset
        var titleCont = container.select('.cbtitleunshift')
            .attr('transform', 'translate(-' +
                Math.round(gs.l) + ',-' +
                Math.round(gs.t) + ')');

        cbAxisOut._axislayer = container.select('.cbaxis');
        var titleHeight = 0;
        if(['top', 'bottom'].indexOf(opts.titleside) !== -1) {
            // draw the title so we know how much room it needs
            // when we squish the axis. This one only applies to
            // top or bottom titles, not right side.
            var x = gs.l + (opts.x + xpadFrac) * gs.w,
                fontSize = cbAxisOut.titlefont.size,
                y;

            if(opts.titleside === 'top') {
                y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h +
                    gs.t + 3 + fontSize * 0.75;
            }
            else {
                y = (1 - (yBottomFrac + ypadFrac)) * gs.h +
                    gs.t - 3 - fontSize * 0.25;
            }
            drawTitle(cbAxisOut._id + 'title', {
                attributes: {x: x, y: y, 'text-anchor': 'start'}
            });
        }

        function drawAxis() {
            if(['top', 'bottom'].indexOf(opts.titleside) !== -1) {
                // squish the axis top to make room for the title
                var titleGroup = container.select('.cbtitle'),
                    titleText = titleGroup.select('text'),
                    titleTrans =
                        [-opts.outlinewidth / 2, opts.outlinewidth / 2],
                    mathJaxNode = titleGroup
                        .select('.h' + cbAxisOut._id + 'title-math-group')
                        .node(),
                    lineSize = 15.6;
                if(titleText.node()) {
                    lineSize =
                        parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING;
                }
                if(mathJaxNode) {
                    titleHeight = Drawing.bBox(mathJaxNode).height;
                    if(titleHeight > lineSize) {
                        // not entirely sure how mathjax is doing
                        // vertical alignment, but this seems to work.
                        titleTrans[1] -= (titleHeight - lineSize) / 2;
                    }
                }
                else if(titleText.node() &&
                        !titleText.classed(cn.jsPlaceholder)) {
                    titleHeight = Drawing.bBox(titleText.node()).height;
                }
                if(titleHeight) {
                    // buffer btwn colorbar and title
                    // TODO: configurable
                    titleHeight += 5;

                    if(opts.titleside === 'top') {
                        cbAxisOut.domain[1] -= titleHeight / gs.h;
                        titleTrans[1] *= -1;
                    }
                    else {
                        cbAxisOut.domain[0] += titleHeight / gs.h;
                        var nlines = svgTextUtils.lineCount(titleText);
                        titleTrans[1] += (1 - nlines) * lineSize;
                    }

                    titleGroup.attr('transform',
                        'translate(' + titleTrans + ')');

                    cbAxisOut.setScale();
                }
            }

            container.selectAll('.cbfills,.cblines')
                .attr('transform', 'translate(0,' +
                    Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')');

            cbAxisOut._axislayer.attr('transform', 'translate(0,' +
                Math.round(-gs.t) + ')');

            var fills = container.select('.cbfills')
                .selectAll('rect.cbfill')
                    .data(filllevels);
            fills.enter().append('rect')
                .classed(cn.cbfill, true)
                .style('stroke', 'none');
            fills.exit().remove();
            fills.each(function(d, i) {
                var z = [
                    (i === 0) ? zrange[0] :
                        (filllevels[i] + filllevels[i - 1]) / 2,
                    (i === filllevels.length - 1) ? zrange[1] :
                        (filllevels[i] + filllevels[i + 1]) / 2
                ]
                .map(cbAxisOut.c2p)
                .map(Math.round);

                // offset the side adjoining the next rectangle so they
                // overlap, to prevent antialiasing gaps
                if(i !== filllevels.length - 1) {
                    z[1] += (z[1] > z[0]) ? 1 : -1;
                }


                // Tinycolor can't handle exponents and
                // at this scale, removing it makes no difference.
                var colorString = fillcolormap(d).replace('e-', ''),
                    opaqueColor = tinycolor(colorString).toHexString();

                // Colorbar cannot currently support opacities so we
                // use an opaque fill even when alpha channels present
                d3.select(this).attr({
                    x: xLeft,
                    width: Math.max(thickPx, 2),
                    y: d3.min(z),
                    height: Math.max(d3.max(z) - d3.min(z), 2),
                    fill: opaqueColor
                });
            });

            var lines = container.select('.cblines')
                .selectAll('path.cbline')
                    .data(opts.line.color && opts.line.width ?
                        linelevels : []);
            lines.enter().append('path')
                .classed(cn.cbline, true);
            lines.exit().remove();
            lines.each(function(d) {
                d3.select(this)
                    .attr('d', 'M' + xLeft + ',' +
                        (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) +
                        'h' + thickPx)
                    .call(Drawing.lineGroupStyle,
                        opts.line.width, linecolormap(d), opts.line.dash);
            });

            // force full redraw of labels and ticks
            cbAxisOut._axislayer.selectAll('g.' + cbAxisOut._id + 'tick,path')
                .remove();

            cbAxisOut._pos = xLeft + thickPx +
                (opts.outlinewidth||0) / 2 - (opts.ticks === 'outside' ? 1 : 0);
            cbAxisOut.side = 'right';

            // separate out axis and title drawing,
            // so we don't need such complicated logic in Titles.draw
            // if title is on the top or bottom, we've already drawn it
            // this title call only handles side=right
            return Lib.syncOrAsync([
                function() {
                    return Axes.doTicks(gd, cbAxisOut, true);
                },
                function() {
                    if(['top', 'bottom'].indexOf(opts.titleside) === -1) {
                        var fontSize = cbAxisOut.titlefont.size,
                            y = cbAxisOut._offset + cbAxisOut._length / 2,
                            x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ?
                                10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) :
                                -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0)));

                        // the 'h' + is a hack to get around the fact that
                        // convertToTspans rotates any 'y...' class by 90 degrees.
                        // TODO: find a better way to control this.
                        drawTitle('h' + cbAxisOut._id + 'title', {
                            avoid: {
                                selection: d3.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'),
                                side: opts.titleside,
                                offsetLeft: gs.l,
                                offsetTop: 0,
                                maxShift: fullLayout.width
                            },
                            attributes: {x: x, y: y, 'text-anchor': 'middle'},
                            transform: {rotate: '-90', offset: 0}
                        });
                    }
                }]);
        }

        function drawTitle(titleClass, titleOpts) {
            var trace = getTrace(),
                propName;
            if(Registry.traceIs(trace, 'markerColorscale')) {
                propName = 'marker.colorbar.title';
            }
            else propName = 'colorbar.title';

            var dfltTitleOpts = {
                propContainer: cbAxisOut,
                propName: propName,
                traceIndex: trace.index,
                placeholder: fullLayout._dfltTitle.colorbar,
                containerGroup: container.select('.cbtitle')
            };

            // this class-to-rotate thing with convertToTspans is
            // getting hackier and hackier... delete groups with the
            // wrong class (in case earlier the colorbar was drawn on
            // a different side, I think?)
            var otherClass = titleClass.charAt(0) === 'h' ?
                titleClass.substr(1) : ('h' + titleClass);
            container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group')
                .remove();

            Titles.draw(gd, titleClass,
                extendFlat(dfltTitleOpts, titleOpts || {}));
        }

        function positionCB() {
            // wait for the axis & title to finish rendering before
            // continuing positioning
            // TODO: why are we redrawing multiple times now with this?
            // I guess autoMargin doesn't like being post-promise?
            var innerWidth = thickPx + opts.outlinewidth / 2 +
                    Drawing.bBox(cbAxisOut._axislayer.node()).width;
            titleEl = titleCont.select('text');
            if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) {
                var mathJaxNode = titleCont
                        .select('.h' + cbAxisOut._id + 'title-math-group')
                        .node(),
                    titleWidth;
                if(mathJaxNode &&
                        ['top', 'bottom'].indexOf(opts.titleside) !== -1) {
                    titleWidth = Drawing.bBox(mathJaxNode).width;
                }
                else {
                    // note: the formula below works for all titlesides,
                    // (except for top/bottom mathjax, above)
                    // but the weird gs.l is because the titleunshift
                    // transform gets removed by Drawing.bBox
                    titleWidth =
                        Drawing.bBox(titleCont.node()).right -
                        xLeft - gs.l;
                }
                innerWidth = Math.max(innerWidth, titleWidth);
            }

            var outerwidth = 2 * opts.xpad + innerWidth +
                    opts.borderwidth + opts.outlinewidth / 2,
                outerheight = yBottomPx - yTopPx;

            container.select('.cbbg').attr({
                x: xLeft - opts.xpad -
                    (opts.borderwidth + opts.outlinewidth) / 2,
                y: yTopPx - yExtraPx,
                width: Math.max(outerwidth, 2),
                height: Math.max(outerheight + 2 * yExtraPx, 2)
            })
            .call(Color.fill, opts.bgcolor)
            .call(Color.stroke, opts.bordercolor)
            .style({'stroke-width': opts.borderwidth});

            container.selectAll('.cboutline').attr({
                x: xLeft,
                y: yTopPx + opts.ypad +
                    (opts.titleside === 'top' ? titleHeight : 0),
                width: Math.max(thickPx, 2),
                height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2)
            })
            .call(Color.stroke, opts.outlinecolor)
            .style({
                fill: 'None',
                'stroke-width': opts.outlinewidth
            });

            // fix positioning for xanchor!='left'
            var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) *
                outerwidth;
            container.attr('transform',
                'translate(' + (gs.l - xoffset) + ',' + gs.t + ')');

            // auto margin adjustment
            Plots.autoMargin(gd, id, {
                x: opts.x,
                y: opts.y,
                l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0),
                r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0),
                t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0),
                b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0)
            });
        }

        var cbDone = Lib.syncOrAsync([
            Plots.previousPromises,
            drawAxis,
            Plots.previousPromises,
            positionCB
        ], gd);

        if(cbDone && cbDone.then) (gd._promises || []).push(cbDone);

        // dragging...
        if(gd._context.edits.colorbarPosition) {
            var t0,
                xf,
                yf;

            dragElement.init({
                element: container.node(),
                gd: gd,
                prepFn: function() {
                    t0 = container.attr('transform');
                    setCursor(container);
                },
                moveFn: function(dx, dy) {
                    container.attr('transform',
                        t0 + ' ' + 'translate(' + dx + ',' + dy + ')');

                    xf = dragElement.align(xLeftFrac + (dx / gs.w), thickFrac,
                        0, 1, opts.xanchor);
                    yf = dragElement.align(yBottomFrac - (dy / gs.h), lenFrac,
                        0, 1, opts.yanchor);

                    var csr = dragElement.getCursor(xf, yf,
                        opts.xanchor, opts.yanchor);
                    setCursor(container, csr);
                },
                doneFn: function() {
                    setCursor(container);

                    if(xf !== undefined && yf !== undefined) {
                        Registry.call('restyle',
                            gd,
                            {'colorbar.x': xf, 'colorbar.y': yf},
                            getTrace().index
                        );
                    }
                }
            });
        }
        return cbDone;
    }

    function getTrace() {
        var idNum = id.substr(2),
            i,
            trace;
        for(i = 0; i < gd._fullData.length; i++) {
            trace = gd._fullData[i];
            if(trace.uid === idNum) return trace;
        }
    }

    // setter/getters for every item defined in opts
    Object.keys(opts).forEach(function(name) {
        component[name] = function(v) {
            // getter
            if(!arguments.length) return opts[name];

            // setter - for multi-part properties,
            // set only the parts that are provided
            opts[name] = Lib.isPlainObject(opts[name]) ?
                 Lib.extendFlat(opts[name], v) :
                 v;

            return component;
        };
    });

    // or use .options to set multiple options at once via a dictionary
    component.options = function(o) {
        Object.keys(o).forEach(function(name) {
            // in case something random comes through
            // that's not an option, ignore it
            if(typeof component[name] === 'function') {
                component[name](o[name]);
            }
        });
        return component;
    };

    component._opts = opts;

    return component;
};

},{"../../constants/alignment":143,"../../lib":164,"../../lib/extend":157,"../../lib/setcursor":183,"../../lib/svg_text_utils":185,"../../plots/cartesian/axes":206,"../../plots/cartesian/axis_defaults":208,"../../plots/cartesian/layout_attributes":218,"../../plots/cartesian/position_defaults":221,"../../plots/plots":245,"../../registry":254,"../color":43,"../dragelement":65,"../drawing":68,"../titles":136,"./attributes":44,"./constants":45,"d3":6,"tinycolor2":25}],48:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');


module.exports = function hasColorbar(container) {
    return Lib.isPlainObject(container.colorbar);
};

},{"../../lib":164}],49:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    zauto: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        impliedEdits: {zmin: undefined, zmax: undefined},
        
    },
    zmin: {
        valType: 'number',
        
        dflt: null,
        editType: 'plot',
        impliedEdits: {zauto: false},
        
    },
    zmax: {
        valType: 'number',
        
        dflt: null,
        editType: 'plot',
        impliedEdits: {zauto: false},
        
    },
    colorscale: {
        valType: 'colorscale',
        
        editType: 'calc',
        impliedEdits: {autocolorscale: false},
        
    },
    autocolorscale: {
        valType: 'boolean',
        
        dflt: true,  // gets overrode in 'heatmap' & 'surface' for backwards comp.
        editType: 'calc',
        impliedEdits: {colorscale: undefined},
        
    },
    reversescale: {
        valType: 'boolean',
        
        dflt: false,
        editType: 'calc',
        
    },
    showscale: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calc',
        
    }
};

},{}],50:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');

var scales = require('./scales');
var flipScale = require('./flip_scale');


module.exports = function calc(trace, vals, containerStr, cLetter) {
    var container = trace;
    var inputContainer = trace._input;
    var fullInputContainer = trace._fullInput;

    // set by traces with groupby transforms
    var updateStyle = trace.updateStyle;

    function doUpdate(attr, inputVal, fullVal) {
        if(fullVal === undefined) fullVal = inputVal;

        if(updateStyle) {
            updateStyle(trace._input, containerStr ? (containerStr + '.' + attr) : attr, inputVal);
        }
        else {
            inputContainer[attr] = inputVal;
        }

        container[attr] = fullVal;
        if(fullInputContainer && (trace !== trace._fullInput)) {
            if(updateStyle) {
                updateStyle(trace._fullInput, containerStr ? (containerStr + '.' + attr) : attr, fullVal);
            }
            else {
                fullInputContainer[attr] = fullVal;
            }
        }
    }

    if(containerStr) {
        container = Lib.nestedProperty(container, containerStr).get();
        inputContainer = Lib.nestedProperty(inputContainer, containerStr).get();
        fullInputContainer = Lib.nestedProperty(fullInputContainer, containerStr).get() || {};
    }

    var autoAttr = cLetter + 'auto';
    var minAttr = cLetter + 'min';
    var maxAttr = cLetter + 'max';
    var auto = container[autoAttr];
    var min = container[minAttr];
    var max = container[maxAttr];
    var scl = container.colorscale;

    if(auto !== false || min === undefined) {
        min = Lib.aggNums(Math.min, null, vals);
    }

    if(auto !== false || max === undefined) {
        max = Lib.aggNums(Math.max, null, vals);
    }

    if(min === max) {
        min -= 0.5;
        max += 0.5;
    }

    doUpdate(minAttr, min);
    doUpdate(maxAttr, max);

    /*
     * If auto was explicitly false but min or max was missing,
     * we filled in the missing piece here but later the trace does
     * not look auto.
     * Otherwise make sure the trace still looks auto as far as later
     * changes are concerned.
     */
    doUpdate(autoAttr, (auto !== false || (min === undefined && max === undefined)));

    if(container.autocolorscale) {
        if(min * max < 0) scl = scales.RdBu;
        else if(min >= 0) scl = scales.Reds;
        else scl = scales.Blues;

        // reversescale is handled at the containerOut level
        doUpdate('colorscale', scl, container.reversescale ? flipScale(scl) : scl);

        // We pushed a colorscale back to input, which will change the default autocolorscale next time
        // to avoid spurious redraws from Plotly.react, update resulting autocolorscale now
        // This is a conscious decision so that changing the data later does not unexpectedly
        // give you a new colorscale
        if(!inputContainer.autocolorscale) {
            doUpdate('autocolorscale', false);
        }
    }
};

},{"../../lib":164,"./flip_scale":55,"./scales":62}],51:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorScaleAttributes = require('./attributes');
var extendFlat = require('../../lib/extend').extendFlat;
var palettes = require('./scales.js');

/*
 * Make all the attributes for a regular colorscale:
 *  color, colorscale, cauto, cmin, cmax, autocolorscale, reversescale
 *
 * @param {string} context:
 *   the container this is in (*marker*, *marker.line* etc)
 * @param {optional string} editTypeOverride:
 *   most of these attributes already require a recalc, but the ones that do not
 *   have editType *style* or *plot* unless you override (presumably with *calc*)
 * @param {optional bool} autoColorDflt:
 *   normally autocolorscale.dflt is `true`, but pass `false` to override
 *
 * @return {object} the finished attributes object
 */
module.exports = function makeColorScaleAttributes(context, editTypeOverride, autoColorDflt) {
    var contextHead = context ? (context + '.') : '';

    return {
        color: {
            valType: 'color',
            arrayOk: true,
            
            editType: editTypeOverride || 'style',
            
        },
        colorscale: extendFlat({}, colorScaleAttributes.colorscale, {
            
        }),
        cauto: extendFlat({}, colorScaleAttributes.zauto, {
            impliedEdits: {cmin: undefined, cmax: undefined},
            
        }),
        cmax: extendFlat({}, colorScaleAttributes.zmax, {
            editType: editTypeOverride || colorScaleAttributes.zmax.editType,
            impliedEdits: {cauto: false},
            
        }),
        cmin: extendFlat({}, colorScaleAttributes.zmin, {
            editType: editTypeOverride || colorScaleAttributes.zmin.editType,
            impliedEdits: {cauto: false},
            
        }),
        autocolorscale: extendFlat({}, colorScaleAttributes.autocolorscale, {
            
            dflt: autoColorDflt === false ? autoColorDflt : colorScaleAttributes.autocolorscale.dflt
        }),
        reversescale: extendFlat({}, colorScaleAttributes.reversescale, {
            
        })
    };
};

},{"../../lib/extend":157,"./attributes":49,"./scales.js":62}],52:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scales = require('./scales');


module.exports = scales.RdBu;

},{"./scales":62}],53:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');

var hasColorbar = require('../colorbar/has_colorbar');
var colorbarDefaults = require('../colorbar/defaults');
var isValidScale = require('./is_valid_scale');
var flipScale = require('./flip_scale');


module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) {
    var prefix = opts.prefix,
        cLetter = opts.cLetter,
        containerStr = prefix.slice(0, prefix.length - 1),
        containerIn = prefix ?
            Lib.nestedProperty(traceIn, containerStr).get() || {} :
            traceIn,
        containerOut = prefix ?
            Lib.nestedProperty(traceOut, containerStr).get() || {} :
            traceOut,
        minIn = containerIn[cLetter + 'min'],
        maxIn = containerIn[cLetter + 'max'],
        sclIn = containerIn.colorscale;

    var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && (minIn < maxIn);
    coerce(prefix + cLetter + 'auto', !validMinMax);
    coerce(prefix + cLetter + 'min');
    coerce(prefix + cLetter + 'max');

    // handles both the trace case (autocolorscale is false by default) and
    // the marker and marker.line case (autocolorscale is true by default)
    var autoColorscaleDftl;
    if(sclIn !== undefined) autoColorscaleDftl = !isValidScale(sclIn);
    coerce(prefix + 'autocolorscale', autoColorscaleDftl);
    var sclOut = coerce(prefix + 'colorscale');

    // reversescale is handled at the containerOut level
    var reverseScale = coerce(prefix + 'reversescale');
    if(reverseScale) containerOut.colorscale = flipScale(sclOut);

    // ... until Scatter.colorbar can handle marker line colorbars
    if(prefix === 'marker.line.') return;

    // handle both the trace case where the dflt is listed in attributes and
    // the marker case where the dflt is determined by hasColorbar
    var showScaleDftl;
    if(prefix) showScaleDftl = hasColorbar(containerIn);
    var showScale = coerce(prefix + 'showscale', showScaleDftl);

    if(showScale) colorbarDefaults(containerIn, containerOut, layout);
};

},{"../../lib":164,"../colorbar/defaults":46,"../colorbar/has_colorbar":48,"./flip_scale":55,"./is_valid_scale":59,"fast-isnumeric":9}],54:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/**
 * Extract colorscale into numeric domain and color range.
 *
 * @param {array} scl colorscale array of arrays
 * @param {number} cmin minimum color value (used to clamp scale)
 * @param {number} cmax maximum color value (used to clamp scale)
 */
module.exports = function extractScale(scl, cmin, cmax) {
    var N = scl.length,
        domain = new Array(N),
        range = new Array(N);

    for(var i = 0; i < N; i++) {
        var si = scl[i];

        domain[i] = cmin + si[0] * (cmax - cmin);
        range[i] = si[1];
    }

    return {
        domain: domain,
        range: range
    };
};

},{}],55:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = function flipScale(scl) {
    var N = scl.length,
        sclNew = new Array(N),
        si;

    for(var i = N - 1, j = 0; i >= 0; i--, j++) {
        si = scl[i];
        sclNew[j] = [1 - si[0], si[1]];
    }

    return sclNew;
};

},{}],56:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scales = require('./scales');
var defaultScale = require('./default_scale');
var isValidScaleArray = require('./is_valid_scale_array');


module.exports = function getScale(scl, dflt) {
    if(!dflt) dflt = defaultScale;
    if(!scl) return dflt;

    function parseScale() {
        try {
            scl = scales[scl] || JSON.parse(scl);
        }
        catch(e) {
            scl = dflt;
        }
    }

    if(typeof scl === 'string') {
        parseScale();
        // occasionally scl is double-JSON encoded...
        if(typeof scl === 'string') parseScale();
    }

    if(!isValidScaleArray(scl)) return dflt;
    return scl;
};

},{"./default_scale":52,"./is_valid_scale_array":60,"./scales":62}],57:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');
var Lib = require('../../lib');
var isValidScale = require('./is_valid_scale');

module.exports = function hasColorscale(trace, containerStr) {
    var container = containerStr ?
        Lib.nestedProperty(trace, containerStr).get() || {} :
        trace;
    var color = container.color;

    var isArrayWithOneNumber = false;
    if(Lib.isArrayOrTypedArray(color)) {
        for(var i = 0; i < color.length; i++) {
            if(isNumeric(color[i])) {
                isArrayWithOneNumber = true;
                break;
            }
        }
    }

    return (
        Lib.isPlainObject(container) && (
            isArrayWithOneNumber ||
            container.showscale === true ||
            (isNumeric(container.cmin) && isNumeric(container.cmax)) ||
            isValidScale(container.colorscale) ||
            Lib.isPlainObject(container.colorbar)
        )
    );
};

},{"../../lib":164,"./is_valid_scale":59,"fast-isnumeric":9}],58:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.scales = require('./scales');

exports.defaultScale = require('./default_scale');

exports.attributes = require('./attributes');

exports.handleDefaults = require('./defaults');

exports.calc = require('./calc');

exports.hasColorscale = require('./has_colorscale');

exports.isValidScale = require('./is_valid_scale');

exports.getScale = require('./get_scale');

exports.flipScale = require('./flip_scale');

exports.extractScale = require('./extract_scale');

exports.makeColorScaleFunc = require('./make_color_scale_func');

},{"./attributes":49,"./calc":50,"./default_scale":52,"./defaults":53,"./extract_scale":54,"./flip_scale":55,"./get_scale":56,"./has_colorscale":57,"./is_valid_scale":59,"./make_color_scale_func":61,"./scales":62}],59:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var scales = require('./scales');
var isValidScaleArray = require('./is_valid_scale_array');


module.exports = function isValidScale(scl) {
    if(scales[scl] !== undefined) return true;
    else return isValidScaleArray(scl);
};

},{"./is_valid_scale_array":60,"./scales":62}],60:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var tinycolor = require('tinycolor2');


module.exports = function isValidScaleArray(scl) {
    var highestVal = 0;

    if(!Array.isArray(scl) || scl.length < 2) return false;

    if(!scl[0] || !scl[scl.length - 1]) return false;

    if(+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;

    for(var i = 0; i < scl.length; i++) {
        var si = scl[i];

        if(si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
            return false;
        }

        highestVal = +si[0];
    }

    return true;
};

},{"tinycolor2":25}],61:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var tinycolor = require('tinycolor2');
var isNumeric = require('fast-isnumeric');

var Color = require('../color');

/**
 * General colorscale function generator.
 *
 * @param {object} specs output of Colorscale.extractScale or precomputed domain, range.
 *  - domain {array}
 *  - range {array}
 *
 * @param {object} opts
 *  - noNumericCheck {boolean} if true, scale func bypasses numeric checks
 *  - returnArray {boolean} if true, scale func return 4-item array instead of color strings
 *
 * @return {function}
 */
module.exports = function makeColorScaleFunc(specs, opts) {
    opts = opts || {};

    var domain = specs.domain,
        range = specs.range,
        N = range.length,
        _range = new Array(N);

    for(var i = 0; i < N; i++) {
        var rgba = tinycolor(range[i]).toRgb();
        _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a];
    }

    var _sclFunc = d3.scale.linear()
        .domain(domain)
        .range(_range)
        .clamp(true);

    var noNumericCheck = opts.noNumericCheck,
        returnArray = opts.returnArray,
        sclFunc;

    if(noNumericCheck && returnArray) {
        sclFunc = _sclFunc;
    }
    else if(noNumericCheck) {
        sclFunc = function(v) {
            return colorArray2rbga(_sclFunc(v));
        };
    }
    else if(returnArray) {
        sclFunc = function(v) {
            if(isNumeric(v)) return _sclFunc(v);
            else if(tinycolor(v).isValid()) return v;
            else return Color.defaultLine;
        };
    }
    else {
        sclFunc = function(v) {
            if(isNumeric(v)) return colorArray2rbga(_sclFunc(v));
            else if(tinycolor(v).isValid()) return v;
            else return Color.defaultLine;
        };
    }

    // colorbar draw looks into the d3 scale closure for domain and range

    sclFunc.domain = _sclFunc.domain;

    sclFunc.range = function() { return range; };

    return sclFunc;
};

function colorArray2rbga(colorArray) {
    var colorObj = {
        r: colorArray[0],
        g: colorArray[1],
        b: colorArray[2],
        a: colorArray[3]
    };

    return tinycolor(colorObj).toRgbString();
}

},{"../color":43,"d3":6,"fast-isnumeric":9,"tinycolor2":25}],62:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    'Greys': [
        [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
    ],

    'YlGnBu': [
        [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
        [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
        [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
        [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
        [1, 'rgb(255,255,217)']
    ],

    'Greens': [
        [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
        [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
        [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
        [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
        [1, 'rgb(247,252,245)']
    ],

    'YlOrRd': [
        [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
        [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
        [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
        [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
        [1, 'rgb(255,255,204)']
    ],

    'Bluered': [
        [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
    ],

    // modified RdBu based on
    // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
    'RdBu': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
        [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
        [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-negative numeric values
    'Reds': [
        [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
        [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
    ],

    // Scale for non-positive numeric values
    'Blues': [
        [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
        [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
        [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
    ],

    'Picnic': [
        [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
        [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
        [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
        [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
        [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
        [1, 'rgb(255,0,0)']
    ],

    'Rainbow': [
        [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
        [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
        [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
        [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
        [1, 'rgb(255,0,0)']
    ],

    'Portland': [
        [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
        [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
        [1, 'rgb(217,30,30)']
    ],

    'Jet': [
        [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
        [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
        [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
    ],

    'Hot': [
        [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
        [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
    ],

    'Blackbody': [
        [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
        [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
        [1, 'rgb(160,200,255)']
    ],

    'Earth': [
        [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
        [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
        [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
    ],

    'Electric': [
        [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
        [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
        [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
    ],

    'Viridis': [
        [0, '#440154'], [0.06274509803921569, '#48186a'],
        [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
        [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
        [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
        [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
        [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
        [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
        [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
        [1, '#fde725']
    ],

    'Cividis': [
        [0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'],
        [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'],
        [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'],
        [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'],
        [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'],
        [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'],
        [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'],
        [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'],
        [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']
    ]
};

},{}],63:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// for automatic alignment on dragging, <1/3 means left align,
// >2/3 means right, and between is center. Pick the right fraction
// based on where you are, and return the fraction corresponding to
// that position on the object
module.exports = function align(v, dv, v0, v1, anchor) {
    var vmin = (v - v0) / (v1 - v0),
        vmax = vmin + dv / (v1 - v0),
        vc = (vmin + vmax) / 2;

    // explicitly specified anchor
    if(anchor === 'left' || anchor === 'bottom') return vmin;
    if(anchor === 'center' || anchor === 'middle') return vc;
    if(anchor === 'right' || anchor === 'top') return vmax;

    // automatic based on position
    if(vmin < (2 / 3) - vc) return vmin;
    if(vmax > (4 / 3) - vc) return vmax;
    return vc;
};

},{}],64:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');


// set cursors pointing toward the closest corner/side,
// to indicate alignment
// x and y are 0-1, fractions of the plot area
var cursorset = [
    ['sw-resize', 's-resize', 'se-resize'],
    ['w-resize', 'move', 'e-resize'],
    ['nw-resize', 'n-resize', 'ne-resize']
];

module.exports = function getCursor(x, y, xanchor, yanchor) {
    if(xanchor === 'left') x = 0;
    else if(xanchor === 'center') x = 1;
    else if(xanchor === 'right') x = 2;
    else x = Lib.constrain(Math.floor(x * 3), 0, 2);

    if(yanchor === 'bottom') y = 0;
    else if(yanchor === 'middle') y = 1;
    else if(yanchor === 'top') y = 2;
    else y = Lib.constrain(Math.floor(y * 3), 0, 2);

    return cursorset[y][x];
};

},{"../../lib":164}],65:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mouseOffset = require('mouse-event-offset');
var hasHover = require('has-hover');
var supportsPassive = require('has-passive-events');

var Registry = require('../../registry');
var Lib = require('../../lib');

var constants = require('../../plots/cartesian/constants');
var interactConstants = require('../../constants/interactions');

var dragElement = module.exports = {};

dragElement.align = require('./align');
dragElement.getCursor = require('./cursor');

var unhover = require('./unhover');
dragElement.unhover = unhover.wrapped;
dragElement.unhoverRaw = unhover.raw;


/**
 * Abstracts click & drag interactions
 *
 * During the interaction, a "coverSlip" element - a transparent
 * div covering the whole page - is created, which has two key effects:
 * - Lets you drag beyond the boundaries of the plot itself without
 *   dropping (but if you drag all the way out of the browser window the
 *   interaction will end)
 * - Freezes the cursor: whatever mouse cursor the drag element had when the
 *   interaction started gets copied to the coverSlip for use until mouseup
 *
 * If the user executes a drag bigger than MINDRAG, callbacks will fire as:
 *      prepFn, moveFn (1 or more times), doneFn
 * If the user does not drag enough, prepFn and clickFn will fire.
 *
 * Note: If you cancel contextmenu, clickFn will fire even with a right click
 * (unlike native events) so you'll get a `plotly_click` event. Cancel context eg:
 *    gd.addEventListener('contextmenu', function(e) { e.preventDefault(); });
 * TODO: we should probably turn this into a `config` parameter, so we can fix it
 * such that if you *don't* cancel contextmenu, we can prevent partial drags, which
 * put you in a weird state.
 *
 * If the user clicks multiple times quickly, clickFn will fire each time
 * but numClicks will increase to help you recognize doubleclicks.
 *
 * @param {object} options with keys:
 *      element (required) the DOM element to drag
 *      prepFn (optional) function(event, startX, startY)
 *          executed on mousedown
 *          startX and startY are the clientX and clientY pixel position
 *          of the mousedown event
 *      moveFn (optional) function(dx, dy)
 *          executed on move, ONLY after we've exceeded MINDRAG
 *          (we keep executing moveFn if you move back to where you started)
 *          dx and dy are the net pixel offset of the drag,
 *          dragged is true/false, has the mouse moved enough to
 *          constitute a drag
 *      doneFn (optional) function(e)
 *          executed on mouseup, ONLY if we exceeded MINDRAG (so you can be
 *          sure that moveFn has been called at least once)
 *          numClicks is how many clicks we've registered within
 *          a doubleclick time
 *          e is the original mouseup event
 *      clickFn (optional) function(numClicks, e)
 *          executed on mouseup if we have NOT exceeded MINDRAG (ie moveFn
 *          has not been called at all)
 *          numClicks is how many clicks we've registered within
 *          a doubleclick time
 *          e is the original mousedown event
 *      clampFn (optional, function(dx, dy) return [dx2, dy2])
 *          Provide custom clamping function for small displacements.
 *          By default, clamping is done using `minDrag` to x and y displacements
 *          independently.
 */
dragElement.init = function init(options) {
    var gd = options.gd;
    var numClicks = 1;
    var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;
    var element = options.element;

    var startX,
        startY,
        newMouseDownTime,
        cursor,
        dragCover,
        initialEvent,
        initialTarget,
        rightClick;

    if(!gd._mouseDownTime) gd._mouseDownTime = 0;

    element.style.pointerEvents = 'all';

    element.onmousedown = onStart;

    if(!supportsPassive) {
        element.ontouchstart = onStart;
    }
    else {
        if(element._ontouchstart) {
            element.removeEventListener('touchstart', element._ontouchstart);
        }
        element._ontouchstart = onStart;
        element.addEventListener('touchstart', onStart, {passive: false});
    }

    function _clampFn(dx, dy, minDrag) {
        if(Math.abs(dx) < minDrag) dx = 0;
        if(Math.abs(dy) < minDrag) dy = 0;
        return [dx, dy];
    }

    var clampFn = options.clampFn || _clampFn;

    function onStart(e) {
        e.preventDefault();

        // make dragging and dragged into properties of gd
        // so that others can look at and modify them
        gd._dragged = false;
        gd._dragging = true;
        var offset = pointerOffset(e);
        startX = offset[0];
        startY = offset[1];
        initialTarget = e.target;
        initialEvent = e;
        rightClick = e.buttons === 2 || e.ctrlKey;

        newMouseDownTime = (new Date()).getTime();
        if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) {
            // in a click train
            numClicks += 1;
        }
        else {
            // new click train
            numClicks = 1;
            gd._mouseDownTime = newMouseDownTime;
        }

        if(options.prepFn) options.prepFn(e, startX, startY);

        if(hasHover && !rightClick) {
            dragCover = coverSlip();
            dragCover.style.cursor = window.getComputedStyle(element).cursor;
        }
        else if(!hasHover) {
            // document acts as a dragcover for mobile, bc we can't create dragcover dynamically
            dragCover = document;
            cursor = window.getComputedStyle(document.documentElement).cursor;
            document.documentElement.style.cursor = window.getComputedStyle(element).cursor;
        }

        document.addEventListener('mousemove', onMove);
        document.addEventListener('mouseup', onDone);
        document.addEventListener('touchmove', onMove);
        document.addEventListener('touchend', onDone);

        return;
    }

    function onMove(e) {
        e.preventDefault();

        var offset = pointerOffset(e);
        var minDrag = options.minDrag || constants.MINDRAG;
        var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag);
        var dx = dxdy[0];
        var dy = dxdy[1];

        if(dx || dy) {
            gd._dragged = true;
            dragElement.unhover(gd);
        }

        if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy);

        return;
    }

    function onDone(e) {
        document.removeEventListener('mousemove', onMove);
        document.removeEventListener('mouseup', onDone);
        document.removeEventListener('touchmove', onMove);
        document.removeEventListener('touchend', onDone);

        e.preventDefault();

        if(hasHover) {
            Lib.removeElement(dragCover);
        }
        else if(cursor) {
            dragCover.documentElement.style.cursor = cursor;
            cursor = null;
        }

        if(!gd._dragging) {
            gd._dragged = false;
            return;
        }
        gd._dragging = false;

        // don't count as a dblClick unless the mouseUp is also within
        // the dblclick delay
        if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) {
            numClicks = Math.max(numClicks - 1, 1);
        }

        if(gd._dragged) {
            if(options.doneFn) options.doneFn(e);
        }
        else {
            if(options.clickFn) options.clickFn(numClicks, initialEvent);

            // If we haven't dragged, this should be a click. But because of the
            // coverSlip changing the element, the natural system might not generate one,
            // so we need to make our own. But right clicks don't normally generate
            // click events, only contextmenu events, which happen on mousedown.
            if(!rightClick) {
                var e2;

                try {
                    e2 = new MouseEvent('click', e);
                }
                catch(err) {
                    var offset = pointerOffset(e);
                    e2 = document.createEvent('MouseEvents');
                    e2.initMouseEvent('click',
                        e.bubbles, e.cancelable,
                        e.view, e.detail,
                        e.screenX, e.screenY,
                        offset[0], offset[1],
                        e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
                        e.button, e.relatedTarget);
                }

                initialTarget.dispatchEvent(e2);
            }
        }

        finishDrag(gd);

        gd._dragged = false;

        return;
    }
};

function coverSlip() {
    var cover = document.createElement('div');

    cover.className = 'dragcover';
    var cStyle = cover.style;
    cStyle.position = 'fixed';
    cStyle.left = 0;
    cStyle.right = 0;
    cStyle.top = 0;
    cStyle.bottom = 0;
    cStyle.zIndex = 999999999;
    cStyle.background = 'none';

    document.body.appendChild(cover);

    return cover;
}

dragElement.coverSlip = coverSlip;

function finishDrag(gd) {
    gd._dragging = false;
    if(gd._replotPending) Registry.call('plot', gd);
}

function pointerOffset(e) {
    return mouseOffset(
        e.changedTouches ? e.changedTouches[0] : e,
        document.body
    );
}

},{"../../constants/interactions":144,"../../lib":164,"../../plots/cartesian/constants":211,"../../registry":254,"./align":63,"./cursor":64,"./unhover":66,"has-hover":11,"has-passive-events":12,"mouse-event-offset":15}],66:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var Events = require('../../lib/events');
var throttle = require('../../lib/throttle');
var getGraphDiv = require('../../lib/get_graph_div');

var hoverConstants = require('../fx/constants');

var unhover = module.exports = {};


unhover.wrapped = function(gd, evt, subplot) {
    gd = getGraphDiv(gd);

    // Important, clear any queued hovers
    if(gd._fullLayout) {
        throttle.clear(gd._fullLayout._uid + hoverConstants.HOVERID);
    }

    unhover.raw(gd, evt, subplot);
};


// remove hover effects on mouse out, and emit unhover event
unhover.raw = function unhoverRaw(gd, evt) {
    var fullLayout = gd._fullLayout;
    var oldhoverdata = gd._hoverdata;

    if(!evt) evt = {};
    if(evt.target &&
       Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
        return;
    }

    fullLayout._hoverlayer.selectAll('g').remove();
    fullLayout._hoverlayer.selectAll('line').remove();
    fullLayout._hoverlayer.selectAll('circle').remove();
    gd._hoverdata = undefined;

    if(evt.target && oldhoverdata) {
        gd.emit('plotly_unhover', {
            event: evt,
            points: oldhoverdata
        });
    }
};

},{"../../lib/events":156,"../../lib/get_graph_div":162,"../../lib/throttle":186,"../fx/constants":80}],67:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.dash = {
    valType: 'string',
    // string type usually doesn't take values... this one should really be
    // a special type or at least a special coercion function, from the GUI
    // you only get these values but elsewhere the user can supply a list of
    // dash lengths in px, and it will be honored
    values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'],
    dflt: 'solid',
    
    editType: 'style',
    
};

},{}],68:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');
var tinycolor = require('tinycolor2');

var Registry = require('../../registry');
var Color = require('../color');
var Colorscale = require('../colorscale');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');

var xmlnsNamespaces = require('../../constants/xmlns_namespaces');
var alignment = require('../../constants/alignment');
var LINE_SPACING = alignment.LINE_SPACING;
var DESELECTDIM = require('../../constants/interactions').DESELECTDIM;

var subTypes = require('../../traces/scatter/subtypes');
var makeBubbleSizeFn = require('../../traces/scatter/make_bubble_size_func');

var drawing = module.exports = {};

// -----------------------------------------------------
// styling functions for plot elements
// -----------------------------------------------------

drawing.font = function(s, family, size, color) {
    // also allow the form font(s, {family, size, color})
    if(Lib.isPlainObject(family)) {
        color = family.color;
        size = family.size;
        family = family.family;
    }
    if(family) s.style('font-family', family);
    if(size + 1) s.style('font-size', size + 'px');
    if(color) s.call(Color.fill, color);
};

/*
 * Positioning helpers
 * Note: do not use `setPosition` with <text> nodes modified by
 * `svgTextUtils.convertToTspans`. Use `svgTextUtils.positionText`
 * instead, so that <tspan.line> elements get updated to match.
 */
drawing.setPosition = function(s, x, y) { s.attr('x', x).attr('y', y); };
drawing.setSize = function(s, w, h) { s.attr('width', w).attr('height', h); };
drawing.setRect = function(s, x, y, w, h) {
    s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
};

/** Translate node
 *
 * @param {object} d : calcdata point item
 * @param {sel} sel : d3 selction of node to translate
 * @param {object} xa : corresponding full xaxis object
 * @param {object} ya : corresponding full yaxis object
 *
 * @return {boolean} :
 *  true if selection got translated
 *  false if selection could not get translated
 */
drawing.translatePoint = function(d, sel, xa, ya) {
    var x = xa.c2p(d.x);
    var y = ya.c2p(d.y);

    if(isNumeric(x) && isNumeric(y) && sel.node()) {
        // for multiline text this works better
        if(sel.node().nodeName === 'text') {
            sel.attr('x', x).attr('y', y);
        } else {
            sel.attr('transform', 'translate(' + x + ',' + y + ')');
        }
    } else {
        return false;
    }

    return true;
};

drawing.translatePoints = function(s, xa, ya) {
    s.each(function(d) {
        var sel = d3.select(this);
        drawing.translatePoint(d, sel, xa, ya);
    });
};

drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) {
    sel.attr(
        'display',
        (xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar)) ? null : 'none'
    );
};

drawing.hideOutsideRangePoints = function(traceGroups, subplot, selector) {
    if(!subplot._hasClipOnAxisFalse) return;

    selector = selector || '.point,.textpoint';

    var xa = subplot.xaxis;
    var ya = subplot.yaxis;

    traceGroups.each(function(d) {
        var trace = d[0].trace;
        var xcalendar = trace.xcalendar;
        var ycalendar = trace.ycalendar;

        traceGroups.selectAll(selector).each(function(d) {
            drawing.hideOutsideRangePoint(d, d3.select(this), xa, ya, xcalendar, ycalendar);
        });
    });
};

drawing.crispRound = function(gd, lineWidth, dflt) {
    // for lines that disable antialiasing we want to
    // make sure the width is an integer, and at least 1 if it's nonzero

    if(!lineWidth || !isNumeric(lineWidth)) return dflt || 0;

    // but not for static plots - these don't get antialiased anyway.
    if(gd._context.staticPlot) return lineWidth;

    if(lineWidth < 1) return 1;
    return Math.round(lineWidth);
};

drawing.singleLineStyle = function(d, s, lw, lc, ld) {
    s.style('fill', 'none');
    var line = (((d || [])[0] || {}).trace || {}).line || {},
        lw1 = lw || line.width||0,
        dash = ld || line.dash || '';

    Color.stroke(s, lc || line.color);
    drawing.dashLine(s, dash, lw1);
};

drawing.lineGroupStyle = function(s, lw, lc, ld) {
    s.style('fill', 'none')
    .each(function(d) {
        var line = (((d || [])[0] || {}).trace || {}).line || {},
            lw1 = lw || line.width||0,
            dash = ld || line.dash || '';

        d3.select(this)
            .call(Color.stroke, lc || line.color)
            .call(drawing.dashLine, dash, lw1);
    });
};

drawing.dashLine = function(s, dash, lineWidth) {
    lineWidth = +lineWidth || 0;

    dash = drawing.dashStyle(dash, lineWidth);

    s.style({
        'stroke-dasharray': dash,
        'stroke-width': lineWidth + 'px'
    });
};

drawing.dashStyle = function(dash, lineWidth) {
    lineWidth = +lineWidth || 1;
    var dlw = Math.max(lineWidth, 3);

    if(dash === 'solid') dash = '';
    else if(dash === 'dot') dash = dlw + 'px,' + dlw + 'px';
    else if(dash === 'dash') dash = (3 * dlw) + 'px,' + (3 * dlw) + 'px';
    else if(dash === 'longdash') dash = (5 * dlw) + 'px,' + (5 * dlw) + 'px';
    else if(dash === 'dashdot') {
        dash = (3 * dlw) + 'px,' + dlw + 'px,' + dlw + 'px,' + dlw + 'px';
    }
    else if(dash === 'longdashdot') {
        dash = (5 * dlw) + 'px,' + (2 * dlw) + 'px,' + dlw + 'px,' + (2 * dlw) + 'px';
    }
    // otherwise user wrote the dasharray themselves - leave it be

    return dash;
};

// Same as fillGroupStyle, except in this case the selection may be a transition
drawing.singleFillStyle = function(sel) {
    var node = d3.select(sel.node());
    var data = node.data();
    var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor;
    if(fillcolor) {
        sel.call(Color.fill, fillcolor);
    }
};

drawing.fillGroupStyle = function(s) {
    s.style('stroke-width', 0)
    .each(function(d) {
        var shape = d3.select(this);
        try {
            shape.call(Color.fill, d[0].trace.fillcolor);
        }
        catch(e) {
            Lib.error(e, s);
            shape.remove();
        }
    });
};

var SYMBOLDEFS = require('./symbol_defs');

drawing.symbolNames = [];
drawing.symbolFuncs = [];
drawing.symbolNeedLines = {};
drawing.symbolNoDot = {};
drawing.symbolNoFill = {};
drawing.symbolList = [];

Object.keys(SYMBOLDEFS).forEach(function(k) {
    var symDef = SYMBOLDEFS[k];
    drawing.symbolList = drawing.symbolList.concat(
        [symDef.n, k, symDef.n + 100, k + '-open']);
    drawing.symbolNames[symDef.n] = k;
    drawing.symbolFuncs[symDef.n] = symDef.f;
    if(symDef.needLine) {
        drawing.symbolNeedLines[symDef.n] = true;
    }
    if(symDef.noDot) {
        drawing.symbolNoDot[symDef.n] = true;
    }
    else {
        drawing.symbolList = drawing.symbolList.concat(
            [symDef.n + 200, k + '-dot', symDef.n + 300, k + '-open-dot']);
    }
    if(symDef.noFill) {
        drawing.symbolNoFill[symDef.n] = true;
    }
});
var MAXSYMBOL = drawing.symbolNames.length,
    // add a dot in the middle of the symbol
    DOTPATH = 'M0,0.5L0.5,0L0,-0.5L-0.5,0Z';

drawing.symbolNumber = function(v) {
    if(typeof v === 'string') {
        var vbase = 0;
        if(v.indexOf('-open') > 0) {
            vbase = 100;
            v = v.replace('-open', '');
        }
        if(v.indexOf('-dot') > 0) {
            vbase += 200;
            v = v.replace('-dot', '');
        }
        v = drawing.symbolNames.indexOf(v);
        if(v >= 0) { v += vbase; }
    }
    if((v % 100 >= MAXSYMBOL) || v >= 400) { return 0; }
    return Math.floor(Math.max(v, 0));
};

function makePointPath(symbolNumber, r) {
    var base = symbolNumber % 100;
    return drawing.symbolFuncs[base](r) + (symbolNumber >= 200 ? DOTPATH : '');
}

var HORZGRADIENT = {x1: 1, x2: 0, y1: 0, y2: 0};
var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0};

drawing.gradient = function(sel, gd, gradientID, type, color1, color2) {
    var gradient = gd._fullLayout._defs.select('.gradients')
        .selectAll('#' + gradientID)
        .data([type + color1 + color2], Lib.identity);

    gradient.exit().remove();

    gradient.enter()
        .append(type === 'radial' ? 'radialGradient' : 'linearGradient')
        .each(function() {
            var el = d3.select(this);
            if(type === 'horizontal') el.attr(HORZGRADIENT);
            else if(type === 'vertical') el.attr(VERTGRADIENT);

            el.attr('id', gradientID);

            var tc1 = tinycolor(color1);
            var tc2 = tinycolor(color2);

            el.append('stop').attr({
                offset: '0%',
                'stop-color': Color.tinyRGB(tc2),
                'stop-opacity': tc2.getAlpha()
            });

            el.append('stop').attr({
                offset: '100%',
                'stop-color': Color.tinyRGB(tc1),
                'stop-opacity': tc1.getAlpha()
            });
        });

    sel.style({
        fill: 'url(#' + gradientID + ')',
        'fill-opacity': null
    });
};

/*
 * Make the gradients container and clear out any previous gradients.
 * We never collect all the gradients we need in one place,
 * so we can't ever remove gradients that have stopped being useful,
 * except all at once before a full redraw.
 * The upside of this is arbitrary points can share gradient defs
 */
drawing.initGradients = function(gd) {
    var gradientsGroup = Lib.ensureSingle(gd._fullLayout._defs, 'g', 'gradients');
    gradientsGroup.selectAll('linearGradient,radialGradient').remove();
};


drawing.pointStyle = function(s, trace, gd) {
    if(!s.size()) return;

    var fns = drawing.makePointStyleFns(trace);

    s.each(function(d) {
        drawing.singlePointStyle(d, d3.select(this), trace, fns, gd);
    });
};

drawing.singlePointStyle = function(d, sel, trace, fns, gd) {
    var marker = trace.marker;
    var markerLine = marker.line;

    sel.style('opacity',
        fns.selectedOpacityFn ? fns.selectedOpacityFn(d) :
            (d.mo === undefined ? marker.opacity : d.mo)
    );

    if(fns.ms2mrc) {
        var r;

        // handle multi-trace graph edit case
        if(d.ms === 'various' || marker.size === 'various') {
            r = 3;
        } else {
            r = fns.ms2mrc(d.ms);
        }

        // store the calculated size so hover can use it
        d.mrc = r;

        if(fns.selectedSizeFn) {
            r = d.mrc = fns.selectedSizeFn(d);
        }

        // turn the symbol into a sanitized number
        var x = drawing.symbolNumber(d.mx || marker.symbol) || 0;

        // save if this marker is open
        // because that impacts how to handle colors
        d.om = x % 200 >= 100;

        sel.attr('d', makePointPath(x, r));
    }

    var perPointGradient = false;
    var fillColor, lineColor, lineWidth;

    // 'so' is suspected outliers, for box plots
    if(d.so) {
        lineWidth = markerLine.outlierwidth;
        lineColor = markerLine.outliercolor;
        fillColor = marker.outliercolor;
    } else {
        lineWidth = (d.mlw + 1 || markerLine.width + 1 ||
            // TODO: we need the latter for legends... can we get rid of it?
            (d.trace ? d.trace.marker.line.width : 0) + 1) - 1;

        if('mlc' in d) lineColor = d.mlcc = fns.lineScale(d.mlc);
        // weird case: array wasn't long enough to apply to every point
        else if(Lib.isArrayOrTypedArray(markerLine.color)) lineColor = Color.defaultLine;
        else lineColor = markerLine.color;

        if(Lib.isArrayOrTypedArray(marker.color)) {
            fillColor = Color.defaultLine;
            perPointGradient = true;
        }

        if('mc' in d) {
            fillColor = d.mcc = fns.markerScale(d.mc);
        } else {
            fillColor = marker.color || 'rgba(0,0,0,0)';
        }

        if(fns.selectedColorFn) {
            fillColor = fns.selectedColorFn(d);
        }
    }

    if(d.om) {
        // open markers can't have zero linewidth, default to 1px,
        // and use fill color as stroke color
        sel.call(Color.stroke, fillColor)
            .style({
                'stroke-width': (lineWidth || 1) + 'px',
                fill: 'none'
            });
    } else {
        sel.style('stroke-width', lineWidth + 'px');

        var markerGradient = marker.gradient;

        var gradientType = d.mgt;
        if(gradientType) perPointGradient = true;
        else gradientType = markerGradient && markerGradient.type;

        if(gradientType && gradientType !== 'none') {
            var gradientColor = d.mgc;
            if(gradientColor) perPointGradient = true;
            else gradientColor = markerGradient.color;

            var gradientID = 'g' + gd._fullLayout._uid + '-' + trace.uid;
            if(perPointGradient) gradientID += '-' + d.i;

            sel.call(drawing.gradient, gd, gradientID, gradientType, fillColor, gradientColor);
        } else {
            sel.call(Color.fill, fillColor);
        }

        if(lineWidth) {
            sel.call(Color.stroke, lineColor);
        }
    }
};

drawing.makePointStyleFns = function(trace) {
    var out = {};
    var marker = trace.marker;

    // allow array marker and marker line colors to be
    // scaled by given max and min to colorscales
    out.markerScale = drawing.tryColorscale(marker, '');
    out.lineScale = drawing.tryColorscale(marker, 'line');

    if(Registry.traceIs(trace, 'symbols')) {
        out.ms2mrc = subTypes.isBubble(trace) ?
            makeBubbleSizeFn(trace) :
            function() { return (marker.size || 6) / 2; };
    }

    if(trace.selectedpoints) {
        Lib.extendFlat(out, drawing.makeSelectedPointStyleFns(trace));
    }

    return out;
};

drawing.makeSelectedPointStyleFns = function(trace) {
    var out = {};

    var selectedAttrs = trace.selected || {};
    var unselectedAttrs = trace.unselected || {};

    var marker = trace.marker || {};
    var selectedMarker = selectedAttrs.marker || {};
    var unselectedMarker = unselectedAttrs.marker || {};

    var mo = marker.opacity;
    var smo = selectedMarker.opacity;
    var usmo = unselectedMarker.opacity;
    var smoIsDefined = smo !== undefined;
    var usmoIsDefined = usmo !== undefined;

    if(Lib.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) {
        out.selectedOpacityFn = function(d) {
            var base = d.mo === undefined ? marker.opacity : d.mo;

            if(d.selected) {
                return smoIsDefined ? smo : base;
            } else {
                return usmoIsDefined ? usmo : DESELECTDIM * base;
            }
        };
    }

    var mc = marker.color;
    var smc = selectedMarker.color;
    var usmc = unselectedMarker.color;

    if(smc || usmc) {
        out.selectedColorFn = function(d) {
            var base = d.mcc || mc;

            if(d.selected) {
                return smc || base;
            } else {
                return usmc || base;
            }
        };
    }

    var ms = marker.size;
    var sms = selectedMarker.size;
    var usms = unselectedMarker.size;
    var smsIsDefined = sms !== undefined;
    var usmsIsDefined = usms !== undefined;

    if(Registry.traceIs(trace, 'symbols') && (smsIsDefined || usmsIsDefined)) {
        out.selectedSizeFn = function(d) {
            var base = d.mrc || ms / 2;

            if(d.selected) {
                return smsIsDefined ? sms / 2 : base;
            } else {
                return usmsIsDefined ? usms / 2 : base;
            }
        };
    }

    return out;
};

drawing.makeSelectedTextStyleFns = function(trace) {
    var out = {};

    var selectedAttrs = trace.selected || {};
    var unselectedAttrs = trace.unselected || {};

    var textFont = trace.textfont || {};
    var selectedTextFont = selectedAttrs.textfont || {};
    var unselectedTextFont = unselectedAttrs.textfont || {};

    var tc = textFont.color;
    var stc = selectedTextFont.color;
    var utc = unselectedTextFont.color;

    out.selectedTextColorFn = function(d) {
        var base = d.tc || tc;

        if(d.selected) {
            return stc || base;
        } else {
            if(utc) return utc;
            else return stc ? base : Color.addOpacity(base, DESELECTDIM);
        }
    };

    return out;
};

drawing.selectedPointStyle = function(s, trace) {
    if(!s.size() || !trace.selectedpoints) return;

    var fns = drawing.makeSelectedPointStyleFns(trace);
    var marker = trace.marker || {};
    var seq = [];

    if(fns.selectedOpacityFn) {
        seq.push(function(pt, d) {
            pt.style('opacity', fns.selectedOpacityFn(d));
        });
    }

    if(fns.selectedColorFn) {
        seq.push(function(pt, d) {
            Color.fill(pt, fns.selectedColorFn(d));
        });
    }

    if(fns.selectedSizeFn) {
        seq.push(function(pt, d) {
            var mx = d.mx || marker.symbol || 0;
            var mrc2 = fns.selectedSizeFn(d);

            pt.attr('d', makePointPath(drawing.symbolNumber(mx), mrc2));

            // save for Drawing.selectedTextStyle
            d.mrc2 = mrc2;
        });
    }

    if(seq.length) {
        s.each(function(d) {
            var pt = d3.select(this);
            for(var i = 0; i < seq.length; i++) {
                seq[i](pt, d);
            }
        });
    }
};

drawing.tryColorscale = function(marker, prefix) {
    var cont = prefix ? Lib.nestedProperty(marker, prefix).get() : marker,
        scl = cont.colorscale,
        colorArray = cont.color;

    if(scl && Lib.isArrayOrTypedArray(colorArray)) {
        return Colorscale.makeColorScaleFunc(
            Colorscale.extractScale(scl, cont.cmin, cont.cmax)
        );
    }
    else return Lib.identity;
};

var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1};

function textPointPosition(s, textPosition, fontSize, markerRadius) {
    var group = d3.select(s.node().parentNode);

    var v = textPosition.indexOf('top') !== -1 ?
        'top' :
        textPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
    var h = textPosition.indexOf('left') !== -1 ?
        'end' :
        textPosition.indexOf('right') !== -1 ? 'start' : 'middle';

    // if markers are shown, offset a little more than
    // the nominal marker size
    // ie 2/1.6 * nominal, bcs some markers are a bit bigger
    var r = markerRadius ? markerRadius / 0.8 + 1 : 0;

    var numLines = (svgTextUtils.lineCount(s) - 1) * LINE_SPACING + 1;
    var dx = TEXTOFFSETSIGN[h] * r;
    var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r +
            (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2;

    // fix the overall text group position
    s.attr('text-anchor', h);
    group.attr('transform', 'translate(' + dx + ',' + dy + ')');
}

function extracTextFontSize(d, trace) {
    var fontSize = d.ts || trace.textfont.size;
    return (isNumeric(fontSize) && fontSize > 0) ? fontSize : 0;
}

// draw text at points
drawing.textPointStyle = function(s, trace, gd) {
    if(!s.size()) return;

    var selectedTextColorFn;

    if(trace.selectedpoints) {
        var fns = drawing.makeSelectedTextStyleFns(trace);
        selectedTextColorFn = fns.selectedTextColorFn;
    }

    s.each(function(d) {
        var p = d3.select(this);
        var text = Lib.extractOption(d, trace, 'tx', 'text');

        if(!text) {
            p.remove();
            return;
        }

        var pos = d.tp || trace.textposition;
        var fontSize = extracTextFontSize(d, trace);
        var fontColor = selectedTextColorFn ?
            selectedTextColorFn(d) :
            (d.tc || trace.textfont.color);

        p.call(drawing.font,
                d.tf || trace.textfont.family,
                fontSize,
                fontColor)
            .text(text)
            .call(svgTextUtils.convertToTspans, gd)
            .call(textPointPosition, pos, fontSize, d.mrc);
    });
};

drawing.selectedTextStyle = function(s, trace) {
    if(!s.size() || !trace.selectedpoints) return;

    var fns = drawing.makeSelectedTextStyleFns(trace);

    s.each(function(d) {
        var tx = d3.select(this);
        var tc = fns.selectedTextColorFn(d);
        var tp = d.tp || trace.textposition;
        var fontSize = extracTextFontSize(d, trace);

        Color.fill(tx, tc);
        textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc);
    });
};

// generalized Catmull-Rom splines, per
// http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
var CatmullRomExp = 0.5;
drawing.smoothopen = function(pts, smoothness) {
    if(pts.length < 3) { return 'M' + pts.join('L');}
    var path = 'M' + pts[0],
        tangents = [], i;
    for(i = 1; i < pts.length - 1; i++) {
        tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
    }
    path += 'Q' + tangents[0][0] + ' ' + pts[1];
    for(i = 2; i < pts.length - 1; i++) {
        path += 'C' + tangents[i - 2][1] + ' ' + tangents[i - 1][0] + ' ' + pts[i];
    }
    path += 'Q' + tangents[pts.length - 3][1] + ' ' + pts[pts.length - 1];
    return path;
};

drawing.smoothclosed = function(pts, smoothness) {
    if(pts.length < 3) { return 'M' + pts.join('L') + 'Z'; }
    var path = 'M' + pts[0],
        pLast = pts.length - 1,
        tangents = [makeTangent(pts[pLast],
                        pts[0], pts[1], smoothness)],
        i;
    for(i = 1; i < pLast; i++) {
        tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
    }
    tangents.push(
        makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness)
    );

    for(i = 1; i <= pLast; i++) {
        path += 'C' + tangents[i - 1][1] + ' ' + tangents[i][0] + ' ' + pts[i];
    }
    path += 'C' + tangents[pLast][1] + ' ' + tangents[0][0] + ' ' + pts[0] + 'Z';
    return path;
};

function makeTangent(prevpt, thispt, nextpt, smoothness) {
    var d1x = prevpt[0] - thispt[0],
        d1y = prevpt[1] - thispt[1],
        d2x = nextpt[0] - thispt[0],
        d2y = nextpt[1] - thispt[1],
        d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2),
        d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2),
        numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness,
        numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness,
        denom1 = 3 * d2a * (d1a + d2a),
        denom2 = 3 * d1a * (d1a + d2a);
    return [
        [
            d3.round(thispt[0] + (denom1 && numx / denom1), 2),
            d3.round(thispt[1] + (denom1 && numy / denom1), 2)
        ], [
            d3.round(thispt[0] - (denom2 && numx / denom2), 2),
            d3.round(thispt[1] - (denom2 && numy / denom2), 2)
        ]
    ];
}

// step paths - returns a generator function for paths
// with the given step shape
var STEPPATH = {
    hv: function(p0, p1) {
        return 'H' + d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
    },
    vh: function(p0, p1) {
        return 'V' + d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
    },
    hvh: function(p0, p1) {
        return 'H' + d3.round((p0[0] + p1[0]) / 2, 2) + 'V' +
            d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
    },
    vhv: function(p0, p1) {
        return 'V' + d3.round((p0[1] + p1[1]) / 2, 2) + 'H' +
            d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
    }
};
var STEPLINEAR = function(p0, p1) {
    return 'L' + d3.round(p1[0], 2) + ',' + d3.round(p1[1], 2);
};
drawing.steps = function(shape) {
    var onestep = STEPPATH[shape] || STEPLINEAR;
    return function(pts) {
        var path = 'M' + d3.round(pts[0][0], 2) + ',' + d3.round(pts[0][1], 2);
        for(var i = 1; i < pts.length; i++) {
            path += onestep(pts[i - 1], pts[i]);
        }
        return path;
    };
};

// off-screen svg render testing element, shared by the whole page
// uses the id 'js-plotly-tester' and stores it in drawing.tester
drawing.makeTester = function() {
    var tester = Lib.ensureSingleById(d3.select('body'), 'svg', 'js-plotly-tester', function(s) {
        s.attr(xmlnsNamespaces.svgAttrs)
            .style({
                position: 'absolute',
                left: '-10000px',
                top: '-10000px',
                width: '9000px',
                height: '9000px',
                'z-index': '1'
            });
    });

    // browsers differ on how they describe the bounding rect of
    // the svg if its contents spill over... so make a 1x1px
    // reference point we can measure off of.
    var testref = Lib.ensureSingle(tester, 'path', 'js-reference-point', function(s) {
        s.attr('d', 'M0,0H1V1H0Z')
            .style({
                'stroke-width': 0,
                fill: 'black'
            });
    });

    drawing.tester = tester;
    drawing.testref = testref;
};

/*
 * use our offscreen tester to get a clientRect for an element,
 * in a reference frame where it isn't translated (or transformed) and
 * its anchor point is at (0,0)
 * always returns a copy of the bbox, so the caller can modify it safely
 *
 * @param {SVGElement} node: the element to measure. If possible this should be
 *   a <text> or MathJax <g> element that's already passed through
 *   `convertToTspans` because in that case we can cache the results, but it's
 *   possible to pass in any svg element.
 *
 * @param {boolean} inTester: is this element already in `drawing.tester`?
 *   If you are measuring a dummy element, rather than one you really intend
 *   to use on the plot, making it in `drawing.tester` in the first place
 *   allows us to test faster because it cuts out cloning and appending it.
 *
 * @param {string} hash: for internal use only, if we already know the cache key
 *   for this element beforehand.
 *
 * @return {object}: a plain object containing the width, height, left, right,
 *   top, and bottom of `node`
 */
drawing.savedBBoxes = {};
var savedBBoxesCount = 0;
var maxSavedBBoxes = 10000;

drawing.bBox = function(node, inTester, hash) {
    /*
     * Cache elements we've already measured so we don't have to
     * remeasure the same thing many times
     * We have a few bBox callers though who pass a node larger than
     * a <text> or a MathJax <g>, such as an axis group containing many labels.
     * These will not generate a hash (unless we figure out an appropriate
     * hash key for them) and thus we will not hash them.
     */
    if(!hash) hash = nodeHash(node);
    var out;
    if(hash) {
        out = drawing.savedBBoxes[hash];
        if(out) return Lib.extendFlat({}, out);
    }
    else if(node.childNodes.length === 1) {
        /*
         * If we have only one child element, which is itself hashable, make
         * a new hash from this element plus its x,y,transform
         * These bounding boxes *include* x,y,transform - mostly for use by
         * callers trying to avoid overlaps (ie titles)
         */
        var innerNode = node.childNodes[0];

        hash = nodeHash(innerNode);
        if(hash) {
            var x = +innerNode.getAttribute('x') || 0;
            var y = +innerNode.getAttribute('y') || 0;
            var transform = innerNode.getAttribute('transform');

            if(!transform) {
                // in this case, just varying x and y, don't bother caching
                // the final bBox because the alteration is quick.
                var innerBB = drawing.bBox(innerNode, false, hash);
                if(x) {
                    innerBB.left += x;
                    innerBB.right += x;
                }
                if(y) {
                    innerBB.top += y;
                    innerBB.bottom += y;
                }
                return innerBB;
            }
            /*
             * else we have a transform - rather than make a complicated
             * (and error-prone and probably slow) transform parser/calculator,
             * just continue on calculating the boundingClientRect of the group
             * and use the new composite hash to cache it.
             * That said, `innerNode.transform.baseVal` is an array of
             * `SVGTransform` objects, that *do* seem to have a nice matrix
             * multiplication interface that we could use to avoid making
             * another getBoundingClientRect call...
             */
            hash += '~' + x + '~' + y + '~' + transform;

            out = drawing.savedBBoxes[hash];
            if(out) return Lib.extendFlat({}, out);
        }
    }
    var testNode, tester;
    if(inTester) {
        testNode = node;
    }
    else {
        tester = drawing.tester.node();

        // copy the node to test into the tester
        testNode = node.cloneNode(true);
        tester.appendChild(testNode);
    }

    // standardize its position (and newline tspans if any)
    d3.select(testNode)
        .attr('transform', null)
        .call(svgTextUtils.positionText, 0, 0);

    var testRect = testNode.getBoundingClientRect();
    var refRect = drawing.testref
        .node()
        .getBoundingClientRect();

    if(!inTester) tester.removeChild(testNode);

    var bb = {
        height: testRect.height,
        width: testRect.width,
        left: testRect.left - refRect.left,
        top: testRect.top - refRect.top,
        right: testRect.right - refRect.left,
        bottom: testRect.bottom - refRect.top
    };

    // make sure we don't have too many saved boxes,
    // or a long session could overload on memory
    // by saving boxes for long-gone elements
    if(savedBBoxesCount >= maxSavedBBoxes) {
        drawing.savedBBoxes = {};
        savedBBoxesCount = 0;
    }

    // cache this bbox
    if(hash) drawing.savedBBoxes[hash] = bb;
    savedBBoxesCount++;

    return Lib.extendFlat({}, bb);
};

// capture everything about a node (at least in our usage) that
// impacts its bounding box, given that bBox clears x, y, and transform
function nodeHash(node) {
    var inputText = node.getAttribute('data-unformatted');
    if(inputText === null) return;
    return inputText +
        node.getAttribute('data-math') +
        node.getAttribute('text-anchor') +
        node.getAttribute('style');
}

/*
 * make a robust clipPath url from a local id
 * note! We'd better not be exporting from a page
 * with a <base> or the svg will not be portable!
 */
drawing.setClipUrl = function(s, localId) {
    if(!localId) {
        s.attr('clip-path', null);
        return;
    }

    if(drawing.baseUrl === undefined) {
        var base = d3.select('base');

        // Stash base url once and for all!
        // We may have to stash this elsewhere when
        // we'll try to support for child windows
        // more info -> https://github.com/plotly/plotly.js/issues/702
        if(base.size() && base.attr('href')) {
            drawing.baseUrl = window.location.href.split('#')[0];
        } else {
            drawing.baseUrl = '';
        }
    }

    s.attr('clip-path', 'url(' + drawing.baseUrl + '#' + localId + ')');
};

drawing.getTranslate = function(element) {
    // Note the separator [^\d] between x and y in this regex
    // We generally use ',' but IE will convert it to ' '
    var re = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,
        getter = element.attr ? 'attr' : 'getAttribute',
        transform = element[getter]('transform') || '';

    var translate = transform.replace(re, function(match, p1, p2) {
        return [p1, p2].join(' ');
    })
    .split(' ');

    return {
        x: +translate[0] || 0,
        y: +translate[1] || 0
    };
};

drawing.setTranslate = function(element, x, y) {

    var re = /(\btranslate\(.*?\);?)/,
        getter = element.attr ? 'attr' : 'getAttribute',
        setter = element.attr ? 'attr' : 'setAttribute',
        transform = element[getter]('transform') || '';

    x = x || 0;
    y = y || 0;

    transform = transform.replace(re, '').trim();
    transform += ' translate(' + x + ', ' + y + ')';
    transform = transform.trim();

    element[setter]('transform', transform);

    return transform;
};

drawing.getScale = function(element) {

    var re = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/,
        getter = element.attr ? 'attr' : 'getAttribute',
        transform = element[getter]('transform') || '';

    var translate = transform.replace(re, function(match, p1, p2) {
        return [p1, p2].join(' ');
    })
    .split(' ');

    return {
        x: +translate[0] || 1,
        y: +translate[1] || 1
    };
};

drawing.setScale = function(element, x, y) {

    var re = /(\bscale\(.*?\);?)/,
        getter = element.attr ? 'attr' : 'getAttribute',
        setter = element.attr ? 'attr' : 'setAttribute',
        transform = element[getter]('transform') || '';

    x = x || 1;
    y = y || 1;

    transform = transform.replace(re, '').trim();
    transform += ' scale(' + x + ', ' + y + ')';
    transform = transform.trim();

    element[setter]('transform', transform);

    return transform;
};

drawing.setPointGroupScale = function(selection, x, y) {
    var t, scale, re;

    x = x || 1;
    y = y || 1;

    if(x === 1 && y === 1) {
        scale = '';
    } else {
        // The same scale transform for every point:
        scale = ' scale(' + x + ',' + y + ')';
    }

    // A regex to strip any existing scale:
    re = /\s*sc.*/;

    selection.each(function() {
        // Get the transform:
        t = (this.getAttribute('transform') || '').replace(re, '');
        t += scale;
        t = t.trim();

        // Append the scale transform
        this.setAttribute('transform', t);
    });

    return scale;
};

var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/;

drawing.setTextPointsScale = function(selection, xScale, yScale) {
    selection.each(function() {
        var transforms;
        var el = d3.select(this);
        var text = el.select('text');

        if(!text.node()) return;

        var x = parseFloat(text.attr('x') || 0);
        var y = parseFloat(text.attr('y') || 0);

        var existingTransform = (el.attr('transform') || '').match(TEXT_POINT_LAST_TRANSLATION_RE);

        if(xScale === 1 && yScale === 1) {
            transforms = [];
        } else {
            transforms = [
                'translate(' + x + ',' + y + ')',
                'scale(' + xScale + ',' + yScale + ')',
                'translate(' + (-x) + ',' + (-y) + ')',
            ];
        }

        if(existingTransform) {
            transforms.push(existingTransform);
        }

        el.attr('transform', transforms.join(' '));
    });
};

},{"../../constants/alignment":143,"../../constants/interactions":144,"../../constants/xmlns_namespaces":147,"../../lib":164,"../../lib/svg_text_utils":185,"../../registry":254,"../../traces/scatter/make_bubble_size_func":283,"../../traces/scatter/subtypes":288,"../color":43,"../colorscale":58,"./symbol_defs":69,"d3":6,"fast-isnumeric":9,"tinycolor2":25}],69:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

/** Marker symbol definitions
 * users can specify markers either by number or name
 * add 100 (or '-open') and you get an open marker
 *  open markers have no fill and use line color as the stroke color
 * add 200 (or '-dot') and you get a dot in the middle
 * add both and you get both
 */

module.exports = {
    circle: {
        n: 0,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        }
    },
    square: {
        n: 1,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        }
    },
    diamond: {
        n: 2,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z';
        }
    },
    cross: {
        n: 3,
        f: function(r) {
            var rc = d3.round(r * 0.4, 2),
                rc2 = d3.round(r * 1.2, 2);
            return 'M' + rc2 + ',' + rc + 'H' + rc + 'V' + rc2 + 'H-' + rc +
                'V' + rc + 'H-' + rc2 + 'V-' + rc + 'H-' + rc + 'V-' + rc2 +
                'H' + rc + 'V-' + rc + 'H' + rc2 + 'Z';
        }
    },
    x: {
        n: 4,
        f: function(r) {
            var rx = d3.round(r * 0.8 / Math.sqrt(2), 2),
                ne = 'l' + rx + ',' + rx,
                se = 'l' + rx + ',-' + rx,
                sw = 'l-' + rx + ',-' + rx,
                nw = 'l-' + rx + ',' + rx;
            return 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z';
        }
    },
    'triangle-up': {
        n: 5,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2),
                r2 = d3.round(r / 2, 2),
                rs = d3.round(r, 2);
            return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z';
        }
    },
    'triangle-down': {
        n: 6,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2),
                r2 = d3.round(r / 2, 2),
                rs = d3.round(r, 2);
            return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z';
        }
    },
    'triangle-left': {
        n: 7,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2),
                r2 = d3.round(r / 2, 2),
                rs = d3.round(r, 2);
            return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z';
        }
    },
    'triangle-right': {
        n: 8,
        f: function(r) {
            var rt = d3.round(r * 2 / Math.sqrt(3), 2),
                r2 = d3.round(r / 2, 2),
                rs = d3.round(r, 2);
            return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z';
        }
    },
    'triangle-ne': {
        n: 9,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2),
                r2 = d3.round(r * 1.2, 2);
            return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z';
        }
    },
    'triangle-se': {
        n: 10,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2),
                r2 = d3.round(r * 1.2, 2);
            return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z';
        }
    },
    'triangle-sw': {
        n: 11,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2),
                r2 = d3.round(r * 1.2, 2);
            return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z';
        }
    },
    'triangle-nw': {
        n: 12,
        f: function(r) {
            var r1 = d3.round(r * 0.6, 2),
                r2 = d3.round(r * 1.2, 2);
            return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z';
        }
    },
    pentagon: {
        n: 13,
        f: function(r) {
            var x1 = d3.round(r * 0.951, 2),
                x2 = d3.round(r * 0.588, 2),
                y0 = d3.round(-r, 2),
                y1 = d3.round(r * -0.309, 2),
                y2 = d3.round(r * 0.809, 2);
            return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 +
                'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z';
        }
    },
    hexagon: {
        n: 14,
        f: function(r) {
            var y0 = d3.round(r, 2),
                y1 = d3.round(r / 2, 2),
                x = d3.round(r * Math.sqrt(3) / 2, 2);
            return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 +
                'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z';
        }
    },
    hexagon2: {
        n: 15,
        f: function(r) {
            var x0 = d3.round(r, 2),
                x1 = d3.round(r / 2, 2),
                y = d3.round(r * Math.sqrt(3) / 2, 2);
            return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 +
                ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z';
        }
    },
    octagon: {
        n: 16,
        f: function(r) {
            var a = d3.round(r * 0.924, 2),
                b = d3.round(r * 0.383, 2);
            return 'M-' + b + ',-' + a + 'H' + b + 'L' + a + ',-' + b + 'V' + b +
                'L' + b + ',' + a + 'H-' + b + 'L-' + a + ',' + b + 'V-' + b + 'Z';
        }
    },
    star: {
        n: 17,
        f: function(r) {
            var rs = r * 1.4,
                x1 = d3.round(rs * 0.225, 2),
                x2 = d3.round(rs * 0.951, 2),
                x3 = d3.round(rs * 0.363, 2),
                x4 = d3.round(rs * 0.588, 2),
                y0 = d3.round(-rs, 2),
                y1 = d3.round(rs * -0.309, 2),
                y3 = d3.round(rs * 0.118, 2),
                y4 = d3.round(rs * 0.809, 2),
                y5 = d3.round(rs * 0.382, 2);
            return 'M' + x1 + ',' + y1 + 'H' + x2 + 'L' + x3 + ',' + y3 +
                'L' + x4 + ',' + y4 + 'L0,' + y5 + 'L-' + x4 + ',' + y4 +
                'L-' + x3 + ',' + y3 + 'L-' + x2 + ',' + y1 + 'H-' + x1 +
                'L0,' + y0 + 'Z';
        }
    },
    hexagram: {
        n: 18,
        f: function(r) {
            var y = d3.round(r * 0.66, 2),
                x1 = d3.round(r * 0.38, 2),
                x2 = d3.round(r * 0.76, 2);
            return 'M-' + x2 + ',0l-' + x1 + ',-' + y + 'h' + x2 +
                'l' + x1 + ',-' + y + 'l' + x1 + ',' + y + 'h' + x2 +
                'l-' + x1 + ',' + y + 'l' + x1 + ',' + y + 'h-' + x2 +
                'l-' + x1 + ',' + y + 'l-' + x1 + ',-' + y + 'h-' + x2 + 'Z';
        }
    },
    'star-triangle-up': {
        n: 19,
        f: function(r) {
            var x = d3.round(r * Math.sqrt(3) * 0.8, 2),
                y1 = d3.round(r * 0.8, 2),
                y2 = d3.round(r * 1.6, 2),
                rc = d3.round(r * 4, 2),
                aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 +
                aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z';
        }
    },
    'star-triangle-down': {
        n: 20,
        f: function(r) {
            var x = d3.round(r * Math.sqrt(3) * 0.8, 2),
                y1 = d3.round(r * 0.8, 2),
                y2 = d3.round(r * 1.6, 2),
                rc = d3.round(r * 4, 2),
                aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 +
                aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z';
        }
    },
    'star-square': {
        n: 21,
        f: function(r) {
            var rp = d3.round(r * 1.1, 2),
                rc = d3.round(r * 2, 2),
                aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp +
                aPart + rp + ',' + rp + aPart + rp + ',-' + rp +
                aPart + '-' + rp + ',-' + rp + 'Z';
        }
    },
    'star-diamond': {
        n: 22,
        f: function(r) {
            var rp = d3.round(r * 1.4, 2),
                rc = d3.round(r * 1.9, 2),
                aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
            return 'M-' + rp + ',0' + aPart + '0,' + rp +
                aPart + rp + ',0' + aPart + '0,-' + rp +
                aPart + '-' + rp + ',0' + 'Z';
        }
    },
    'diamond-tall': {
        n: 23,
        f: function(r) {
            var x = d3.round(r * 0.7, 2),
                y = d3.round(r * 1.4, 2);
            return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
        }
    },
    'diamond-wide': {
        n: 24,
        f: function(r) {
            var x = d3.round(r * 1.4, 2),
                y = d3.round(r * 0.7, 2);
            return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
        }
    },
    hourglass: {
        n: 25,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z';
        },
        noDot: true
    },
    bowtie: {
        n: 26,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z';
        },
        noDot: true
    },
    'circle-cross': {
        n: 27,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
                'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        },
        needLine: true,
        noDot: true
    },
    'circle-x': {
        n: 28,
        f: function(r) {
            var rs = d3.round(r, 2),
                rc = d3.round(r / Math.sqrt(2), 2);
            return 'M' + rc + ',' + rc + 'L-' + rc + ',-' + rc +
                'M' + rc + ',-' + rc + 'L-' + rc + ',' + rc +
                'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
                'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
        },
        needLine: true,
        noDot: true
    },
    'square-cross': {
        n: 29,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
                'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        },
        needLine: true,
        noDot: true
    },
    'square-x': {
        n: 30,
        f: function(r) {
            var rs = d3.round(r, 2);
            return 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
                'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs +
                'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
        },
        needLine: true,
        noDot: true
    },
    'diamond-cross': {
        n: 31,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
                'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd;
        },
        needLine: true,
        noDot: true
    },
    'diamond-x': {
        n: 32,
        f: function(r) {
            var rd = d3.round(r * 1.3, 2),
                r2 = d3.round(r * 0.65, 2);
            return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
                'M-' + r2 + ',-' + r2 + 'L' + r2 + ',' + r2 +
                'M-' + r2 + ',' + r2 + 'L' + r2 + ',-' + r2;
        },
        needLine: true,
        noDot: true
    },
    'cross-thin': {
        n: 33,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'x-thin': {
        n: 34,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx +
                'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    asterisk: {
        n: 35,
        f: function(r) {
            var rc = d3.round(r * 1.2, 2);
            var rs = d3.round(r * 0.85, 2);
            return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc +
                'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
                'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    hash: {
        n: 36,
        f: function(r) {
            var r1 = d3.round(r / 2, 2),
                r2 = d3.round(r, 2);
            return 'M' + r1 + ',' + r2 + 'V-' + r2 +
                'm-' + r2 + ',0V' + r2 +
                'M' + r2 + ',' + r1 + 'H-' + r2 +
                'm0,-' + r2 + 'H' + r2;
        },
        needLine: true,
        noFill: true
    },
    'y-up': {
        n: 37,
        f: function(r) {
            var x = d3.round(r * 1.2, 2),
                y0 = d3.round(r * 1.6, 2),
                y1 = d3.round(r * 0.8, 2);
            return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-down': {
        n: 38,
        f: function(r) {
            var x = d3.round(r * 1.2, 2),
                y0 = d3.round(r * 1.6, 2),
                y1 = d3.round(r * 0.8, 2);
            return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-left': {
        n: 39,
        f: function(r) {
            var y = d3.round(r * 1.2, 2),
                x0 = d3.round(r * 1.6, 2),
                x1 = d3.round(r * 0.8, 2);
            return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'y-right': {
        n: 40,
        f: function(r) {
            var y = d3.round(r * 1.2, 2),
                x0 = d3.round(r * 1.6, 2),
                x1 = d3.round(r * 0.8, 2);
            return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0';
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ew': {
        n: 41,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M' + rc + ',0H-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ns': {
        n: 42,
        f: function(r) {
            var rc = d3.round(r * 1.4, 2);
            return 'M0,' + rc + 'V-' + rc;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-ne': {
        n: 43,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    },
    'line-nw': {
        n: 44,
        f: function(r) {
            var rx = d3.round(r, 2);
            return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx;
        },
        needLine: true,
        noDot: true,
        noFill: true
    }
};

},{"d3":6}],70:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    type: {
        valType: 'enumerated',
        values: ['percent', 'constant', 'sqrt', 'data'],
        
        editType: 'calc',
        
    },
    symmetric: {
        valType: 'boolean',
        
        editType: 'calc',
        
    },
    array: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    arrayminus: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    value: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'calc',
        
    },
    valueminus: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'calc',
        
    },
    traceref: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'style'
    },
    tracerefminus: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'style'
    },
    copy_ystyle: {
        valType: 'boolean',
        
        editType: 'plot'
    },
    copy_zstyle: {
        valType: 'boolean',
        
        editType: 'style'
    },
    color: {
        valType: 'color',
        
        editType: 'style',
        
    },
    thickness: {
        valType: 'number',
        min: 0,
        dflt: 2,
        
        editType: 'style',
        
    },
    width: {
        valType: 'number',
        min: 0,
        
        editType: 'plot',
        
    },
    editType: 'calc',

    _deprecated: {
        opacity: {
            valType: 'number',
            
            editType: 'style',
            
        }
    }
};

},{}],71:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var Registry = require('../../registry');
var Axes = require('../../plots/cartesian/axes');

var makeComputeError = require('./compute_error');


module.exports = function calc(gd) {
    var calcdata = gd.calcdata;

    for(var i = 0; i < calcdata.length; i++) {
        var calcTrace = calcdata[i],
            trace = calcTrace[0].trace;

        if(!Registry.traceIs(trace, 'errorBarsOK')) continue;

        var xa = Axes.getFromId(gd, trace.xaxis),
            ya = Axes.getFromId(gd, trace.yaxis);

        calcOneAxis(calcTrace, trace, xa, 'x');
        calcOneAxis(calcTrace, trace, ya, 'y');
    }
};

function calcOneAxis(calcTrace, trace, axis, coord) {
    var opts = trace['error_' + coord] || {},
        isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1),
        vals = [];

    if(!isVisible) return;

    var computeError = makeComputeError(opts);

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i],
            calcCoord = calcPt[coord];

        if(!isNumeric(axis.c2l(calcCoord))) continue;

        var errors = computeError(calcCoord, i);
        if(isNumeric(errors[0]) && isNumeric(errors[1])) {
            var shoe = calcPt[coord + 's'] = calcCoord - errors[0],
                hat = calcPt[coord + 'h'] = calcCoord + errors[1];
            vals.push(shoe, hat);
        }
    }

    Axes.expand(axis, vals, {padded: true});
}

},{"../../plots/cartesian/axes":206,"../../registry":254,"./compute_error":72,"fast-isnumeric":9}],72:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Error bar computing function generator
 *
 * N.B. The generated function does not clean the dataPt entries. Non-numeric
 * entries result in undefined error magnitudes.
 *
 * @param {object} opts error bar attributes
 *
 * @return {function} :
 *      @param {numeric} dataPt data point from where to compute the error magnitude
 *      @param {number} index index of dataPt in its corresponding data array
 *      @return {array}
 *        - error[0] : error magnitude in the negative direction
 *        - error[1] : " " " " positive "
 */
module.exports = function makeComputeError(opts) {
    var type = opts.type,
        symmetric = opts.symmetric;

    if(type === 'data') {
        var array = opts.array || [];

        if(symmetric) {
            return function computeError(dataPt, index) {
                var val = +(array[index]);
                return [val, val];
            };
        }
        else {
            var arrayminus = opts.arrayminus || [];
            return function computeError(dataPt, index) {
                var val = +array[index];
                var valMinus = +arrayminus[index];
                // in case one is present and the other is missing, fill in 0
                // so we still see the present one. Mostly useful during manual
                // data entry.
                if(!isNaN(val) || !isNaN(valMinus)) {
                    return [valMinus || 0, val || 0];
                }
                return [NaN, NaN];
            };
        }
    }
    else {
        var computeErrorValue = makeComputeErrorValue(type, opts.value),
            computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);

        if(symmetric || opts.valueminus === undefined) {
            return function computeError(dataPt) {
                var val = computeErrorValue(dataPt);
                return [val, val];
            };
        }
        else {
            return function computeError(dataPt) {
                return [
                    computeErrorValueMinus(dataPt),
                    computeErrorValue(dataPt)
                ];
            };
        }
    }
};

/**
 * Compute error bar magnitude (for all types except data)
 *
 * @param {string} type error bar type
 * @param {numeric} value error bar value
 *
 * @return {function} :
 *      @param {numeric} dataPt
 */
function makeComputeErrorValue(type, value) {
    if(type === 'percent') {
        return function(dataPt) {
            return Math.abs(dataPt * value / 100);
        };
    }
    if(type === 'constant') {
        return function() {
            return Math.abs(value);
        };
    }
    if(type === 'sqrt') {
        return function(dataPt) {
            return Math.sqrt(Math.abs(dataPt));
        };
    }
}

},{}],73:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');

var Registry = require('../../registry');
var Lib = require('../../lib');

var attributes = require('./attributes');


module.exports = function(traceIn, traceOut, defaultColor, opts) {
    var objName = 'error_' + opts.axis,
        containerOut = traceOut[objName] = {},
        containerIn = traceIn[objName] || {};

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    var hasErrorBars = (
        containerIn.array !== undefined ||
        containerIn.value !== undefined ||
        containerIn.type === 'sqrt'
    );

    var visible = coerce('visible', hasErrorBars);

    if(visible === false) return;

    var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'),
        symmetric = true;

    if(type !== 'sqrt') {
        symmetric = coerce('symmetric',
            !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn));
    }

    if(type === 'data') {
        coerce('array');
        coerce('traceref');
        if(!symmetric) {
            coerce('arrayminus');
            coerce('tracerefminus');
        }
    }
    else if(type === 'percent' || type === 'constant') {
        coerce('value');
        if(!symmetric) coerce('valueminus');
    }

    var copyAttr = 'copy_' + opts.inherit + 'style';
    if(opts.inherit) {
        var inheritObj = traceOut['error_' + opts.inherit];
        if((inheritObj || {}).visible) {
            coerce(copyAttr, !(containerIn.color ||
                               isNumeric(containerIn.thickness) ||
                               isNumeric(containerIn.width)));
        }
    }
    if(!opts.inherit || !containerOut[copyAttr]) {
        coerce('color', defaultColor);
        coerce('thickness');
        coerce('width', Registry.traceIs(traceOut, 'gl3d') ? 0 : 4);
    }
};

},{"../../lib":164,"../../registry":254,"./attributes":70,"fast-isnumeric":9}],74:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var overrideAll = require('../../plot_api/edit_types').overrideAll;

var attributes = require('./attributes');
var calc = require('./calc');

var xyAttrs = {
    error_x: Lib.extendFlat({}, attributes),
    error_y: Lib.extendFlat({}, attributes)
};
delete xyAttrs.error_x.copy_zstyle;
delete xyAttrs.error_y.copy_zstyle;
delete xyAttrs.error_y.copy_ystyle;

var xyzAttrs = {
    error_x: Lib.extendFlat({}, attributes),
    error_y: Lib.extendFlat({}, attributes),
    error_z: Lib.extendFlat({}, attributes)
};
delete xyzAttrs.error_x.copy_ystyle;
delete xyzAttrs.error_y.copy_ystyle;
delete xyzAttrs.error_z.copy_ystyle;
delete xyzAttrs.error_z.copy_zstyle;

module.exports = {
    moduleType: 'component',
    name: 'errorbars',

    schema: {
        traces: {
            scatter: xyAttrs,
            bar: xyAttrs,
            histogram: xyAttrs,
            scatter3d: overrideAll(xyzAttrs, 'calc', 'nested'),
            scattergl: overrideAll(xyAttrs, 'calc', 'nested')
        }
    },

    supplyDefaults: require('./defaults'),

    calc: calc,
    calcFromTrace: calcFromTrace,

    plot: require('./plot'),
    style: require('./style'),
    hoverInfo: hoverInfo
};

function calcFromTrace(trace, layout) {
    var x = trace.x || [],
        y = trace.y || [],
        len = x.length || y.length;

    var calcdataMock = new Array(len);

    for(var i = 0; i < len; i++) {
        calcdataMock[i] = {
            x: x[i],
            y: y[i]
        };
    }

    calcdataMock[0].trace = trace;

    calc({
        calcdata: [calcdataMock],
        _fullLayout: layout
    });

    return calcdataMock;
}

function hoverInfo(calcPoint, trace, hoverPoint) {
    if((trace.error_y || {}).visible) {
        hoverPoint.yerr = calcPoint.yh - calcPoint.y;
        if(!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
    }
    if((trace.error_x || {}).visible) {
        hoverPoint.xerr = calcPoint.xh - calcPoint.x;
        if(!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
    }
}

},{"../../lib":164,"../../plot_api/edit_types":191,"./attributes":70,"./calc":71,"./defaults":73,"./plot":75,"./style":76}],75:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var Drawing = require('../drawing');
var subTypes = require('../../traces/scatter/subtypes');

module.exports = function plot(traces, plotinfo, transitionOpts) {
    var isNew;

    var xa = plotinfo.xaxis;
    var ya = plotinfo.yaxis;

    var hasAnimation = transitionOpts && transitionOpts.duration > 0;

    traces.each(function(d) {
        var trace = d[0].trace,
            // || {} is in case the trace (specifically scatterternary)
            // doesn't support error bars at all, but does go through
            // the scatter.plot mechanics, which calls ErrorBars.plot
            // internally
            xObj = trace.error_x || {},
            yObj = trace.error_y || {};

        var keyFunc;

        if(trace.ids) {
            keyFunc = function(d) {return d.id;};
        }

        var sparse = (
            subTypes.hasMarkers(trace) &&
            trace.marker.maxdisplayed > 0
        );

        if(!yObj.visible && !xObj.visible) d = [];

        var errorbars = d3.select(this).selectAll('g.errorbar')
            .data(d, keyFunc);

        errorbars.exit().remove();

        if(!d.length) return;

        if(!xObj.visible) errorbars.selectAll('path.xerror').remove();
        if(!yObj.visible) errorbars.selectAll('path.yerror').remove();

        errorbars.style('opacity', 1);

        var enter = errorbars.enter().append('g')
            .classed('errorbar', true);

        if(hasAnimation) {
            enter.style('opacity', 0).transition()
                .duration(transitionOpts.duration)
                .style('opacity', 1);
        }

        Drawing.setClipUrl(errorbars, plotinfo.layerClipId);

        errorbars.each(function(d) {
            var errorbar = d3.select(this);
            var coords = errorCoords(d, xa, ya);

            if(sparse && !d.vis) return;

            var path;

            var yerror = errorbar.select('path.yerror');
            if(yObj.visible && isNumeric(coords.x) &&
                    isNumeric(coords.yh) &&
                    isNumeric(coords.ys)) {
                var yw = yObj.width;

                path = 'M' + (coords.x - yw) + ',' +
                    coords.yh + 'h' + (2 * yw) + // hat
                    'm-' + yw + ',0V' + coords.ys; // bar


                if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe

                isNew = !yerror.size();

                if(isNew) {
                    yerror = errorbar.append('path')
                        .style('vector-effect', 'non-scaling-stroke')
                        .classed('yerror', true);
                } else if(hasAnimation) {
                    yerror = yerror
                        .transition()
                            .duration(transitionOpts.duration)
                            .ease(transitionOpts.easing);
                }

                yerror.attr('d', path);
            }
            else yerror.remove();

            var xerror = errorbar.select('path.xerror');
            if(xObj.visible && isNumeric(coords.y) &&
                    isNumeric(coords.xh) &&
                    isNumeric(coords.xs)) {
                var xw = (xObj.copy_ystyle ? yObj : xObj).width;

                path = 'M' + coords.xh + ',' +
                    (coords.y - xw) + 'v' + (2 * xw) + // hat
                    'm0,-' + xw + 'H' + coords.xs; // bar

                if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe

                isNew = !xerror.size();

                if(isNew) {
                    xerror = errorbar.append('path')
                        .style('vector-effect', 'non-scaling-stroke')
                        .classed('xerror', true);
                } else if(hasAnimation) {
                    xerror = xerror
                        .transition()
                            .duration(transitionOpts.duration)
                            .ease(transitionOpts.easing);
                }

                xerror.attr('d', path);
            }
            else xerror.remove();
        });
    });
};

// compute the coordinates of the error-bar objects
function errorCoords(d, xa, ya) {
    var out = {
        x: xa.c2p(d.x),
        y: ya.c2p(d.y)
    };

    // calculate the error bar size and hat and shoe locations
    if(d.yh !== undefined) {
        out.yh = ya.c2p(d.yh);
        out.ys = ya.c2p(d.ys);

        // if the shoes go off-scale (ie log scale, error bars past zero)
        // clip the bar and hide the shoes
        if(!isNumeric(out.ys)) {
            out.noYS = true;
            out.ys = ya.c2p(d.ys, true);
        }
    }

    if(d.xh !== undefined) {
        out.xh = xa.c2p(d.xh);
        out.xs = xa.c2p(d.xs);

        if(!isNumeric(out.xs)) {
            out.noXS = true;
            out.xs = xa.c2p(d.xs, true);
        }
    }

    return out;
}

},{"../../traces/scatter/subtypes":288,"../drawing":68,"d3":6,"fast-isnumeric":9}],76:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Color = require('../color');


module.exports = function style(traces) {
    traces.each(function(d) {
        var trace = d[0].trace,
            yObj = trace.error_y || {},
            xObj = trace.error_x || {};

        var s = d3.select(this);

        s.selectAll('path.yerror')
            .style('stroke-width', yObj.thickness + 'px')
            .call(Color.stroke, yObj.color);

        if(xObj.copy_ystyle) xObj = yObj;

        s.selectAll('path.xerror')
            .style('stroke-width', xObj.thickness + 'px')
            .call(Color.stroke, xObj.color);
    });
};

},{"../color":43,"d3":6}],77:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('../../plots/font_attributes');

module.exports = {
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            arrayOk: true,
            editType: 'none',
            
        },
        bordercolor: {
            valType: 'color',
            
            arrayOk: true,
            editType: 'none',
            
        },
        font: fontAttrs({
            arrayOk: true,
            editType: 'none',
            
        }),
        namelength: {
            valType: 'integer',
            min: -1,
            arrayOk: true,
            
            editType: 'none',
            
        },
        editType: 'calc'
    }
};

},{"../../plots/font_attributes":232}],78:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Registry = require('../../registry');

module.exports = function calc(gd) {
    var calcdata = gd.calcdata;
    var fullLayout = gd._fullLayout;

    function makeCoerceHoverInfo(trace) {
        return function(val) {
            return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
        };
    }

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var trace = cd[0].trace;

        // don't include hover calc fields for pie traces
        // as calcdata items might be sorted by value and
        // won't match the data array order.
        if(Registry.traceIs(trace, 'pie')) continue;

        var fillFn = Registry.traceIs(trace, '2dMap') ? paste : Lib.fillArray;

        fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace));

        if(!trace.hoverlabel) continue;

        fillFn(trace.hoverlabel.bgcolor, cd, 'hbg');
        fillFn(trace.hoverlabel.bordercolor, cd, 'hbc');
        fillFn(trace.hoverlabel.font.size, cd, 'hts');
        fillFn(trace.hoverlabel.font.color, cd, 'htc');
        fillFn(trace.hoverlabel.font.family, cd, 'htf');
        fillFn(trace.hoverlabel.namelength, cd, 'hnl');
    }
};

function paste(traceAttr, cd, cdAttr, fn) {
    fn = fn || Lib.identity;

    if(Array.isArray(traceAttr)) {
        cd[0][cdAttr] = fn(traceAttr);
    }
}

},{"../../lib":164,"../../registry":254}],79:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');
var hover = require('./hover').hover;

module.exports = function click(gd, evt, subplot) {
    var annotationsDone = Registry.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata);

    // fallback to fail-safe in case the plot type's hover method doesn't pass the subplot.
    // Ternary, for example, didn't, but it was caught because tested.
    if(subplot !== undefined) {
        // The true flag at the end causes it to re-run the hover computation to figure out *which*
        // point is being clicked. Without this, clicking is somewhat unreliable.
        hover(gd, evt, subplot, true);
    }

    function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); }

    if(gd._hoverdata && evt && evt.target) {
        if(annotationsDone && annotationsDone.then) {
            annotationsDone.then(emitClick);
        }
        else emitClick();

        // why do we get a double event without this???
        if(evt.stopImmediatePropagation) evt.stopImmediatePropagation();
    }
};

},{"../../registry":254,"./hover":83}],80:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    // hover labels for multiple horizontal bars get tilted by this angle
    YANGLE: 60,

    // size and display constants for hover text

    // pixel size of hover arrows
    HOVERARROWSIZE: 6,
    // pixels padding around text
    HOVERTEXTPAD: 3,
    // hover font
    HOVERFONTSIZE: 13,
    HOVERFONT: 'Arial, sans-serif',

    // minimum time (msec) between hover calls
    HOVERMINTIME: 50,

    // ID suffix (with fullLayout._uid) for hover events in the throttle cache
    HOVERID: '-hover'
};

},{}],81:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var attributes = require('./attributes');
var handleHoverLabelDefaults = require('./hoverlabel_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    handleHoverLabelDefaults(traceIn, traceOut, coerce, layout.hoverlabel);
};

},{"../../lib":164,"./attributes":77,"./hoverlabel_defaults":84}],82:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');

// look for either subplot or xaxis and yaxis attributes
// does not handle splom case
exports.getSubplot = function getSubplot(trace) {
    return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo;
};

// is trace in given list of subplots?
// does handle splom case
exports.isTraceInSubplots = function isTraceInSubplot(trace, subplots) {
    if(trace.type === 'splom') {
        var xaxes = trace.xaxes || [];
        var yaxes = trace.yaxes || [];
        for(var i = 0; i < xaxes.length; i++) {
            for(var j = 0; j < yaxes.length; j++) {
                if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) {
                    return true;
                }
            }
        }
        return false;
    }

    return subplots.indexOf(exports.getSubplot(trace)) !== -1;
};

// convenience functions for mapping all relevant axes
exports.flat = function flat(subplots, v) {
    var out = new Array(subplots.length);
    for(var i = 0; i < subplots.length; i++) {
        out[i] = v;
    }
    return out;
};

exports.p2c = function p2c(axArray, v) {
    var out = new Array(axArray.length);
    for(var i = 0; i < axArray.length; i++) {
        out[i] = axArray[i].p2c(v);
    }
    return out;
};

exports.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) {
    if(mode === 'closest') return dxy || exports.quadrature(dx, dy);
    return mode === 'x' ? dx : dy;
};

exports.getClosest = function getClosest(cd, distfn, pointData) {
    // do we already have a point number? (array mode only)
    if(pointData.index !== false) {
        if(pointData.index >= 0 && pointData.index < cd.length) {
            pointData.distance = 0;
        }
        else pointData.index = false;
    }
    else {
        // apply the distance function to each data point
        // this is the longest loop... if this bogs down, we may need
        // to create pre-sorted data (by x or y), not sure how to
        // do this for 'closest'
        for(var i = 0; i < cd.length; i++) {
            var newDistance = distfn(cd[i]);
            if(newDistance <= pointData.distance) {
                pointData.index = i;
                pointData.distance = newDistance;
            }
        }
    }
    return pointData;
};

/*
 * pseudo-distance function for hover effects on areas: inside the region
 * distance is finite (`passVal`), outside it's Infinity.
 *
 * @param {number} v0: signed difference between the current position and the left edge
 * @param {number} v1: signed difference between the current position and the right edge
 * @param {number} passVal: the value to return on success
 */
exports.inbox = function inbox(v0, v1, passVal) {
    return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity;
};

exports.quadrature = function quadrature(dx, dy) {
    return function(di) {
        var x = dx(di),
            y = dy(di);
        return Math.sqrt(x * x + y * y);
    };
};

/** Fill event data point object for hover and selection.
 *  Invokes _module.eventData if present.
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * If the hovered/selected pt corresponds to an multiple input points
 * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices'
 * are include in the event data.
 *
 * @param {object} pt
 * @param {object} trace
 * @param {object} cd
 * @return {object}
 */
exports.makeEventData = function makeEventData(pt, trace, cd) {
    // hover uses 'index', select uses 'pointNumber'
    var pointNumber = 'index' in pt ? pt.index : pt.pointNumber;

    var out = {
        data: trace._input,
        fullData: trace,
        curveNumber: trace.index,
        pointNumber: pointNumber
    };

    if(trace._indexToPoints) {
        var pointIndices = trace._indexToPoints[pointNumber];

        if(pointIndices.length === 1) {
            out.pointIndex = pointIndices[0];
        } else {
            out.pointIndices = pointIndices;
        }
    } else {
        out.pointIndex = pointNumber;
    }

    if(trace._module.eventData) {
        out = trace._module.eventData(out, pt, trace, cd, pointNumber);
    } else {
        if('xVal' in pt) out.x = pt.xVal;
        else if('x' in pt) out.x = pt.x;

        if('yVal' in pt) out.y = pt.yVal;
        else if('y' in pt) out.y = pt.y;

        if(pt.xa) out.xaxis = pt.xa;
        if(pt.ya) out.yaxis = pt.ya;
        if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal;
    }

    exports.appendArrayPointValue(out, trace, pointNumber);

    return out;
};

/** Appends values inside array attributes corresponding to given point number
 *
 * @param {object} pointData : point data object (gets mutated here)
 * @param {object} trace : full trace object
 * @param {number|Array(number)} pointNumber : point number. May be a length-2 array
 *     [row, col] to dig into 2D arrays
 */
exports.appendArrayPointValue = function(pointData, trace, pointNumber) {
    var arrayAttrs = trace._arrayAttrs;

    if(!arrayAttrs) {
        return;
    }

    for(var i = 0; i < arrayAttrs.length; i++) {
        var astr = arrayAttrs[i];
        var key = getPointKey(astr);

        if(pointData[key] === undefined) {
            var val = Lib.nestedProperty(trace, astr).get();
            var pointVal = getPointData(val, pointNumber);

            if(pointVal !== undefined) pointData[key] = pointVal;
        }
    }
};

/**
 * Appends values inside array attributes corresponding to given point number array
 * For use when pointData references a plot entity that arose (or potentially arose)
 * from multiple points in the input data
 *
 * @param {object} pointData : point data object (gets mutated here)
 * @param {object} trace : full trace object
 * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers.
 *     Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays
 */
exports.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) {
    var arrayAttrs = trace._arrayAttrs;

    if(!arrayAttrs) {
        return;
    }

    for(var i = 0; i < arrayAttrs.length; i++) {
        var astr = arrayAttrs[i];
        var key = getPointKey(astr);

        if(pointData[key] === undefined) {
            var val = Lib.nestedProperty(trace, astr).get();
            var keyVal = new Array(pointNumbers.length);

            for(var j = 0; j < pointNumbers.length; j++) {
                keyVal[j] = getPointData(val, pointNumbers[j]);
            }
            pointData[key] = keyVal;
        }
    }
};

var pointKeyMap = {
    ids: 'id',
    locations: 'location',
    labels: 'label',
    values: 'value',
    'marker.colors': 'color'
};

function getPointKey(astr) {
    return pointKeyMap[astr] || astr;
}

function getPointData(val, pointNumber) {
    if(Array.isArray(pointNumber)) {
        if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) {
            return val[pointNumber[0]][pointNumber[1]];
        }
    } else {
        return val[pointNumber];
    }
}

},{"../../lib":164}],83:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');
var tinycolor = require('tinycolor2');

var Lib = require('../../lib');
var Events = require('../../lib/events');
var svgTextUtils = require('../../lib/svg_text_utils');
var overrideCursor = require('../../lib/override_cursor');
var Drawing = require('../drawing');
var Color = require('../color');
var dragElement = require('../dragelement');
var Axes = require('../../plots/cartesian/axes');
var Registry = require('../../registry');

var helpers = require('./helpers');
var constants = require('./constants');

// hover labels for multiple horizontal bars get tilted by some angle,
// then need to be offset differently if they overlap
var YANGLE = constants.YANGLE;
var YA_RADIANS = Math.PI * YANGLE / 180;

// expansion of projected height
var YFACTOR = 1 / Math.sin(YA_RADIANS);

// to make the appropriate post-rotation x offset,
// you need both x and y offsets
var YSHIFTX = Math.cos(YA_RADIANS);
var YSHIFTY = Math.sin(YA_RADIANS);

// size and display constants for hover text
var HOVERARROWSIZE = constants.HOVERARROWSIZE;
var HOVERTEXTPAD = constants.HOVERTEXTPAD;

// fx.hover: highlight data on hover
// evt can be a mousemove event, or an object with data about what points
//   to hover on
//      {xpx,ypx[,hovermode]} - pixel locations from top left
//          (with optional overriding hovermode)
//      {xval,yval[,hovermode]} - data values
//      [{curveNumber,(pointNumber|xval and/or yval)}] -
//              array of specific points to highlight
//          pointNumber is a single integer if gd.data[curveNumber] is 1D,
//              or a two-element array if it's 2D
//          xval and yval are data values,
//              1D data may specify either or both,
//              2D data must specify both
// subplot is an id string (default "xy")
// makes use of gl.hovermode, which can be:
//      x (find the points with the closest x values, ie a column),
//      closest (find the single closest point)
//    internally there are two more that occasionally get used:
//      y (pick out a row - only used for multiple horizontal bar charts)
//      array (used when the user specifies an explicit
//          array of points to hover on)
//
// We wrap the hovers in a timer, to limit their frequency.
// The actual rendering is done by private function _hover.
exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
    gd = Lib.getGraphDiv(gd);

    Lib.throttle(
        gd._fullLayout._uid + constants.HOVERID,
        constants.HOVERMINTIME,
        function() { _hover(gd, evt, subplot, noHoverEvent); }
    );
};

/*
 * Draw a single hover item in a pre-existing svg container somewhere
 * hoverItem should have keys:
 *    - x and y (or x0, x1, y0, and y1):
 *      the pixel position to mark, relative to opts.container
 *    - xLabel, yLabel, zLabel, text, and name:
 *      info to go in the label
 *    - color:
 *      the background color for the label.
 *    - idealAlign (optional):
 *      'left' or 'right' for which side of the x/y box to try to put this on first
 *    - borderColor (optional):
 *      color for the border, defaults to strongest contrast with color
 *    - fontFamily (optional):
 *      string, the font for this label, defaults to constants.HOVERFONT
 *    - fontSize (optional):
 *      the label font size, defaults to constants.HOVERFONTSIZE
 *    - fontColor (optional):
 *      defaults to borderColor
 * opts should have keys:
 *    - bgColor:
 *      the background color this is against, used if the trace is
 *      non-opaque, and for the name, which goes outside the box
 *    - container:
 *      a <svg> or <g> element to add the hover label to
 *    - outerContainer:
 *      normally a parent of `container`, sets the bounding box to use to
 *      constrain the hover label and determine whether to show it on the left or right
 */
exports.loneHover = function loneHover(hoverItem, opts) {
    var pointData = {
        color: hoverItem.color || Color.defaultLine,
        x0: hoverItem.x0 || hoverItem.x || 0,
        x1: hoverItem.x1 || hoverItem.x || 0,
        y0: hoverItem.y0 || hoverItem.y || 0,
        y1: hoverItem.y1 || hoverItem.y || 0,
        xLabel: hoverItem.xLabel,
        yLabel: hoverItem.yLabel,
        zLabel: hoverItem.zLabel,
        text: hoverItem.text,
        name: hoverItem.name,
        idealAlign: hoverItem.idealAlign,

        // optional extra bits of styling
        borderColor: hoverItem.borderColor,
        fontFamily: hoverItem.fontFamily,
        fontSize: hoverItem.fontSize,
        fontColor: hoverItem.fontColor,

        // filler to make createHoverText happy
        trace: {
            index: 0,
            hoverinfo: ''
        },
        xa: {_offset: 0},
        ya: {_offset: 0},
        index: 0
    };

    var container3 = d3.select(opts.container),
        outerContainer3 = opts.outerContainer ?
            d3.select(opts.outerContainer) : container3;

    var fullOpts = {
        hovermode: 'closest',
        rotateLabels: false,
        bgColor: opts.bgColor || Color.background,
        container: container3,
        outerContainer: outerContainer3
    };

    var hoverLabel = createHoverText([pointData], fullOpts, opts.gd);
    alignHoverText(hoverLabel, fullOpts.rotateLabels);

    return hoverLabel.node();
};

// The actual implementation is here:
function _hover(gd, evt, subplot, noHoverEvent) {
    if(!subplot) subplot = 'xy';

    // if the user passed in an array of subplots,
    // use those instead of finding overlayed plots
    var subplots = Array.isArray(subplot) ? subplot : [subplot];

    var fullLayout = gd._fullLayout;
    var plots = fullLayout._plots || [];
    var plotinfo = plots[subplot];
    var hasCartesian = fullLayout._has('cartesian');

    // list of all overlaid subplots to look at
    if(plotinfo) {
        var overlayedSubplots = plotinfo.overlays.map(function(pi) {
            return pi.id;
        });

        subplots = subplots.concat(overlayedSubplots);
    }

    var len = subplots.length;
    var xaArray = new Array(len);
    var yaArray = new Array(len);
    var supportsCompare = false;

    for(var i = 0; i < len; i++) {
        var spId = subplots[i];

        // 'cartesian' case
        var plotObj = plots[spId];
        if(plotObj) {
            supportsCompare = true;

            // TODO make sure that fullLayout_plots axis refs
            // get updated properly so that we don't have
            // to use Axes.getFromId in general.

            xaArray[i] = Axes.getFromId(gd, plotObj.xaxis._id);
            yaArray[i] = Axes.getFromId(gd, plotObj.yaxis._id);
            continue;
        }

        // other subplot types
        var _subplot = fullLayout[spId]._subplot;
        xaArray[i] = _subplot.xaxis;
        yaArray[i] = _subplot.yaxis;
    }

    var hovermode = evt.hovermode || fullLayout.hovermode;

    if(hovermode && !supportsCompare) hovermode = 'closest';

    if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata ||
            gd.querySelector('.zoombox') || gd._dragging) {
        return dragElement.unhoverRaw(gd, evt);
    }

    var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance;
    var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance;

    // hoverData: the set of candidate points we've found to highlight
    var hoverData = [],

        // searchData: the data to search in. Mostly this is just a copy of
        // gd.calcdata, filtered to the subplot and overlays we're on
        // but if a point array is supplied it will be a mapping
        // of indicated curves
        searchData = [],

        // [x|y]valArray: the axis values of the hover event
        // mapped onto each of the currently selected overlaid subplots
        xvalArray,
        yvalArray,

        // used in loops
        itemnum,
        curvenum,
        cd,
        trace,
        subplotId,
        subploti,
        mode,
        xval,
        yval,
        pointData,
        closedataPreviousLength,

        // spikePoints: the set of candidate points we've found to draw spikes to
        spikePoints = {
            hLinePoint: null,
            vLinePoint: null
        };

    // Figure out what we're hovering on:
    // mouse location or user-supplied data

    if(Array.isArray(evt)) {
        // user specified an array of points to highlight
        hovermode = 'array';
        for(itemnum = 0; itemnum < evt.length; itemnum++) {
            cd = gd.calcdata[evt[itemnum].curveNumber||0];
            if(cd[0].trace.hoverinfo !== 'skip') {
                searchData.push(cd);
            }
        }
    }
    else {
        for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
            cd = gd.calcdata[curvenum];
            trace = cd[0].trace;
            if(trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
                searchData.push(cd);
            }
        }

        // [x|y]px: the pixels (from top left) of the mouse location
        // on the currently selected plot area
        // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
        var hasUserCalledHover = !evt.target,
            xpx, ypx;

        if(hasUserCalledHover) {
            if('xpx' in evt) xpx = evt.xpx;
            else xpx = xaArray[0]._length / 2;

            if('ypx' in evt) ypx = evt.ypx;
            else ypx = yaArray[0]._length / 2;
        }
        else {
            // fire the beforehover event and quit if it returns false
            // note that we're only calling this on real mouse events, so
            // manual calls to fx.hover will always run.
            if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
                return;
            }

            var dbb = evt.target.getBoundingClientRect();

            xpx = evt.clientX - dbb.left;
            ypx = evt.clientY - dbb.top;

            // in case hover was called from mouseout into hovertext,
            // it's possible you're not actually over the plot anymore
            if(xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
                return dragElement.unhoverRaw(gd, evt);
            }
        }

        evt.pointerX = xpx + xaArray[0]._offset;
        evt.pointerY = ypx + yaArray[0]._offset;

        if('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);
        else xvalArray = helpers.p2c(xaArray, xpx);

        if('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);
        else yvalArray = helpers.p2c(yaArray, ypx);

        if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
            Lib.warn('Fx.hover failed', evt, gd);
            return dragElement.unhoverRaw(gd, evt);
        }
    }

    // the pixel distance to beat as a matching point
    // in 'x' or 'y' mode this resets for each trace
    var distance = Infinity;

    // find the closest point in each trace
    // this is minimum dx and/or dy, depending on mode
    // and the pixel position for the label (labelXpx, labelYpx)
    for(curvenum = 0; curvenum < searchData.length; curvenum++) {
        cd = searchData[curvenum];

        // filter out invisible or broken data
        if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue;

        trace = cd[0].trace;

        // Explicitly bail out for these two. I don't know how to otherwise prevent
        // the rest of this function from running and failing
        if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;

        if(trace.type === 'splom') {
            // splom traces do not generate overlay subplots,
            // it is safe to assume here splom traces correspond to the 0th subplot
            subploti = 0;
            subplotId = subplots[subploti];
        } else {
            subplotId = helpers.getSubplot(trace);
            subploti = subplots.indexOf(subplotId);
        }

        // within one trace mode can sometimes be overridden
        mode = hovermode;

        // container for new point, also used to pass info into module.hoverPoints
        pointData = {
            // trace properties
            cd: cd,
            trace: trace,
            xa: xaArray[subploti],
            ya: yaArray[subploti],

            // max distances for hover and spikes - for points that want to show but do not
            // want to override other points, set distance/spikeDistance equal to max*Distance
            // and it will not get filtered out but it will be guaranteed to have a greater
            // distance than any point that calculated a real distance.
            maxHoverDistance: hoverdistance,
            maxSpikeDistance: spikedistance,

            // point properties - override all of these
            index: false, // point index in trace - only used by plotly.js hoverdata consumers
            distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance

            // distance/pseudo-distance for spikes. This distance should always be calculated
            // as if in "closest" mode, and should only be set if this point should
            // generate a spike.
            spikeDistance: Infinity,

            // in some cases the spikes have different positioning from the hover label
            // they don't need x0/x1, just one position
            xSpike: undefined,
            ySpike: undefined,

            // where and how to display the hover label
            color: Color.defaultLine, // trace color
            name: trace.name,
            x0: undefined,
            x1: undefined,
            y0: undefined,
            y1: undefined,
            xLabelVal: undefined,
            yLabelVal: undefined,
            zLabelVal: undefined,
            text: undefined
        };

        // add ref to subplot object (non-cartesian case)
        if(fullLayout[subplotId]) {
            pointData.subplot = fullLayout[subplotId]._subplot;
        }

        closedataPreviousLength = hoverData.length;

        // for a highlighting array, figure out what
        // we're searching for with this element
        if(mode === 'array') {
            var selection = evt[curvenum];
            if('pointNumber' in selection) {
                pointData.index = selection.pointNumber;
                mode = 'closest';
            }
            else {
                mode = '';
                if('xval' in selection) {
                    xval = selection.xval;
                    mode = 'x';
                }
                if('yval' in selection) {
                    yval = selection.yval;
                    mode = mode ? 'closest' : 'y';
                }
            }
        }
        else {
            xval = xvalArray[subploti];
            yval = yvalArray[subploti];
        }

        // Now if there is range to look in, find the points to hover.
        if(hoverdistance !== 0) {
            if(trace._module && trace._module.hoverPoints) {
                var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer);
                if(newPoints) {
                    var newPoint;
                    for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
                        newPoint = newPoints[newPointNum];
                        if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
                            hoverData.push(cleanPoint(newPoint, hovermode));
                        }
                    }
                }
            }
            else {
                Lib.log('Unrecognized trace type in hover:', trace);
            }
        }

        // in closest mode, remove any existing (farther) points
        // and don't look any farther than this latest point (or points, some
        // traces like box & violin make multiple hover labels at once)
        if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
            hoverData.splice(0, closedataPreviousLength);
            distance = hoverData[0].distance;
        }

        // Now if there is range to look in, find the points to draw the spikelines
        // Do it only if there is no hoverData
        if(hasCartesian && (spikedistance !== 0)) {
            if(hoverData.length === 0) {
                pointData.distance = spikedistance;
                pointData.index = false;
                var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer);
                if(closestPoints) {
                    closestPoints = closestPoints.filter(function(point) {
                        // some hover points, like scatter fills, do not allow spikes,
                        // so will generate a hover point but without a valid spikeDistance
                        return point.spikeDistance <= spikedistance;
                    });
                }
                if(closestPoints && closestPoints.length) {
                    var tmpPoint;
                    var closestVPoints = closestPoints.filter(function(point) {
                        return point.xa.showspikes;
                    });
                    if(closestVPoints.length) {
                        var closestVPt = closestVPoints[0];
                        if(isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
                            tmpPoint = fillSpikePoint(closestVPt);
                            if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
                                spikePoints.vLinePoint = tmpPoint;
                            }
                        }
                    }

                    var closestHPoints = closestPoints.filter(function(point) {
                        return point.ya.showspikes;
                    });
                    if(closestHPoints.length) {
                        var closestHPt = closestHPoints[0];
                        if(isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
                            tmpPoint = fillSpikePoint(closestHPt);
                            if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
                                spikePoints.hLinePoint = tmpPoint;
                            }
                        }
                    }
                }
            }
        }
    }

    function selectClosestPoint(pointsData, spikedistance) {
        var resultPoint = null;
        var minDistance = Infinity;
        var thisSpikeDistance;
        for(var i = 0; i < pointsData.length; i++) {
            thisSpikeDistance = pointsData[i].spikeDistance;
            if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) {
                resultPoint = pointsData[i];
                minDistance = thisSpikeDistance;
            }
        }
        return resultPoint;
    }

    function fillSpikePoint(point) {
        if(!point) return null;
        return {
            xa: point.xa,
            ya: point.ya,
            x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
            y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
            distance: point.distance,
            spikeDistance: point.spikeDistance,
            curveNumber: point.trace.index,
            color: point.color,
            pointNumber: point.index
        };
    }

    var spikelineOpts = {
        fullLayout: fullLayout,
        container: fullLayout._hoverlayer,
        outerContainer: fullLayout._paperdiv,
        event: evt
    };
    var oldspikepoints = gd._spikepoints,
        newspikepoints = {
            vLinePoint: spikePoints.vLinePoint,
            hLinePoint: spikePoints.hLinePoint
        };
    gd._spikepoints = newspikepoints;

    // Now if it is not restricted by spikedistance option, set the points to draw the spikelines
    if(hasCartesian && (spikedistance !== 0)) {
        if(hoverData.length !== 0) {
            var tmpHPointData = hoverData.filter(function(point) {
                return point.ya.showspikes;
            });
            var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance);
            spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);

            var tmpVPointData = hoverData.filter(function(point) {
                return point.xa.showspikes;
            });
            var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance);
            spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
        }
    }

    // if hoverData is empty check for the spikes to draw and quit if there are none
    if(hoverData.length === 0) {
        var result = dragElement.unhoverRaw(gd, evt);
        if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) {
            if(spikesChanged(oldspikepoints)) {
                createSpikelines(spikePoints, spikelineOpts);
            }
        }
        return result;
    }

    if(hasCartesian) {
        if(spikesChanged(oldspikepoints)) {
            createSpikelines(spikePoints, spikelineOpts);
        }
    }

    hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });

    // lastly, emit custom hover/unhover events
    var oldhoverdata = gd._hoverdata,
        newhoverdata = [];

    // pull out just the data that's useful to
    // other people and send it to the event
    for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
        var pt = hoverData[itemnum];
        newhoverdata.push(helpers.makeEventData(pt, pt.trace, pt.cd));
    }

    gd._hoverdata = newhoverdata;

    // if there's more than one horz bar trace,
    // rotate the labels so they don't overlap
    var rotateLabels = hovermode === 'y' && searchData.length > 1;

    var bgColor = Color.combine(
        fullLayout.plot_bgcolor || Color.background,
        fullLayout.paper_bgcolor
    );

    var labelOpts = {
        hovermode: hovermode,
        rotateLabels: rotateLabels,
        bgColor: bgColor,
        container: fullLayout._hoverlayer,
        outerContainer: fullLayout._paperdiv,
        commonLabelOpts: fullLayout.hoverlabel,
        hoverdistance: fullLayout.hoverdistance
    };

    var hoverLabels = createHoverText(hoverData, labelOpts, gd);

    hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout);

    alignHoverText(hoverLabels, rotateLabels);

    // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true
    // we should improve the "fx" API so other plots can use it without these hack.
    if(evt.target && evt.target.tagName) {
        var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
        overrideCursor(d3.select(evt.target), hasClickToShow ? 'pointer' : '');
    }

    // don't emit events if called manually
    if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;

    if(oldhoverdata) {
        gd.emit('plotly_unhover', {
            event: evt,
            points: oldhoverdata
        });
    }

    gd.emit('plotly_hover', {
        event: evt,
        points: gd._hoverdata,
        xaxes: xaArray,
        yaxes: yaArray,
        xvals: xvalArray,
        yvals: yvalArray
    });
}

function createHoverText(hoverData, opts, gd) {
    var hovermode = opts.hovermode;
    var rotateLabels = opts.rotateLabels;
    var bgColor = opts.bgColor;
    var container = opts.container;
    var outerContainer = opts.outerContainer;
    var commonLabelOpts = opts.commonLabelOpts || {};

    // opts.fontFamily/Size are used for the common label
    // and as defaults for each hover label, though the individual labels
    // can override this.
    var fontFamily = opts.fontFamily || constants.HOVERFONT;
    var fontSize = opts.fontSize || constants.HOVERFONTSIZE;

    var c0 = hoverData[0];
    var xa = c0.xa;
    var ya = c0.ya;
    var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel';
    var t0 = c0[commonAttr];
    var t00 = (String(t0) || '').split(' ')[0];
    var outerContainerBB = outerContainer.node().getBoundingClientRect();
    var outerTop = outerContainerBB.top;
    var outerWidth = outerContainerBB.width;
    var outerHeight = outerContainerBB.height;

    // show the common label, if any, on the axis
    // never show a common label in array mode,
    // even if sometimes there could be one
    var showCommonLabel = (
        (t0 !== undefined) &&
        (c0.distance <= opts.hoverdistance) &&
        (hovermode === 'x' || hovermode === 'y')
    );

    // all hover traces hoverinfo must contain the hovermode
    // to have common labels
    if(showCommonLabel) {
        var i, traceHoverinfo;
        var allHaveZ = true;
        for(i = 0; i < hoverData.length; i++) {
            if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;

            traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
            var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
            if(parts.indexOf('all') === -1 &&
                parts.indexOf(hovermode) === -1) {
                showCommonLabel = false;
                break;
            }
        }

        // xyz labels put all info in their main label, so have no need of a common label
        if(allHaveZ) showCommonLabel = false;
    }

    var commonLabel = container.selectAll('g.axistext')
        .data(showCommonLabel ? [0] : []);
    commonLabel.enter().append('g')
        .classed('axistext', true);
    commonLabel.exit().remove();

    commonLabel.each(function() {
        var label = d3.select(this);
        var lpath = Lib.ensureSingle(label, 'path', '', function(s) {
            s.style({'stroke-width': '1px'});
        });
        var ltext = Lib.ensureSingle(label, 'text', '', function(s) {
            // prohibit tex interpretation until we can handle
            // tex and regular text together
            s.attr('data-notex', 1);
        });

        var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
        var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);

        lpath.style({
            fill: commonBgColor,
            stroke: commonStroke
        });

        ltext.text(t0)
            .call(Drawing.font,
                commonLabelOpts.font.family || fontFamily,
                commonLabelOpts.font.size || fontSize,
                commonLabelOpts.font.color || Color.background
             )
            .call(svgTextUtils.positionText, 0, 0)
            .call(svgTextUtils.convertToTspans, gd);

        label.attr('transform', '');

        var tbb = ltext.node().getBoundingClientRect();
        if(hovermode === 'x') {
            ltext.attr('text-anchor', 'middle')
                .call(svgTextUtils.positionText, 0, (xa.side === 'top' ?
                    (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
                    (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)));

            var topsign = xa.side === 'top' ? '-' : '';
            lpath.attr('d', 'M0,0' +
                'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
                'H' + (HOVERTEXTPAD + tbb.width / 2) +
                'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
                'H-' + (HOVERTEXTPAD + tbb.width / 2) +
                'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z');

            label.attr('transform', 'translate(' +
                (xa._offset + (c0.x0 + c0.x1) / 2) + ',' +
                (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')');
        }
        else {
            ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end')
                .call(svgTextUtils.positionText,
                    (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE),
                    outerTop - tbb.top - tbb.height / 2);

            var leftsign = ya.side === 'right' ? '' : '-';
            lpath.attr('d', 'M0,0' +
                'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
                'V' + (HOVERTEXTPAD + tbb.height / 2) +
                'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
                'V-' + (HOVERTEXTPAD + tbb.height / 2) +
                'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');

            label.attr('transform', 'translate(' +
                (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' +
                (ya._offset + (c0.y0 + c0.y1) / 2) + ')');
        }
        // remove the "close but not quite" points
        // because of error bars, only take up to a space
        hoverData = hoverData.filter(function(d) {
            return (d.zLabelVal !== undefined) ||
                (d[commonAttr] || '').split(' ')[0] === t00;
        });
    });

    // show all the individual labels

    // first create the objects
    var hoverLabels = container.selectAll('g.hovertext')
        .data(hoverData, function(d) {
            return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
        });
    hoverLabels.enter().append('g')
        .classed('hovertext', true)
        .each(function() {
            var g = d3.select(this);
            // trace name label (rect and text.name)
            g.append('rect')
                .call(Color.fill, Color.addOpacity(bgColor, 0.8));
            g.append('text').classed('name', true);
            // trace data label (path and text.nums)
            g.append('path')
                .style('stroke-width', '1px');
            g.append('text').classed('nums', true)
                .call(Drawing.font, fontFamily, fontSize);
        });
    hoverLabels.exit().remove();

    // then put the text in, position the pointer to the data,
    // and figure out sizes
    hoverLabels.each(function(d) {
        var g = d3.select(this).attr('transform', ''),
            name = '',
            text = '';

            // combine possible non-opaque trace color with bgColor
        var baseColor = Color.opacity(d.color) ? d.color : Color.defaultLine;
        var traceColor = Color.combine(baseColor, bgColor);

        // find a contrasting color for border and text
        var contrastColor = d.borderColor || Color.contrast(traceColor);

        // to get custom 'name' labels pass cleanPoint
        if(d.nameOverride !== undefined) d.name = d.nameOverride;

        if(d.name) {
            // strip out our pseudo-html elements from d.name (if it exists at all)
            name = svgTextUtils.plainText(d.name || '');

            var nameLength = Math.round(d.nameLength);

            if(nameLength > -1 && name.length > nameLength) {
                if(nameLength > 3) name = name.substr(0, nameLength - 3) + '...';
                else name = name.substr(0, nameLength);
            }
        }

        if(d.zLabel !== undefined) {
            if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
            if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
            text += (text ? 'z: ' : '') + d.zLabel;
        }
        else if(showCommonLabel && d[hovermode + 'Label'] === t0) {
            text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || '';
        }
        else if(d.xLabel === undefined) {
            if(d.yLabel !== undefined) text = d.yLabel;
        }
        else if(d.yLabel === undefined) text = d.xLabel;
        else text = '(' + d.xLabel + ', ' + d.yLabel + ')';

        if(d.text && !Array.isArray(d.text)) {
            text += (text ? '<br>' : '') + d.text;
        }

        // used by other modules (initially just ternary) that
        // manage their own hoverinfo independent of cleanPoint
        // the rest of this will still apply, so such modules
        // can still put things in (x|y|z)Label, text, and name
        // and hoverinfo will still determine their visibility
        if(d.extraText !== undefined) text += (text ? '<br>' : '') + d.extraText;

        // if 'text' is empty at this point,
        // put 'name' in main label and don't show secondary label
        if(text === '') {
            // if 'name' is also empty, remove entire label
            if(name === '') g.remove();
            text = name;
        }

        // main label
        var tx = g.select('text.nums')
            .call(Drawing.font,
                d.fontFamily || fontFamily,
                d.fontSize || fontSize,
                d.fontColor || contrastColor)
            .text(text)
            .attr('data-notex', 1)
            .call(svgTextUtils.positionText, 0, 0)
            .call(svgTextUtils.convertToTspans, gd);

        var tx2 = g.select('text.name'),
            tx2width = 0;

        // secondary label for non-empty 'name'
        if(name && name !== text) {
            tx2.call(Drawing.font,
                    d.fontFamily || fontFamily,
                    d.fontSize || fontSize,
                    traceColor)
                .text(name)
                .attr('data-notex', 1)
                .call(svgTextUtils.positionText, 0, 0)
                .call(svgTextUtils.convertToTspans, gd);
            tx2width = tx2.node().getBoundingClientRect().width + 2 * HOVERTEXTPAD;
        }
        else {
            tx2.remove();
            g.select('rect').remove();
        }

        g.select('path')
            .style({
                fill: traceColor,
                stroke: contrastColor
            });
        var tbb = tx.node().getBoundingClientRect(),
            htx = d.xa._offset + (d.x0 + d.x1) / 2,
            hty = d.ya._offset + (d.y0 + d.y1) / 2,
            dx = Math.abs(d.x1 - d.x0),
            dy = Math.abs(d.y1 - d.y0),
            txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width,
            anchorStartOK,
            anchorEndOK;

        d.ty0 = outerTop - tbb.top;
        d.bx = tbb.width + 2 * HOVERTEXTPAD;
        d.by = tbb.height + 2 * HOVERTEXTPAD;
        d.anchor = 'start';
        d.txwidth = tbb.width;
        d.tx2width = tx2width;
        d.offset = 0;

        if(rotateLabels) {
            d.pos = htx;
            anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
            anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
            if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
                hty -= dy / 2;
                d.anchor = 'end';
            } else if(anchorStartOK) {
                hty += dy / 2;
                d.anchor = 'start';
            } else d.anchor = 'middle';
        }
        else {
            d.pos = hty;
            anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
            anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
            if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
                htx -= dx / 2;
                d.anchor = 'end';
            } else if(anchorStartOK) {
                htx += dx / 2;
                d.anchor = 'start';
            } else d.anchor = 'middle';
        }

        tx.attr('text-anchor', d.anchor);
        if(tx2width) tx2.attr('text-anchor', d.anchor);
        g.attr('transform', 'translate(' + htx + ',' + hty + ')' +
            (rotateLabels ? 'rotate(' + YANGLE + ')' : ''));
    });

    return hoverLabels;
}

// Make groups of touching points, and within each group
// move each point so that no labels overlap, but the average
// label position is the same as it was before moving. Indicentally,
// this is equivalent to saying all the labels are on equal linear
// springs about their initial position. Initially, each point is
// its own group, but as we find overlaps we will clump the points.
//
// Also, there are hard constraints at the edges of the graphs,
// that push all groups to the middle so they are visible. I don't
// know what happens if the group spans all the way from one edge to
// the other, though it hardly matters - there's just too much
// information then.
function hoverAvoidOverlaps(hoverData, ax, fullLayout) {
    var nummoves = 0,

        // make groups of touching points
        pointgroups = hoverData
            .map(function(d, i) {
                var axis = d[ax];
                return [{
                    i: i,
                    dp: 0,
                    pos: d.pos,
                    posref: d.posref,
                    size: d.by * (axis._id.charAt(0) === 'x' ? YFACTOR : 1) / 2,
                    pmin: 0,
                    pmax: (axis._id.charAt(0) === 'x' ? fullLayout.width : fullLayout.height)
                }];
            })
            .sort(function(a, b) { return a[0].posref - b[0].posref; }),
        donepositioning,
        topOverlap,
        bottomOverlap,
        i, j,
        pti,
        sumdp;

    function constrainGroup(grp) {
        var minPt = grp[0],
            maxPt = grp[grp.length - 1];

        // overlap with the top - positive vals are overlaps
        topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;

        // overlap with the bottom - positive vals are overlaps
        bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;

        // check for min overlap first, so that we always
        // see the largest labels
        // allow for .01px overlap, so we don't get an
        // infinite loop from rounding errors
        if(topOverlap > 0.01) {
            for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
            donepositioning = false;
        }
        if(bottomOverlap < 0.01) return;
        if(topOverlap < -0.01) {
            // make sure we're not pushing back and forth
            for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
            donepositioning = false;
        }
        if(!donepositioning) return;

        // no room to fix positioning, delete off-screen points

        // first see how many points we need to delete
        var deleteCount = 0;
        for(i = 0; i < grp.length; i++) {
            pti = grp[i];
            if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
        }

        // start by deleting points whose data is off screen
        for(i = grp.length - 1; i >= 0; i--) {
            if(deleteCount <= 0) break;
            pti = grp[i];

            // pos has already been constrained to [pmin,pmax]
            // so look for points close to that to delete
            if(pti.pos > minPt.pmax - 1) {
                pti.del = true;
                deleteCount--;
            }
        }
        for(i = 0; i < grp.length; i++) {
            if(deleteCount <= 0) break;
            pti = grp[i];

            // pos has already been constrained to [pmin,pmax]
            // so look for points close to that to delete
            if(pti.pos < minPt.pmin + 1) {
                pti.del = true;
                deleteCount--;

                // shift the whole group minus into this new space
                bottomOverlap = pti.size * 2;
                for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
            }
        }
        // then delete points that go off the bottom
        for(i = grp.length - 1; i >= 0; i--) {
            if(deleteCount <= 0) break;
            pti = grp[i];
            if(pti.pos + pti.dp + pti.size > minPt.pmax) {
                pti.del = true;
                deleteCount--;
            }
        }
    }

    // loop through groups, combining them if they overlap,
    // until nothing moves
    while(!donepositioning && nummoves <= hoverData.length) {
        // to avoid infinite loops, don't move more times
        // than there are traces
        nummoves++;

        // assume nothing will move in this iteration,
        // reverse this if it does
        donepositioning = true;
        i = 0;
        while(i < pointgroups.length - 1) {
                // the higher (g0) and lower (g1) point group
            var g0 = pointgroups[i],
                g1 = pointgroups[i + 1],

                // the lowest point in the higher group (p0)
                // the highest point in the lower group (p1)
                p0 = g0[g0.length - 1],
                p1 = g1[0];
            topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;

            // Only group points that lie on the same axes
            if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) {
                // push the new point(s) added to this group out of the way
                for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;

                // add them to the group
                g0.push.apply(g0, g1);
                pointgroups.splice(i + 1, 1);

                // adjust for minimum average movement
                sumdp = 0;
                for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
                bottomOverlap = sumdp / g0.length;
                for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
                donepositioning = false;
            }
            else i++;
        }

        // check if we're going off the plot on either side and fix
        pointgroups.forEach(constrainGroup);
    }

    // now put these offsets into hoverData
    for(i = pointgroups.length - 1; i >= 0; i--) {
        var grp = pointgroups[i];
        for(j = grp.length - 1; j >= 0; j--) {
            var pt = grp[j],
                hoverPt = hoverData[pt.i];
            hoverPt.offset = pt.dp;
            hoverPt.del = pt.del;
        }
    }
}

function alignHoverText(hoverLabels, rotateLabels) {
    // finally set the text positioning relative to the data and draw the
    // box around it
    hoverLabels.each(function(d) {
        var g = d3.select(this);
        if(d.del) {
            g.remove();
            return;
        }
        var horzSign = d.anchor === 'end' ? -1 : 1,
            tx = g.select('text.nums'),
            alignShift = {start: 1, end: -1, middle: 0}[d.anchor],
            txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD),
            tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD),
            offsetX = 0,
            offsetY = d.offset;
        if(d.anchor === 'middle') {
            txx -= d.tx2width / 2;
            tx2x += d.txwidth / 2 + HOVERTEXTPAD;
        }
        if(rotateLabels) {
            offsetY *= -YSHIFTY;
            offsetX = d.offset * YSHIFTX;
        }

        g.select('path').attr('d', d.anchor === 'middle' ?
            // middle aligned: rect centered on data
            ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) +
              'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') :
            // left or right aligned: side rect with arrow to data
            ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) +
                'v' + (d.by / 2 - HOVERARROWSIZE) +
                'h' + (horzSign * d.bx) +
                'v-' + d.by +
                'H' + (horzSign * HOVERARROWSIZE + offsetX) +
                'V' + (offsetY - HOVERARROWSIZE) +
                'Z'));

        tx.call(svgTextUtils.positionText,
            txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);

        if(d.tx2width) {
            g.select('text.name')
                .call(svgTextUtils.positionText,
                    tx2x + alignShift * HOVERTEXTPAD + offsetX,
                    offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);
            g.select('rect')
                .call(Drawing.setRect,
                    tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX,
                    offsetY - d.by / 2 - 1,
                    d.tx2width, d.by + 2);
        }
    });
}

function cleanPoint(d, hovermode) {
    var index = d.index;
    var trace = d.trace || {};
    var cd0 = d.cd[0];
    var cd = d.cd[index] || {};

    var getVal = Array.isArray(index) ?
        function(calcKey, traceKey) {
            return Lib.castOption(cd0, index, calcKey) ||
                Lib.extractOption({}, trace, '', traceKey);
        } :
        function(calcKey, traceKey) {
            return Lib.extractOption(cd, trace, calcKey, traceKey);
        };

    function fill(key, calcKey, traceKey) {
        var val = getVal(calcKey, traceKey);
        if(val) d[key] = val;
    }

    fill('hoverinfo', 'hi', 'hoverinfo');
    fill('color', 'hbg', 'hoverlabel.bgcolor');
    fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
    fill('fontFamily', 'htf', 'hoverlabel.font.family');
    fill('fontSize', 'hts', 'hoverlabel.font.size');
    fill('fontColor', 'htc', 'hoverlabel.font.color');
    fill('nameLength', 'hnl', 'hoverlabel.namelength');

    d.posref = hovermode === 'y' ?
        (d.xa._offset + (d.x0 + d.x1) / 2) :
        (d.ya._offset + (d.y0 + d.y1) / 2);

    // then constrain all the positions to be on the plot
    d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
    d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
    d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
    d.y1 = Lib.constrain(d.y1, 0, d.ya._length);

    // and convert the x and y label values into formatted text
    if(d.xLabelVal !== undefined) {
        d.xLabel = ('xLabel' in d) ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal);
        d.xVal = d.xa.c2d(d.xLabelVal);
    }
    if(d.yLabelVal !== undefined) {
        d.yLabel = ('yLabel' in d) ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal);
        d.yVal = d.ya.c2d(d.yLabelVal);
    }

    // Traces like heatmaps generate the zLabel in their hoverPoints function
    if(d.zLabelVal !== undefined && d.zLabel === undefined) {
        d.zLabel = String(d.zLabelVal);
    }

    // for box means and error bars, add the range to the label
    if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
        var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
        if(d.xerrneg !== undefined) {
            d.xLabel += ' +' + xeText + ' / -' +
                Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
        }
        else d.xLabel += ' ± ' + xeText;

        // small distance penalty for error bars, so that if there are
        // traces with errors and some without, the error bar label will
        // hoist up to the point
        if(hovermode === 'x') d.distance += 1;
    }
    if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
        var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
        if(d.yerrneg !== undefined) {
            d.yLabel += ' +' + yeText + ' / -' +
                Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
        }
        else d.yLabel += ' ± ' + yeText;

        if(hovermode === 'y') d.distance += 1;
    }

    var infomode = d.hoverinfo || d.trace.hoverinfo;

    if(infomode !== 'all') {
        infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
        if(infomode.indexOf('x') === -1) d.xLabel = undefined;
        if(infomode.indexOf('y') === -1) d.yLabel = undefined;
        if(infomode.indexOf('z') === -1) d.zLabel = undefined;
        if(infomode.indexOf('text') === -1) d.text = undefined;
        if(infomode.indexOf('name') === -1) d.name = undefined;
    }

    return d;
}

function createSpikelines(closestPoints, opts) {
    var container = opts.container;
    var fullLayout = opts.fullLayout;
    var evt = opts.event;
    var xa,
        ya;

    var showY = !!closestPoints.hLinePoint;
    var showX = !!closestPoints.vLinePoint;

    // Remove old spikeline items
    container.selectAll('.spikeline').remove();

    if(!(showX || showY)) return;

    var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);

    // Horizontal line (to y-axis)
    if(showY) {
        var hLinePoint = closestPoints.hLinePoint,
            hLinePointX,
            hLinePointY;
        xa = hLinePoint && hLinePoint.xa;
        ya = hLinePoint && hLinePoint.ya;
        var ySnap = ya.spikesnap;

        if(ySnap === 'cursor') {
            hLinePointX = evt.pointerX;
            hLinePointY = evt.pointerY;
        } else {
            hLinePointX = xa._offset + hLinePoint.x;
            hLinePointY = ya._offset + hLinePoint.y;
        }
        var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ?
            Color.contrast(contrastColor) : hLinePoint.color;
        var yMode = ya.spikemode,
            yThickness = ya.spikethickness,
            yColor = ya.spikecolor || dfltHLineColor,
            yBB = ya._boundingBox,
            xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left,
            xBase,
            xEndSpike;

        if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
            if(yMode.indexOf('toaxis') !== -1) {
                xBase = xEdge;
                xEndSpike = hLinePointX;
            }
            if(yMode.indexOf('across') !== -1) {
                xBase = ya._counterSpan[0];
                xEndSpike = ya._counterSpan[1];
            }

            // Foreground horizontal line (to y-axis)
            container.insert('line', ':first-child')
                .attr({
                    'x1': xBase,
                    'x2': xEndSpike,
                    'y1': hLinePointY,
                    'y2': hLinePointY,
                    'stroke-width': yThickness,
                    'stroke': yColor,
                    'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
                })
                .classed('spikeline', true)
                .classed('crisp', true);

            // Background horizontal Line (to y-axis)
            container.insert('line', ':first-child')
                .attr({
                    'x1': xBase,
                    'x2': xEndSpike,
                    'y1': hLinePointY,
                    'y2': hLinePointY,
                    'stroke-width': yThickness + 2,
                    'stroke': contrastColor
                })
                .classed('spikeline', true)
                .classed('crisp', true);
        }
        // Y axis marker
        if(yMode.indexOf('marker') !== -1) {
            container.insert('circle', ':first-child')
                .attr({
                    'cx': xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
                    'cy': hLinePointY,
                    'r': yThickness,
                    'fill': yColor
                })
                .classed('spikeline', true);
        }
    }

    if(showX) {
        var vLinePoint = closestPoints.vLinePoint,
            vLinePointX,
            vLinePointY;

        xa = vLinePoint && vLinePoint.xa;
        ya = vLinePoint && vLinePoint.ya;
        var xSnap = xa.spikesnap;

        if(xSnap === 'cursor') {
            vLinePointX = evt.pointerX;
            vLinePointY = evt.pointerY;
        } else {
            vLinePointX = xa._offset + vLinePoint.x;
            vLinePointY = ya._offset + vLinePoint.y;
        }
        var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ?
        Color.contrast(contrastColor) : vLinePoint.color;
        var xMode = xa.spikemode,
            xThickness = xa.spikethickness,
            xColor = xa.spikecolor || dfltVLineColor,
            xBB = xa._boundingBox,
            yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top,
            yBase,
            yEndSpike;

        if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
            if(xMode.indexOf('toaxis') !== -1) {
                yBase = yEdge;
                yEndSpike = vLinePointY;
            }
            if(xMode.indexOf('across') !== -1) {
                yBase = xa._counterSpan[0];
                yEndSpike = xa._counterSpan[1];
            }

            // Foreground vertical line (to x-axis)
            container.insert('line', ':first-child')
                .attr({
                    'x1': vLinePointX,
                    'x2': vLinePointX,
                    'y1': yBase,
                    'y2': yEndSpike,
                    'stroke-width': xThickness,
                    'stroke': xColor,
                    'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
                })
                .classed('spikeline', true)
                .classed('crisp', true);

            // Background vertical line (to x-axis)
            container.insert('line', ':first-child')
                .attr({
                    'x1': vLinePointX,
                    'x2': vLinePointX,
                    'y1': yBase,
                    'y2': yEndSpike,
                    'stroke-width': xThickness + 2,
                    'stroke': contrastColor
                })
                .classed('spikeline', true)
                .classed('crisp', true);
        }

        // X axis marker
        if(xMode.indexOf('marker') !== -1) {
            container.insert('circle', ':first-child')
                .attr({
                    'cx': vLinePointX,
                    'cy': yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
                    'r': xThickness,
                    'fill': xColor
                })
                .classed('spikeline', true);
        }
    }
}

function hoverChanged(gd, evt, oldhoverdata) {
    // don't emit any events if nothing changed
    if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;

    for(var i = oldhoverdata.length - 1; i >= 0; i--) {
        var oldPt = oldhoverdata[i],
            newPt = gd._hoverdata[i];
        if(oldPt.curveNumber !== newPt.curveNumber ||
                String(oldPt.pointNumber) !== String(newPt.pointNumber)) {
            return true;
        }
    }
    return false;
}

function spikesChanged(gd, oldspikepoints) {
    // don't relayout the plot because of new spikelines if spikelines points didn't change
    if(!oldspikepoints) return true;
    if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint ||
        oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint
    ) return true;
    return false;
}

},{"../../lib":164,"../../lib/events":156,"../../lib/override_cursor":175,"../../lib/svg_text_utils":185,"../../plots/cartesian/axes":206,"../../registry":254,"../color":43,"../dragelement":65,"../drawing":68,"./constants":80,"./helpers":82,"d3":6,"fast-isnumeric":9,"tinycolor2":25}],84:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');

module.exports = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) {
    opts = opts || {};

    coerce('hoverlabel.bgcolor', opts.bgcolor);
    coerce('hoverlabel.bordercolor', opts.bordercolor);
    coerce('hoverlabel.namelength', opts.namelength);
    Lib.coerceFont(coerce, 'hoverlabel.font', opts.font);
};

},{"../../lib":164}],85:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');
var Lib = require('../../lib');
var dragElement = require('../dragelement');
var helpers = require('./helpers');
var layoutAttributes = require('./layout_attributes');

module.exports = {
    moduleType: 'component',
    name: 'fx',

    constants: require('./constants'),
    schema: {
        layout: layoutAttributes
    },

    attributes: require('./attributes'),
    layoutAttributes: layoutAttributes,

    supplyLayoutGlobalDefaults: require('./layout_global_defaults'),
    supplyDefaults: require('./defaults'),
    supplyLayoutDefaults: require('./layout_defaults'),

    calc: require('./calc'),

    getDistanceFunction: helpers.getDistanceFunction,
    getClosest: helpers.getClosest,
    inbox: helpers.inbox,
    quadrature: helpers.quadrature,
    appendArrayPointValue: helpers.appendArrayPointValue,

    castHoverOption: castHoverOption,
    castHoverinfo: castHoverinfo,

    hover: require('./hover').hover,
    unhover: dragElement.unhover,

    loneHover: require('./hover').loneHover,
    loneUnhover: loneUnhover,

    click: require('./click')
};

function loneUnhover(containerOrSelection) {
    // duck type whether the arg is a d3 selection because ie9 doesn't
    // handle instanceof like modern browsers do.
    var selection = Lib.isD3Selection(containerOrSelection) ?
            containerOrSelection :
            d3.select(containerOrSelection);

    selection.selectAll('g.hovertext').remove();
    selection.selectAll('.spikeline').remove();
}

// helpers for traces that use Fx.loneHover

function castHoverOption(trace, ptNumber, attr) {
    return Lib.castOption(trace, ptNumber, 'hoverlabel.' + attr);
}

function castHoverinfo(trace, fullLayout, ptNumber) {
    function _coerce(val) {
        return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
    }

    return Lib.castOption(trace, ptNumber, 'hoverinfo', _coerce);
}

},{"../../lib":164,"../dragelement":65,"./attributes":77,"./calc":78,"./click":79,"./constants":80,"./defaults":81,"./helpers":82,"./hover":83,"./layout_attributes":86,"./layout_defaults":87,"./layout_global_defaults":88,"d3":6}],86:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = require('./constants');

var fontAttrs = require('../../plots/font_attributes')({
    editType: 'none',
    
});
fontAttrs.family.dflt = constants.HOVERFONT;
fontAttrs.size.dflt = constants.HOVERFONTSIZE;

module.exports = {
    dragmode: {
        valType: 'enumerated',
        
        values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'],
        dflt: 'zoom',
        editType: 'modebar',
        
    },
    hovermode: {
        valType: 'enumerated',
        
        values: ['x', 'y', 'closest', false],
        editType: 'modebar',
        
    },
    hoverdistance: {
        valType: 'integer',
        min: -1,
        dflt: 20,
        
        editType: 'none',
        
    },
    spikedistance: {
        valType: 'integer',
        min: -1,
        dflt: 20,
        
        editType: 'none',
        
    },
    hoverlabel: {
        bgcolor: {
            valType: 'color',
            
            editType: 'none',
            
        },
        bordercolor: {
            valType: 'color',
            
            editType: 'none',
            
        },
        font: fontAttrs,
        namelength: {
            valType: 'integer',
            min: -1,
            dflt: 15,
            
            editType: 'none',
            
        },
        editType: 'none'
    },
    selectdirection: {
        valType: 'enumerated',
        
        values: ['h', 'v', 'd', 'any'],
        dflt: 'any',
        
        editType: 'none'
    }
};

},{"../../plots/font_attributes":232,"./constants":80}],87:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var layoutAttributes = require('./layout_attributes');

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    var dragMode = coerce('dragmode');
    if(dragMode === 'select') coerce('selectdirection');

    var hovermodeDflt;
    if(layoutOut._has('cartesian')) {
        // flag for 'horizontal' plots:
        // determines the state of the mode bar 'compare' hovermode button
        layoutOut._isHoriz = isHoriz(fullData);
        hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x';
    }
    else hovermodeDflt = 'closest';

    var hoverMode = coerce('hovermode', hovermodeDflt);
    if(hoverMode) {
        coerce('hoverdistance');
        coerce('spikedistance');
    }

    // if only mapbox or geo subplots is present on graph,
    // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented,
    // so that the correct modebar button is active
    var hasMapbox = layoutOut._has('mapbox');
    var hasGeo = layoutOut._has('geo');
    var len = layoutOut._basePlotModules.length;

    if(layoutOut.dragmode === 'zoom' && (
        ((hasMapbox || hasGeo) && len === 1) ||
        (hasMapbox && hasGeo && len === 2)
    )) {
        layoutOut.dragmode = 'pan';
    }
};

function isHoriz(fullData) {
    var out = true;

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(trace.orientation !== 'h') {
            out = false;
            break;
        }
    }

    return out;
}

},{"../../lib":164,"./layout_attributes":86}],88:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var handleHoverLabelDefaults = require('./hoverlabel_defaults');
var layoutAttributes = require('./layout_attributes');

module.exports = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
    }

    handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
};

},{"../../lib":164,"./hoverlabel_defaults":84,"./layout_attributes":86}],89:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var counterRegex = require('../../lib/regex').counter;
var domainAttrs = require('../../plots/domain').attributes;
var cartesianIdRegex = require('../../plots/cartesian/constants').idRegex;

var gridAttrs = {
    rows: {
        valType: 'integer',
        min: 1,
        
        editType: 'plot',
        
    },
    roworder: {
        valType: 'enumerated',
        values: ['top to bottom', 'bottom to top'],
        dflt: 'top to bottom',
        
        editType: 'plot',
        
    },
    columns: {
        valType: 'integer',
        min: 1,
        
        editType: 'plot',
        
    },
    subplots: {
        valType: 'info_array',
        freeLength: true,
        dimensions: 2,
        items: {valType: 'enumerated', values: [counterRegex('xy').toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    xaxes: {
        valType: 'info_array',
        freeLength: true,
        items: {valType: 'enumerated', values: [cartesianIdRegex.x.toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    yaxes: {
        valType: 'info_array',
        freeLength: true,
        items: {valType: 'enumerated', values: [cartesianIdRegex.y.toString(), ''], editType: 'plot'},
        
        editType: 'plot',
        
    },
    pattern: {
        valType: 'enumerated',
        values: ['independent', 'coupled'],
        dflt: 'coupled',
        
        editType: 'plot',
        
    },
    xgap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    ygap: {
        valType: 'number',
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    domain: domainAttrs({name: 'grid', editType: 'plot', noGridCell: true}, {
        
    }),
    xside: {
        valType: 'enumerated',
        values: ['bottom', 'bottom plot', 'top plot', 'top'],
        dflt: 'bottom plot',
        
        editType: 'plot',
        
    },
    yside: {
        valType: 'enumerated',
        values: ['left', 'left plot', 'right plot', 'right'],
        dflt: 'left plot',
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

function getAxes(layout, grid, axLetter) {
    var gridVal = grid[axLetter + 'axes'];
    var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {});

    if(Array.isArray(gridVal)) return gridVal;
    if(splomVal.length) return splomVal;
}

// the shape of the grid - this needs to be done BEFORE supplyDataDefaults
// so that non-subplot traces can place themselves in the grid
function sizeDefaults(layoutIn, layoutOut) {
    var gridIn = layoutIn.grid || {};
    var xAxes = getAxes(layoutOut, gridIn, 'x');
    var yAxes = getAxes(layoutOut, gridIn, 'y');

    if(!layoutIn.grid && !xAxes && !yAxes) return;

    var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]);
    var hasXaxes = Array.isArray(xAxes);
    var hasYaxes = Array.isArray(yAxes);
    var isSplomGenerated = (
        hasXaxes && xAxes !== gridIn.xaxes &&
        hasYaxes && yAxes !== gridIn.yaxes
    );

    var dfltRows, dfltColumns;

    if(hasSubplotGrid) {
        dfltRows = gridIn.subplots.length;
        dfltColumns = gridIn.subplots[0].length;
    }
    else {
        if(hasYaxes) dfltRows = yAxes.length;
        if(hasXaxes) dfltColumns = xAxes.length;
    }

    var gridOut = layoutOut.grid = {};

    function coerce(attr, dflt) {
        return Lib.coerce(gridIn, gridOut, gridAttrs, attr, dflt);
    }

    var rows = coerce('rows', dfltRows);
    var columns = coerce('columns', dfltColumns);

    if(!(rows * columns > 1)) return;

    if(!hasSubplotGrid && !hasXaxes && !hasYaxes) {
        var useDefaultSubplots = coerce('pattern') === 'independent';
        if(useDefaultSubplots) hasSubplotGrid = true;
    }
    gridOut._hasSubplotGrid = hasSubplotGrid;

    var rowOrder = coerce('roworder');
    var reversed = rowOrder === 'top to bottom';

    var dfltGapX = hasSubplotGrid ? 0.2 : 0.1;
    var dfltGapY = hasSubplotGrid ? 0.3 : 0.1;

    var dfltSideX, dfltSideY;
    if(isSplomGenerated) {
        dfltSideX = 'bottom';
        dfltSideY = 'left';
    }

    gridOut._domains = {
        x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns),
        y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed)
    };
}

// coerce x or y sizing attributes and return an array of domains for this direction
function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) {
    var dirGap = coerce(axLetter + 'gap', dfltGap);
    var domain = coerce('domain.' + axLetter);
    coerce(axLetter + 'side', dfltSide);

    var out = new Array(len);
    var start = domain[0];
    var step = (domain[1] - start) / (len - dirGap);
    var cellDomain = step * (1 - dirGap);
    for(var i = 0; i < len; i++) {
        var cellStart = start + step * i;
        out[reversed ? (len - 1 - i) : i] = [cellStart, cellStart + cellDomain];
    }
    return out;
}

// the (cartesian) contents of the grid - this needs to happen AFTER supplyDataDefaults
// so that we know what cartesian subplots are available
function contentDefaults(layoutIn, layoutOut) {
    var gridOut = layoutOut.grid;
    // make sure we got to the end of handleGridSizing
    if(!gridOut || !gridOut._domains) return;

    var gridIn = layoutIn.grid || {};
    var subplots = layoutOut._subplots;
    var hasSubplotGrid = gridOut._hasSubplotGrid;
    var rows = gridOut.rows;
    var columns = gridOut.columns;
    var useDefaultSubplots = gridOut.pattern === 'independent';

    var i, j, xId, yId, subplotId, subplotsOut, yPos;

    var axisMap = gridOut._axisMap = {};

    if(hasSubplotGrid) {
        var subplotsIn = gridIn.subplots || [];
        subplotsOut = gridOut.subplots = new Array(rows);
        var index = 1;

        for(i = 0; i < rows; i++) {
            var rowOut = subplotsOut[i] = new Array(columns);
            var rowIn = subplotsIn[i] || [];
            for(j = 0; j < columns; j++) {
                if(useDefaultSubplots) {
                    subplotId = (index === 1) ? 'xy' : ('x' + index + 'y' + index);
                    index++;
                }
                else subplotId = rowIn[j];

                rowOut[j] = '';

                if(subplots.cartesian.indexOf(subplotId) !== -1) {
                    yPos = subplotId.indexOf('y');
                    xId = subplotId.slice(0, yPos);
                    yId = subplotId.slice(yPos);
                    if((axisMap[xId] !== undefined && axisMap[xId] !== j) ||
                        (axisMap[yId] !== undefined && axisMap[yId] !== i)
                    ) {
                        continue;
                    }

                    rowOut[j] = subplotId;
                    axisMap[xId] = j;
                    axisMap[yId] = i;
                }
            }
        }
    }
    else {
        var xAxes = getAxes(layoutOut, gridIn, 'x');
        var yAxes = getAxes(layoutOut, gridIn, 'y');
        gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');
        gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');
    }

    var anchors = gridOut._anchors = {};
    var reversed = gridOut.roworder === 'top to bottom';

    for(var axisId in axisMap) {
        var axLetter = axisId.charAt(0);
        var side = gridOut[axLetter + 'side'];

        var i0, inc, iFinal;

        if(side.length < 8) {
            // grid edge -  ie not "* plot" - make these as free axes
            // since we're not guaranteed to have a subplot there at all
            anchors[axisId] = 'free';
        }
        else if(axLetter === 'x') {
            if((side.charAt(0) === 't') === reversed) {
                i0 = 0;
                inc = 1;
                iFinal = rows;
            }
            else {
                i0 = rows - 1;
                inc = -1;
                iFinal = -1;
            }
            if(hasSubplotGrid) {
                var column = axisMap[axisId];
                for(i = i0; i !== iFinal; i += inc) {
                    subplotId = subplotsOut[i][column];
                    if(!subplotId) continue;
                    yPos = subplotId.indexOf('y');
                    if(subplotId.slice(0, yPos) === axisId) {
                        anchors[axisId] = subplotId.slice(yPos);
                        break;
                    }
                }
            }
            else {
                for(i = i0; i !== iFinal; i += inc) {
                    yId = gridOut.yaxes[i];
                    if(subplots.cartesian.indexOf(axisId + yId) !== -1) {
                        anchors[axisId] = yId;
                        break;
                    }
                }
            }
        }
        else {
            if((side.charAt(0) === 'l')) {
                i0 = 0;
                inc = 1;
                iFinal = columns;
            }
            else {
                i0 = columns - 1;
                inc = -1;
                iFinal = -1;
            }
            if(hasSubplotGrid) {
                var row = axisMap[axisId];
                for(i = i0; i !== iFinal; i += inc) {
                    subplotId = subplotsOut[row][i];
                    if(!subplotId) continue;
                    yPos = subplotId.indexOf('y');
                    if(subplotId.slice(yPos) === axisId) {
                        anchors[axisId] = subplotId.slice(0, yPos);
                        break;
                    }
                }
            }
            else {
                for(i = i0; i !== iFinal; i += inc) {
                    xId = gridOut.xaxes[i];
                    if(subplots.cartesian.indexOf(xId + axisId) !== -1) {
                        anchors[axisId] = xId;
                        break;
                    }
                }
            }
        }
    }
}

function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) {
    var out = new Array(len);
    var i;

    function fillOneAxis(i, axisId) {
        if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) {
            out[i] = axisId;
            axisMap[axisId] = i;
        }
        else out[i] = '';
    }

    if(Array.isArray(axesIn)) {
        for(i = 0; i < len; i++) {
            fillOneAxis(i, axesIn[i]);
        }
    }
    else {
        // default axis list is the first `len` axis ids
        fillOneAxis(0, axLetter);
        for(i = 1; i < len; i++) {
            fillOneAxis(i, axLetter + (i + 1));
        }
    }

    return out;
}

module.exports = {
    moduleType: 'component',
    name: 'grid',

    schema: {
        layout: {grid: gridAttrs}
    },

    layoutAttributes: gridAttrs,
    sizeDefaults: sizeDefaults,
    contentDefaults: contentDefaults
};

},{"../../lib":164,"../../lib/regex":179,"../../plots/cartesian/constants":211,"../../plots/domain":231}],90:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var cartesianConstants = require('../../plots/cartesian/constants');


module.exports = {
    _isLinkedToArray: 'image',

    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'arraydraw',
        
    },

    source: {
        valType: 'string',
        
        editType: 'arraydraw',
        
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        
        editType: 'arraydraw',
        
    },

    sizex: {
        valType: 'number',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    sizey: {
        valType: 'number',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    sizing: {
        valType: 'enumerated',
        values: ['fill', 'contain', 'stretch'],
        dflt: 'contain',
        
        editType: 'arraydraw',
        
    },

    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'arraydraw',
        
    },

    x: {
        valType: 'any',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    y: {
        valType: 'any',
        
        dflt: 0,
        editType: 'arraydraw',
        
    },

    xanchor: {
        valType: 'enumerated',
        values: ['left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'arraydraw',
        
    },

    yanchor: {
        valType: 'enumerated',
        values: ['top', 'middle', 'bottom'],
        dflt: 'top',
        
        editType: 'arraydraw',
        
    },

    xref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.x.toString()
        ],
        dflt: 'paper',
        
        editType: 'arraydraw',
        
    },

    yref: {
        valType: 'enumerated',
        values: [
            'paper',
            cartesianConstants.idRegex.y.toString()
        ],
        dflt: 'paper',
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
};

},{"../../plots/cartesian/constants":211}],91:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var toLogRange = require('../../lib/to_log_range');

/*
 * convertCoords: when converting an axis between log and linear
 * you need to alter any images on that axis to keep them
 * pointing at the same data point.
 * In v2.0 this will become obsolete (or perhaps size will still need conversion?)
 * we convert size by declaring that the maximum extent *in data units* should be
 * the same, assuming the image is anchored by its center (could remove that restriction
 * if we think it's important) even though the actual left and right values will not be
 * quite the same since the scale becomes nonlinear (and central anchor means the pixel
 * center of the image, not the data units center)
 *
 * gd: the plot div
 * ax: the axis being changed
 * newType: the type it's getting
 * doExtra: function(attr, val) from inside relayout that sets the attribute.
 *     Use this to make the changes as it's aware if any other changes in the
 *     same relayout call should override this conversion.
 */
module.exports = function convertCoords(gd, ax, newType, doExtra) {
    ax = ax || {};

    var toLog = (newType === 'log') && (ax.type === 'linear'),
        fromLog = (newType === 'linear') && (ax.type === 'log');

    if(!(toLog || fromLog)) return;

    var images = gd._fullLayout.images,
        axLetter = ax._id.charAt(0),
        image,
        attrPrefix;

    for(var i = 0; i < images.length; i++) {
        image = images[i];
        attrPrefix = 'images[' + i + '].';

        if(image[axLetter + 'ref'] === ax._id) {
            var currentPos = image[axLetter],
                currentSize = image['size' + axLetter],
                newPos = null,
                newSize = null;

            if(toLog) {
                newPos = toLogRange(currentPos, ax.range);

                // this is the inverse of the conversion we do in fromLog below
                // so that the conversion is reversible (notice the fromLog conversion
                // is like sinh, and this one looks like arcsinh)
                var dx = currentSize / Math.pow(10, newPos) / 2;
                newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10;
            }
            else {
                newPos = Math.pow(10, currentPos);
                newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2));
            }

            // if conversion failed, delete the value so it can get a default later on
            if(!isNumeric(newPos)) {
                newPos = null;
                newSize = null;
            }
            else if(!isNumeric(newSize)) newSize = null;

            doExtra(attrPrefix + axLetter, newPos);
            doExtra(attrPrefix + 'size' + axLetter, newSize);
        }
    }
};

},{"../../lib/to_log_range":187,"fast-isnumeric":9}],92:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var handleArrayContainerDefaults = require('../../plots/array_container_defaults');

var attributes = require('./attributes');
var name = 'images';

module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: imageDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};


function imageDefaults(imageIn, imageOut, fullLayout) {

    function coerce(attr, dflt) {
        return Lib.coerce(imageIn, imageOut, attributes, attr, dflt);
    }

    var source = coerce('source');
    var visible = coerce('visible', !!source);

    if(!visible) return imageOut;

    coerce('layer');
    coerce('xanchor');
    coerce('yanchor');
    coerce('sizex');
    coerce('sizey');
    coerce('sizing');
    coerce('opacity');

    var gdMock = { _fullLayout: fullLayout },
        axLetters = ['x', 'y'];

    for(var i = 0; i < 2; i++) {
        // 'paper' is the fallback axref
        var axLetter = axLetters[i],
            axRef = Axes.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper');

        Axes.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0);
    }

    return imageOut;
}

},{"../../lib":164,"../../plots/array_container_defaults":202,"../../plots/cartesian/axes":206,"./attributes":90}],93:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');
var Drawing = require('../drawing');
var Axes = require('../../plots/cartesian/axes');
var xmlnsNamespaces = require('../../constants/xmlns_namespaces');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout,
        imageDataAbove = [],
        imageDataSubplot = {},
        imageDataBelow = [],
        subplot,
        i;

    // Sort into top, subplot, and bottom layers
    for(i = 0; i < fullLayout.images.length; i++) {
        var img = fullLayout.images[i];

        if(img.visible) {
            if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') {
                subplot = img.xref + img.yref;

                var plotinfo = fullLayout._plots[subplot];

                if(!plotinfo) {
                    // Fall back to _imageLowerLayer in case the requested subplot doesn't exist.
                    // This can happen if you reference the image to an x / y axis combination
                    // that doesn't have any data on it (and layer is below)
                    imageDataBelow.push(img);
                    continue;
                }

                if(plotinfo.mainplot) {
                    subplot = plotinfo.mainplot.id;
                }

                if(!imageDataSubplot[subplot]) {
                    imageDataSubplot[subplot] = [];
                }
                imageDataSubplot[subplot].push(img);
            } else if(img.layer === 'above') {
                imageDataAbove.push(img);
            } else {
                imageDataBelow.push(img);
            }
        }
    }


    var anchors = {
        x: {
            left: { sizing: 'xMin', offset: 0 },
            center: { sizing: 'xMid', offset: -1 / 2 },
            right: { sizing: 'xMax', offset: -1 }
        },
        y: {
            top: { sizing: 'YMin', offset: 0 },
            middle: { sizing: 'YMid', offset: -1 / 2 },
            bottom: { sizing: 'YMax', offset: -1 }
        }
    };


    // Images must be converted to dataURL's for exporting.
    function setImage(d) {
        var thisImage = d3.select(this);

        if(this.img && this.img.src === d.source) {
            return;
        }

        thisImage.attr('xmlns', xmlnsNamespaces.svg);

        var imagePromise = new Promise(function(resolve) {

            var img = new Image();
            this.img = img;

            // If not set, a `tainted canvas` error is thrown
            img.setAttribute('crossOrigin', 'anonymous');
            img.onerror = errorHandler;
            img.onload = function() {
                var canvas = document.createElement('canvas');
                canvas.width = this.width;
                canvas.height = this.height;

                var ctx = canvas.getContext('2d');
                ctx.drawImage(this, 0, 0);

                var dataURL = canvas.toDataURL('image/png');

                thisImage.attr('xlink:href', dataURL);

                // resolve promise in onload handler instead of on 'load' to support IE11
                // see https://github.com/plotly/plotly.js/issues/1685
                // for more details
                resolve();
            };


            thisImage.on('error', errorHandler);

            img.src = d.source;

            function errorHandler() {
                thisImage.remove();
                resolve();
            }
        }.bind(this));

        gd._promises.push(imagePromise);
    }

    function applyAttributes(d) {
        var thisImage = d3.select(this);

        // Axes if specified
        var xa = Axes.getFromId(gd, d.xref),
            ya = Axes.getFromId(gd, d.yref);

        var size = fullLayout._size,
            width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w,
            height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h;

        // Offsets for anchor positioning
        var xOffset = width * anchors.x[d.xanchor].offset,
            yOffset = height * anchors.y[d.yanchor].offset;

        var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing;

        // Final positions
        var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset,
            yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset;


        // Construct the proper aspectRatio attribute
        switch(d.sizing) {
            case 'fill':
                sizing += ' slice';
                break;

            case 'stretch':
                sizing = 'none';
                break;
        }

        thisImage.attr({
            x: xPos,
            y: yPos,
            width: width,
            height: height,
            preserveAspectRatio: sizing,
            opacity: d.opacity
        });


        // Set proper clipping on images
        var xId = xa ? xa._id : '',
            yId = ya ? ya._id : '',
            clipAxes = xId + yId;

        thisImage.call(Drawing.setClipUrl, clipAxes ?
            ('clip' + fullLayout._uid + clipAxes) :
            null
        );
    }

    var imagesBelow = fullLayout._imageLowerLayer.selectAll('image')
            .data(imageDataBelow),
        imagesAbove = fullLayout._imageUpperLayer.selectAll('image')
            .data(imageDataAbove);

    imagesBelow.enter().append('image');
    imagesAbove.enter().append('image');

    imagesBelow.exit().remove();
    imagesAbove.exit().remove();

    imagesBelow.each(function(d) {
        setImage.bind(this)(d);
        applyAttributes.bind(this)(d);
    });
    imagesAbove.each(function(d) {
        setImage.bind(this)(d);
        applyAttributes.bind(this)(d);
    });

    var allSubplots = Object.keys(fullLayout._plots);
    for(i = 0; i < allSubplots.length; i++) {
        subplot = allSubplots[i];
        var subplotObj = fullLayout._plots[subplot];

        // filter out overlaid plots (which havd their images on the main plot)
        // and gl2d plots (which don't support below images, at least not yet)
        if(!subplotObj.imagelayer) continue;

        var imagesOnSubplot = subplotObj.imagelayer.selectAll('image')
            // even if there are no images on this subplot, we need to run
            // enter and exit in case there were previously
            .data(imageDataSubplot[subplot] || []);

        imagesOnSubplot.enter().append('image');
        imagesOnSubplot.exit().remove();

        imagesOnSubplot.each(function(d) {
            setImage.bind(this)(d);
            applyAttributes.bind(this)(d);
        });
    }
};

},{"../../constants/xmlns_namespaces":147,"../../plots/cartesian/axes":206,"../drawing":68,"d3":6}],94:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'component',
    name: 'images',

    layoutAttributes: require('./attributes'),
    supplyLayoutDefaults: require('./defaults'),
    includeBasePlot: require('../../plots/cartesian/include_components')('images'),

    draw: require('./draw'),

    convertCoords: require('./convert_coords')
};

},{"../../plots/cartesian/include_components":216,"./attributes":90,"./convert_coords":91,"./defaults":92,"./draw":93}],95:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Determine the position anchor property of x/y xanchor/yanchor components.
 *
 * - values < 1/3 align the low side at that fraction,
 * - values [1/3, 2/3] align the center at that fraction,
 * - values > 2/3 align the right at that fraction.
 */

exports.isRightAnchor = function isRightAnchor(opts) {
    return (
        opts.xanchor === 'right' ||
        (opts.xanchor === 'auto' && opts.x >= 2 / 3)
    );
};

exports.isCenterAnchor = function isCenterAnchor(opts) {
    return (
        opts.xanchor === 'center' ||
        (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3)
    );
};

exports.isBottomAnchor = function isBottomAnchor(opts) {
    return (
        opts.yanchor === 'bottom' ||
        (opts.yanchor === 'auto' && opts.y <= 1 / 3)
    );
};

exports.isMiddleAnchor = function isMiddleAnchor(opts) {
    return (
        opts.yanchor === 'middle' ||
        (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3)
    );
};

},{}],96:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('../../plots/font_attributes');
var colorAttrs = require('../color/attributes');


module.exports = {
    bgcolor: {
        valType: 'color',
        
        editType: 'legend',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'legend',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'legend',
        
    },
    font: fontAttrs({
        editType: 'legend',
        
    }),
    orientation: {
        valType: 'enumerated',
        values: ['v', 'h'],
        dflt: 'v',
        
        editType: 'legend',
        
    },
    traceorder: {
        valType: 'flaglist',
        flags: ['reversed', 'grouped'],
        extras: ['normal'],
        
        editType: 'legend',
        
    },
    tracegroupgap: {
        valType: 'number',
        min: 0,
        dflt: 10,
        
        editType: 'legend',
        
    },
    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1.02,
        
        editType: 'legend',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'legend',
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1,
        
        editType: 'legend',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'auto',
        
        editType: 'legend',
        
    },
    editType: 'legend'
};

},{"../../plots/font_attributes":232,"../color/attributes":42}],97:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    scrollBarWidth: 6,
    scrollBarMinHeight: 20,
    scrollBarColor: '#808BA4',
    scrollBarMargin: 4
};

},{}],98:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');

var attributes = require('./attributes');
var basePlotLayoutAttributes = require('../../plots/layout_attributes');
var helpers = require('./helpers');


module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
    var containerIn = layoutIn.legend || {};
    var containerOut = {};

    var visibleTraces = 0;
    var defaultOrder = 'normal';

    var defaultX, defaultY, defaultXAnchor, defaultYAnchor;

    for(var i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(helpers.legendGetsTrace(trace)) {
            visibleTraces++;
            // always show the legend by default if there's a pie
            if(Registry.traceIs(trace, 'pie')) visibleTraces++;
        }

        if((Registry.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') ||
                ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) {
            defaultOrder = helpers.isGrouped({traceorder: defaultOrder}) ?
                'grouped+reversed' : 'reversed';
        }

        if(trace.legendgroup !== undefined && trace.legendgroup !== '') {
            defaultOrder = helpers.isReversed({traceorder: defaultOrder}) ?
                'reversed+grouped' : 'grouped';
        }
    }

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    var showLegend = Lib.coerce(layoutIn, layoutOut,
        basePlotLayoutAttributes, 'showlegend', visibleTraces > 1);

    if(showLegend === false) return;

    layoutOut.legend = containerOut;

    coerce('bgcolor', layoutOut.paper_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
    Lib.coerceFont(coerce, 'font', layoutOut.font);

    coerce('orientation');
    if(containerOut.orientation === 'h') {
        var xaxis = layoutIn.xaxis;
        if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) {
            defaultX = 0;
            defaultXAnchor = 'left';
            defaultY = 1.1;
            defaultYAnchor = 'bottom';
        }
        else {
            defaultX = 0;
            defaultXAnchor = 'left';
            defaultY = -0.1;
            defaultYAnchor = 'top';
        }
    }

    coerce('traceorder', defaultOrder);
    if(helpers.isGrouped(layoutOut.legend)) coerce('tracegroupgap');

    coerce('x', defaultX);
    coerce('xanchor', defaultXAnchor);
    coerce('y', defaultY);
    coerce('yanchor', defaultYAnchor);
    Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
};

},{"../../lib":164,"../../plots/layout_attributes":236,"../../registry":254,"./attributes":96,"./helpers":102}],99:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Lib = require('../../lib');
var Plots = require('../../plots/plots');
var Registry = require('../../registry');
var Events = require('../../lib/events');
var dragElement = require('../dragelement');
var Drawing = require('../drawing');
var Color = require('../color');
var svgTextUtils = require('../../lib/svg_text_utils');
var handleClick = require('./handle_click');

var constants = require('./constants');
var interactConstants = require('../../constants/interactions');
var alignmentConstants = require('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var getLegendData = require('./get_legend_data');
var style = require('./style');
var helpers = require('./helpers');
var anchorUtils = require('./anchor_utils');

var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;
    var clipId = 'legend' + fullLayout._uid;

    if(!fullLayout._infolayer || !gd.calcdata) return;

    if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0;

    var opts = fullLayout.legend;
    var legendData = fullLayout.showlegend && getLegendData(gd.calcdata, opts);
    var hiddenSlices = fullLayout.hiddenlabels || [];

    if(!fullLayout.showlegend || !legendData.length) {
        fullLayout._infolayer.selectAll('.legend').remove();
        fullLayout._topdefs.select('#' + clipId).remove();

        Plots.autoMargin(gd, 'legend');
        return;
    }

    var maxLength = 0;
    for(var i = 0; i < legendData.length; i++) {
        for(var j = 0; j < legendData[i].length; j++) {
            var item = legendData[i][j][0];
            var trace = item.trace;
            var isPie = Registry.traceIs(trace, 'pie');
            var name = isPie ? item.label : trace.name;
            maxLength = Math.max(maxLength, name && name.length || 0);
        }
    }

    var firstRender = false;
    var legend = Lib.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) {
        s.attr('pointer-events', 'all');
        firstRender = true;
    });

    var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) {
        s.append('rect');
    });

    var bg = Lib.ensureSingle(legend, 'rect', 'bg', function(s) {
        s.attr('shape-rendering', 'crispEdges');
    });

    bg.call(Color.stroke, opts.bordercolor)
        .call(Color.fill, opts.bgcolor)
        .style('stroke-width', opts.borderwidth + 'px');

    var scrollBox = Lib.ensureSingle(legend, 'g', 'scrollbox');

    var scrollBar = Lib.ensureSingle(legend, 'rect', 'scrollbar', function(s) {
        s.attr({
            rx: 20,
            ry: 3,
            width: 0,
            height: 0
        })
        .call(Color.fill, '#808BA4');
    });

    var groups = scrollBox.selectAll('g.groups')
        .data(legendData);

    groups.enter().append('g')
        .attr('class', 'groups');

    groups.exit().remove();

    var traces = groups.selectAll('g.traces')
        .data(Lib.identity);

    traces.enter().append('g').attr('class', 'traces');
    traces.exit().remove();

    traces.call(style, gd)
        .style('opacity', function(d) {
            var trace = d[0].trace;
            if(Registry.traceIs(trace, 'pie')) {
                return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
            } else {
                return trace.visible === 'legendonly' ? 0.5 : 1;
            }
        })
        .each(function() {
            d3.select(this)
                .call(drawTexts, gd, maxLength)
                .call(setupTraceToggle, gd);
        });

    if(firstRender) {
        computeLegendDimensions(gd, groups, traces);
        expandMargin(gd);
    }

    // Position and size the legend
    var lxMin = 0,
        lxMax = fullLayout.width,
        lyMin = 0,
        lyMax = fullLayout.height;

    computeLegendDimensions(gd, groups, traces);

    if(opts._height > lyMax) {
        // If the legend doesn't fit in the plot area,
        // do not expand the vertical margins.
        expandHorizontalMargin(gd);
    } else {
        expandMargin(gd);
    }

    // Scroll section must be executed after repositionLegend.
    // It requires the legend width, height, x and y to position the scrollbox
    // and these values are mutated in repositionLegend.
    var gs = fullLayout._size,
        lx = gs.l + gs.w * opts.x,
        ly = gs.t + gs.h * (1 - opts.y);

    if(anchorUtils.isRightAnchor(opts)) {
        lx -= opts._width;
    }
    else if(anchorUtils.isCenterAnchor(opts)) {
        lx -= opts._width / 2;
    }

    if(anchorUtils.isBottomAnchor(opts)) {
        ly -= opts._height;
    }
    else if(anchorUtils.isMiddleAnchor(opts)) {
        ly -= opts._height / 2;
    }

    // Make sure the legend left and right sides are visible
    var legendWidth = opts._width,
        legendWidthMax = gs.w;

    if(legendWidth > legendWidthMax) {
        lx = gs.l;
        legendWidth = legendWidthMax;
    }
    else {
        if(lx + legendWidth > lxMax) lx = lxMax - legendWidth;
        if(lx < lxMin) lx = lxMin;
        legendWidth = Math.min(lxMax - lx, opts._width);
    }

    // Make sure the legend top and bottom are visible
    // (legends with a scroll bar are not allowed to stretch beyond the extended
    // margins)
    var legendHeight = opts._height,
        legendHeightMax = gs.h;

    if(legendHeight > legendHeightMax) {
        ly = gs.t;
        legendHeight = legendHeightMax;
    }
    else {
        if(ly + legendHeight > lyMax) ly = lyMax - legendHeight;
        if(ly < lyMin) ly = lyMin;
        legendHeight = Math.min(lyMax - ly, opts._height);
    }

    // Set size and position of all the elements that make up a legend:
    // legend, background and border, scroll box and scroll bar
    Drawing.setTranslate(legend, lx, ly);

    // to be safe, remove previous listeners
    scrollBar.on('.drag', null);
    legend.on('wheel', null);

    if(opts._height <= legendHeight || gd._context.staticPlot) {
        // if scrollbar should not be shown.
        bg.attr({
            width: legendWidth - opts.borderwidth,
            height: legendHeight - opts.borderwidth,
            x: opts.borderwidth / 2,
            y: opts.borderwidth / 2
        });

        Drawing.setTranslate(scrollBox, 0, 0);

        clipPath.select('rect').attr({
            width: legendWidth - 2 * opts.borderwidth,
            height: legendHeight - 2 * opts.borderwidth,
            x: opts.borderwidth,
            y: opts.borderwidth
        });

        Drawing.setClipUrl(scrollBox, clipId);

        Drawing.setRect(scrollBar, 0, 0, 0, 0);
        delete opts._scrollY;
    }
    else {
        var scrollBarHeight = Math.max(constants.scrollBarMinHeight,
            legendHeight * legendHeight / opts._height);
        var scrollBarYMax = legendHeight -
            scrollBarHeight -
            2 * constants.scrollBarMargin;
        var scrollBoxYMax = opts._height - legendHeight;
        var scrollRatio = scrollBarYMax / scrollBoxYMax;

        var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax);

        // increase the background and clip-path width
        // by the scrollbar width and margin
        bg.attr({
            width: legendWidth -
                2 * opts.borderwidth +
                constants.scrollBarWidth +
                constants.scrollBarMargin,
            height: legendHeight - opts.borderwidth,
            x: opts.borderwidth / 2,
            y: opts.borderwidth / 2
        });

        clipPath.select('rect').attr({
            width: legendWidth -
                2 * opts.borderwidth +
                constants.scrollBarWidth +
                constants.scrollBarMargin,
            height: legendHeight - 2 * opts.borderwidth,
            x: opts.borderwidth,
            y: opts.borderwidth + scrollBoxY
        });

        Drawing.setClipUrl(scrollBox, clipId);

        scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);

        legend.on('wheel', function() {
            scrollBoxY = Lib.constrain(
                opts._scrollY +
                    d3.event.deltaY / scrollBarYMax * scrollBoxYMax,
                0, scrollBoxYMax);
            scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
            if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) {
                d3.event.preventDefault();
            }
        });

        var eventY0, scrollBoxY0;

        var drag = d3.behavior.drag()
        .on('dragstart', function() {
            eventY0 = d3.event.sourceEvent.clientY;
            scrollBoxY0 = scrollBoxY;
        })
        .on('drag', function() {
            var e = d3.event.sourceEvent;
            if(e.buttons === 2 || e.ctrlKey) return;

            scrollBoxY = Lib.constrain(
                (e.clientY - eventY0) / scrollRatio + scrollBoxY0,
                0, scrollBoxYMax);
            scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
        });

        scrollBar.call(drag);
    }


    function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) {
        opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY;
        Drawing.setTranslate(scrollBox, 0, -scrollBoxY);

        Drawing.setRect(
            scrollBar,
            legendWidth,
            constants.scrollBarMargin + scrollBoxY * scrollRatio,
            constants.scrollBarWidth,
            scrollBarHeight
        );
        clipPath.select('rect').attr({
            y: opts.borderwidth + scrollBoxY
        });
    }

    if(gd._context.edits.legendPosition) {
        var xf, yf, x0, y0;

        legend.classed('cursor-move', true);

        dragElement.init({
            element: legend.node(),
            gd: gd,
            prepFn: function() {
                var transform = Drawing.getTranslate(legend);

                x0 = transform.x;
                y0 = transform.y;
            },
            moveFn: function(dx, dy) {
                var newX = x0 + dx,
                    newY = y0 + dy;

                Drawing.setTranslate(legend, newX, newY);

                xf = dragElement.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor);
                yf = dragElement.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor);
            },
            doneFn: function() {
                if(xf !== undefined && yf !== undefined) {
                    Registry.call('relayout', gd, {'legend.x': xf, 'legend.y': yf});
                }
            },
            clickFn: function(numClicks, e) {
                var clickedTrace =
                    fullLayout._infolayer.selectAll('g.traces').filter(function() {
                        var bbox = this.getBoundingClientRect();
                        return (e.clientX >= bbox.left && e.clientX <= bbox.right &&
                            e.clientY >= bbox.top && e.clientY <= bbox.bottom);
                    });
                if(clickedTrace.size() > 0) {
                    clickOrDoubleClick(gd, legend, clickedTrace, numClicks, e);
                }
            }
        });
    }
};

function clickOrDoubleClick(gd, legend, legendItem, numClicks, evt) {
    var trace = legendItem.data()[0][0].trace;

    var evtData = {
        event: evt,
        node: legendItem.node(),
        curveNumber: trace.index,
        expandedIndex: trace._expandedIndex,
        data: gd.data,
        layout: gd.layout,
        frames: gd._transitionData._frames,
        config: gd._context,
        fullData: gd._fullData,
        fullLayout: gd._fullLayout
    };

    if(trace._group) {
        evtData.group = trace._group;
    }
    if(trace.type === 'pie') {
        evtData.label = legendItem.datum()[0].label;
    }

    var clickVal = Events.triggerHandler(gd, 'plotly_legendclick', evtData);
    if(clickVal === false) return;

    if(numClicks === 1) {
        legend._clickTimeout = setTimeout(function() {
            handleClick(legendItem, gd, numClicks);
        }, DBLCLICKDELAY);
    }
    else if(numClicks === 2) {
        if(legend._clickTimeout) clearTimeout(legend._clickTimeout);
        gd._legendMouseDownTime = 0;

        var dblClickVal = Events.triggerHandler(gd, 'plotly_legenddoubleclick', evtData);
        if(dblClickVal !== false) handleClick(legendItem, gd, numClicks);
    }
}

function drawTexts(g, gd, maxLength) {
    var legendItem = g.data()[0][0];
    var fullLayout = gd._fullLayout;
    var trace = legendItem.trace;
    var isPie = Registry.traceIs(trace, 'pie');
    var traceIndex = trace.index;
    var name = isPie ? legendItem.label : trace.name;
    var isEditable = gd._context.edits.legendText && !isPie;

    var textEl = Lib.ensureSingle(g, 'text', 'legendtext');

    textEl.attr('text-anchor', 'start')
        .classed('user-select-none', true)
        .call(Drawing.font, fullLayout.legend.font)
        .text(isEditable ? ensureLength(name, maxLength) : name);

    function textLayout(s) {
        svgTextUtils.convertToTspans(s, gd, function() {
            computeTextDimensions(g, gd);
        });
    }

    if(isEditable) {
        textEl.call(svgTextUtils.makeEditable, {gd: gd, text: name})
            .call(textLayout)
            .on('edit', function(newName) {
                this.text(ensureLength(newName, maxLength))
                    .call(textLayout);

                var fullInput = legendItem.trace._fullInput || {};
                var update = {};

                if(Registry.hasTransform(fullInput, 'groupby')) {
                    var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
                    var index = groupbyIndices[groupbyIndices.length - 1];

                    var kcont = Lib.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name');

                    kcont.set(legendItem.trace._group, newName);

                    update = kcont.constructUpdate();
                } else {
                    update.name = newName;
                }

                return Registry.call('restyle', gd, update, traceIndex);
            });
    } else {
        textLayout(textEl);
    }
}

/*
 * Make sure we have a reasonably clickable region.
 * If this string is missing or very short, pad it with spaces out to at least
 * 4 characters, up to the max length of other labels, on the assumption that
 * most characters are wider than spaces so a string of spaces will usually be
 * no wider than the real labels.
 */
function ensureLength(str, maxLength) {
    var targetLength = Math.max(4, maxLength);
    if(str && str.trim().length >= targetLength / 2) return str;
    str = str || '';
    for(var i = targetLength - str.length; i > 0; i--) str += ' ';
    return str;
}

function setupTraceToggle(g, gd) {
    var newMouseDownTime,
        numClicks = 1;

    var traceToggle = Lib.ensureSingle(g, 'rect', 'legendtoggle', function(s) {
        s.style('cursor', 'pointer')
            .attr('pointer-events', 'all')
            .call(Color.fill, 'rgba(0,0,0,0)');
    });

    traceToggle.on('mousedown', function() {
        newMouseDownTime = (new Date()).getTime();
        if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) {
            // in a click train
            numClicks += 1;
        }
        else {
            // new click train
            numClicks = 1;
            gd._legendMouseDownTime = newMouseDownTime;
        }
    });
    traceToggle.on('mouseup', function() {
        if(gd._dragged || gd._editing) return;
        var legend = gd._fullLayout.legend;

        if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) {
            numClicks = Math.max(numClicks - 1, 1);
        }

        clickOrDoubleClick(gd, legend, g, numClicks, d3.event);
    });
}

function computeTextDimensions(g, gd) {
    var legendItem = g.data()[0][0];

    if(!legendItem.trace.showlegend) {
        g.remove();
        return;
    }

    var mathjaxGroup = g.select('g[class*=math-group]');
    var mathjaxNode = mathjaxGroup.node();
    var opts = gd._fullLayout.legend;
    var lineHeight = opts.font.size * LINE_SPACING;
    var height, width;

    if(mathjaxNode) {
        var mathjaxBB = Drawing.bBox(mathjaxNode);

        height = mathjaxBB.height;
        width = mathjaxBB.width;

        Drawing.setTranslate(mathjaxGroup, 0, (height / 4));
    }
    else {
        var text = g.select('.legendtext');
        var textLines = svgTextUtils.lineCount(text);
        var textNode = text.node();

        height = lineHeight * textLines;
        width = textNode ? Drawing.bBox(textNode).width : 0;

        // approximation to height offset to center the font
        // to avoid getBoundingClientRect
        var textY = lineHeight * (0.3 + (1 - textLines) / 2);
        // TODO: this 40 should go in a constants file (along with other
        // values related to the legend symbol size)
        svgTextUtils.positionText(text, 40, textY);
    }

    height = Math.max(height, 16) + 3;

    legendItem.height = height;
    legendItem.width = width;
}

function computeLegendDimensions(gd, groups, traces) {
    var fullLayout = gd._fullLayout;
    var opts = fullLayout.legend;
    var borderwidth = opts.borderwidth;
    var isGrouped = helpers.isGrouped(opts);

    var extraWidth = 0;

    opts._width = 0;
    opts._height = 0;

    if(helpers.isVertical(opts)) {
        if(isGrouped) {
            groups.each(function(d, i) {
                Drawing.setTranslate(this, 0, i * opts.tracegroupgap);
            });
        }

        traces.each(function(d) {
            var legendItem = d[0],
                textHeight = legendItem.height,
                textWidth = legendItem.width;

            Drawing.setTranslate(this,
                borderwidth,
                (5 + borderwidth + opts._height + textHeight / 2));

            opts._height += textHeight;
            opts._width = Math.max(opts._width, textWidth);
        });

        opts._width += 45 + borderwidth * 2;
        opts._height += 10 + borderwidth * 2;

        if(isGrouped) {
            opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap;
        }

        extraWidth = 40;
    }
    else if(isGrouped) {
        var groupXOffsets = [opts._width],
            groupData = groups.data();

        for(var i = 0, n = groupData.length; i < n; i++) {
            var textWidths = groupData[i].map(function(legendItemArray) {
                return legendItemArray[0].width;
            });

            var groupWidth = 40 + Math.max.apply(null, textWidths);

            opts._width += opts.tracegroupgap + groupWidth;

            groupXOffsets.push(opts._width);
        }

        groups.each(function(d, i) {
            Drawing.setTranslate(this, groupXOffsets[i], 0);
        });

        groups.each(function() {
            var group = d3.select(this),
                groupTraces = group.selectAll('g.traces'),
                groupHeight = 0;

            groupTraces.each(function(d) {
                var legendItem = d[0],
                    textHeight = legendItem.height;

                Drawing.setTranslate(this,
                    0,
                    (5 + borderwidth + groupHeight + textHeight / 2));

                groupHeight += textHeight;
            });

            opts._height = Math.max(opts._height, groupHeight);
        });

        opts._height += 10 + borderwidth * 2;
        opts._width += borderwidth * 2;
    }
    else {
        var rowHeight = 0,
            maxTraceHeight = 0,
            maxTraceWidth = 0,
            offsetX = 0,
            fullTracesWidth = 0,
            traceGap = opts.tracegroupgap || 5,
            oneRowLegend;

        // calculate largest width for traces and use for width of all legend items
        traces.each(function(d) {
            maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth);
            fullTracesWidth += 40 + d[0].width + traceGap;
        });

        // check if legend fits in one row
        oneRowLegend = (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l)) > borderwidth + fullTracesWidth - traceGap;
        traces.each(function(d) {
            var legendItem = d[0],
                traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth;

            if((borderwidth + offsetX + traceGap + traceWidth) > (fullLayout.width - (fullLayout.margin.r + fullLayout.margin.l))) {
                offsetX = 0;
                rowHeight = rowHeight + maxTraceHeight;
                opts._height = opts._height + maxTraceHeight;
                // reset for next row
                maxTraceHeight = 0;
            }

            Drawing.setTranslate(this,
                (borderwidth + offsetX),
                (5 + borderwidth + legendItem.height / 2) + rowHeight);

            opts._width += traceGap + traceWidth;
            opts._height = Math.max(opts._height, legendItem.height);

            // keep track of tallest trace in group
            offsetX += traceGap + traceWidth;
            maxTraceHeight = Math.max(legendItem.height, maxTraceHeight);
        });

        opts._width += borderwidth * 2;
        opts._height += 10 + borderwidth * 2;

    }

    // make sure we're only getting full pixels
    opts._width = Math.ceil(opts._width);
    opts._height = Math.ceil(opts._height);

    traces.each(function(d) {
        var legendItem = d[0],
            bg = d3.select(this).select('.legendtoggle');

        Drawing.setRect(bg,
            0,
            -legendItem.height / 2,
            (gd._context.edits.legendText ? 0 : opts._width) + extraWidth,
            legendItem.height
        );
    });
}

function expandMargin(gd) {
    var fullLayout = gd._fullLayout,
        opts = fullLayout.legend;

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(opts)) {
        xanchor = 'right';
    }
    else if(anchorUtils.isCenterAnchor(opts)) {
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(anchorUtils.isBottomAnchor(opts)) {
        yanchor = 'bottom';
    }
    else if(anchorUtils.isMiddleAnchor(opts)) {
        yanchor = 'middle';
    }

    // lastly check if the margin auto-expand has changed
    Plots.autoMargin(gd, 'legend', {
        x: opts.x,
        y: opts.y,
        l: opts._width * (FROM_TL[xanchor]),
        r: opts._width * (FROM_BR[xanchor]),
        b: opts._height * (FROM_BR[yanchor]),
        t: opts._height * (FROM_TL[yanchor])
    });
}

function expandHorizontalMargin(gd) {
    var fullLayout = gd._fullLayout,
        opts = fullLayout.legend;

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(opts)) {
        xanchor = 'right';
    }
    else if(anchorUtils.isCenterAnchor(opts)) {
        xanchor = 'center';
    }

    // lastly check if the margin auto-expand has changed
    Plots.autoMargin(gd, 'legend', {
        x: opts.x,
        y: 0.5,
        l: opts._width * (FROM_TL[xanchor]),
        r: opts._width * (FROM_BR[xanchor]),
        b: 0,
        t: 0
    });
}

},{"../../constants/alignment":143,"../../constants/interactions":144,"../../lib":164,"../../lib/events":156,"../../lib/svg_text_utils":185,"../../plots/plots":245,"../../registry":254,"../color":43,"../dragelement":65,"../drawing":68,"./anchor_utils":95,"./constants":97,"./get_legend_data":100,"./handle_click":101,"./helpers":102,"./style":104,"d3":6}],100:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var helpers = require('./helpers');


module.exports = function getLegendData(calcdata, opts) {
    var lgroupToTraces = {},
        lgroups = [],
        hasOneNonBlankGroup = false,
        slicesShown = {},
        lgroupi = 0;

    var i, j;

    function addOneItem(legendGroup, legendItem) {
        // each '' legend group is treated as a separate group
        if(legendGroup === '' || !helpers.isGrouped(opts)) {
            var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups?

            lgroups.push(uniqueGroup);
            lgroupToTraces[uniqueGroup] = [[legendItem]];
            lgroupi++;
        }
        else if(lgroups.indexOf(legendGroup) === -1) {
            lgroups.push(legendGroup);
            hasOneNonBlankGroup = true;
            lgroupToTraces[legendGroup] = [[legendItem]];
        }
        else lgroupToTraces[legendGroup].push([legendItem]);
    }

    // build an { legendgroup: [cd0, cd0], ... } object
    for(i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i],
            cd0 = cd[0],
            trace = cd0.trace,
            lgroup = trace.legendgroup;

        if(!helpers.legendGetsTrace(trace) || !trace.showlegend) continue;

        if(Registry.traceIs(trace, 'pie')) {
            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};

            for(j = 0; j < cd.length; j++) {
                var labelj = cd[j].label;

                if(!slicesShown[lgroup][labelj]) {
                    addOneItem(lgroup, {
                        label: labelj,
                        color: cd[j].color,
                        i: cd[j].i,
                        trace: trace
                    });

                    slicesShown[lgroup][labelj] = true;
                }
            }
        }

        else addOneItem(lgroup, cd0);
    }

    // won't draw a legend in this case
    if(!lgroups.length) return [];

    // rearrange lgroupToTraces into a d3-friendly array of arrays
    var lgroupsLength = lgroups.length,
        ltraces,
        legendData;

    if(hasOneNonBlankGroup && helpers.isGrouped(opts)) {
        legendData = new Array(lgroupsLength);

        for(i = 0; i < lgroupsLength; i++) {
            ltraces = lgroupToTraces[lgroups[i]];
            legendData[i] = helpers.isReversed(opts) ? ltraces.reverse() : ltraces;
        }
    }
    else {
        // collapse all groups into one if all groups are blank
        legendData = [new Array(lgroupsLength)];

        for(i = 0; i < lgroupsLength; i++) {
            ltraces = lgroupToTraces[lgroups[i]][0];
            legendData[0][helpers.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces;
        }
        lgroupsLength = 1;
    }

    // needed in repositionLegend
    opts._lgroupsLength = lgroupsLength;
    return legendData;
};

},{"../../registry":254,"./helpers":102}],101:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Registry = require('../../registry');

var SHOWISOLATETIP = true;

module.exports = function handleClick(g, gd, numClicks) {
    if(gd._dragged || gd._editing) return;

    var hiddenSlices = gd._fullLayout.hiddenlabels ?
        gd._fullLayout.hiddenlabels.slice() :
        [];

    var legendItem = g.data()[0][0];
    var fullData = gd._fullData;
    var fullTrace = legendItem.trace;
    var legendgroup = fullTrace.legendgroup;

    var i, j, kcont, key, keys, val;
    var attrUpdate = {};
    var attrIndices = [];
    var carrs = [];
    var carrIdx = [];

    function insertUpdate(traceIndex, key, value) {
        var attrIndex = attrIndices.indexOf(traceIndex);
        var valueArray = attrUpdate[key];
        if(!valueArray) {
            valueArray = attrUpdate[key] = [];
        }

        if(attrIndices.indexOf(traceIndex) === -1) {
            attrIndices.push(traceIndex);
            attrIndex = attrIndices.length - 1;
        }

        valueArray[attrIndex] = value;

        return attrIndex;
    }

    function setVisibility(fullTrace, visibility) {
        var fullInput = fullTrace._fullInput;
        if(Registry.hasTransform(fullInput, 'groupby')) {
            var kcont = carrs[fullInput.index];
            if(!kcont) {
                var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
                var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1];
                kcont = Lib.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible');
                carrs[fullInput.index] = kcont;
            }

            var curState = kcont.get(fullTrace._group);

            // If not specified, assume visible. This happens if there are other style
            // properties set for a group but not the visibility. There are many similar
            // ways to do this (e.g. why not just `curState = fullTrace.visible`??? The
            // answer is: because it breaks other things like groupby trace names in
            // subtle ways.)
            if(curState === undefined) {
                curState = true;
            }

            if(curState !== false) {
                // true -> legendonly. All others toggle to true:
                kcont.set(fullTrace._group, visibility);
            }
            carrIdx[fullInput.index] = insertUpdate(fullInput.index, 'visible', fullInput.visible === false ? false : true);
        } else {
            // false -> false (not possible since will not be visible in legend)
            // true -> legendonly
            // legendonly -> true
            var nextVisibility = fullInput.visible === false ? false : visibility;

            insertUpdate(fullInput.index, 'visible', nextVisibility);
        }
    }

    if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) {
        Lib.notifier(Lib._(gd, 'Double-click on legend to isolate one trace'), 'long');
        SHOWISOLATETIP = false;
    } else {
        SHOWISOLATETIP = false;
    }

    if(Registry.traceIs(fullTrace, 'pie')) {
        var thisLabel = legendItem.label,
            thisLabelIndex = hiddenSlices.indexOf(thisLabel);

        if(numClicks === 1) {
            if(thisLabelIndex === -1) hiddenSlices.push(thisLabel);
            else hiddenSlices.splice(thisLabelIndex, 1);
        } else if(numClicks === 2) {
            hiddenSlices = [];
            gd.calcdata[0].forEach(function(d) {
                if(thisLabel !== d.label) {
                    hiddenSlices.push(d.label);
                }
            });
            if(gd._fullLayout.hiddenlabels && gd._fullLayout.hiddenlabels.length === hiddenSlices.length && thisLabelIndex === -1) {
                hiddenSlices = [];
            }
        }

        Registry.call('relayout', gd, 'hiddenlabels', hiddenSlices);
    } else {
        var hasLegendgroup = legendgroup && legendgroup.length;
        var traceIndicesInGroup = [];
        var tracei;
        if(hasLegendgroup) {
            for(i = 0; i < fullData.length; i++) {
                tracei = fullData[i];
                if(!tracei.visible) continue;
                if(tracei.legendgroup === legendgroup) {
                    traceIndicesInGroup.push(i);
                }
            }
        }

        if(numClicks === 1) {
            var nextVisibility;

            switch(fullTrace.visible) {
                case true:
                    nextVisibility = 'legendonly';
                    break;
                case false:
                    nextVisibility = false;
                    break;
                case 'legendonly':
                    nextVisibility = true;
                    break;
            }

            if(hasLegendgroup) {
                for(i = 0; i < fullData.length; i++) {
                    if(fullData[i].visible !== false && fullData[i].legendgroup === legendgroup) {
                        setVisibility(fullData[i], nextVisibility);
                    }
                }
            } else {
                setVisibility(fullTrace, nextVisibility);
            }
        } else if(numClicks === 2) {
            // Compute the clicked index. expandedIndex does what we want for expanded traces
            // but also culls hidden traces. That means we have some work to do.
            var isClicked, isInGroup, otherState;
            var isIsolated = true;
            for(i = 0; i < fullData.length; i++) {
                isClicked = fullData[i] === fullTrace;
                if(isClicked) continue;

                isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup);

                if(!isInGroup && fullData[i].visible === true && !Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
                    isIsolated = false;
                    break;
                }
            }

            for(i = 0; i < fullData.length; i++) {
                // False is sticky; we don't change it.
                if(fullData[i].visible === false) continue;

                if(Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
                    continue;
                }

                switch(fullTrace.visible) {
                    case 'legendonly':
                        setVisibility(fullData[i], true);
                        break;
                    case true:
                        otherState = isIsolated ? true : 'legendonly';
                        isClicked = fullData[i] === fullTrace;
                        isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup);
                        setVisibility(fullData[i], isInGroup ? true : otherState);
                        break;
                }
            }
        }

        for(i = 0; i < carrs.length; i++) {
            kcont = carrs[i];
            if(!kcont) continue;
            var update = kcont.constructUpdate();

            var updateKeys = Object.keys(update);
            for(j = 0; j < updateKeys.length; j++) {
                key = updateKeys[j];
                val = attrUpdate[key] = attrUpdate[key] || [];
                val[carrIdx[i]] = update[key];
            }
        }

        // The length of the value arrays should be equal and any unspecified
        // values should be explicitly undefined for them to get properly culled
        // as updates and not accidentally reset to the default value. This fills
        // out sparse arrays with the required number of undefined values:
        keys = Object.keys(attrUpdate);
        for(i = 0; i < keys.length; i++) {
            key = keys[i];
            for(j = 0; j < attrIndices.length; j++) {
                // Use hasOwnPropety to protect against falsey values:
                if(!attrUpdate[key].hasOwnProperty(j)) {
                    attrUpdate[key][j] = undefined;
                }
            }
        }

        Registry.call('restyle', gd, attrUpdate, attrIndices);
    }
};

},{"../../lib":164,"../../registry":254}],102:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.legendGetsTrace = function legendGetsTrace(trace) {
    // traceIs(trace, 'showLegend') is not sufficient anymore, due to contour(carpet)?
    // which are legend-eligible only if type: constraint. Otherwise, showlegend gets deleted.

    // Note that we explicitly include showlegend: false, so a trace that *could* be
    // in the legend but is not shown still counts toward the two traces you need to
    // ensure the legend is shown by default, because this can still help disambiguate.
    return trace.visible && (trace.showlegend !== undefined);
};

exports.isGrouped = function isGrouped(legendLayout) {
    return (legendLayout.traceorder || '').indexOf('grouped') !== -1;
};

exports.isVertical = function isVertical(legendLayout) {
    return legendLayout.orientation !== 'h';
};

exports.isReversed = function isReversed(legendLayout) {
    return (legendLayout.traceorder || '').indexOf('reversed') !== -1;
};

},{}],103:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    moduleType: 'component',
    name: 'legend',

    layoutAttributes: require('./attributes'),
    supplyLayoutDefaults: require('./defaults'),

    draw: require('./draw'),
    style: require('./style')
};

},{"./attributes":96,"./defaults":98,"./draw":99,"./style":104}],104:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Lib = require('../../lib');
var Drawing = require('../drawing');
var Color = require('../color');

var subTypes = require('../../traces/scatter/subtypes');
var stylePie = require('../../traces/pie/style_one');

module.exports = function style(s, gd) {
    s.each(function(d) {
        var traceGroup = d3.select(this);

        var layers = Lib.ensureSingle(traceGroup, 'g', 'layers');
        layers.style('opacity', d[0].trace.opacity);

        var fill = layers
            .selectAll('g.legendfill')
                .data([d]);
        fill.enter().append('g')
            .classed('legendfill', true);

        var line = layers
            .selectAll('g.legendlines')
                .data([d]);
        line.enter().append('g')
            .classed('legendlines', true);

        var symbol = layers
            .selectAll('g.legendsymbols')
                .data([d]);
        symbol.enter().append('g')
            .classed('legendsymbols', true);

        symbol.selectAll('g.legendpoints')
            .data([d])
          .enter().append('g')
            .classed('legendpoints', true);
    })
    .each(styleBars)
    .each(styleBoxes)
    .each(stylePies)
    .each(styleLines)
    .each(stylePoints)
    .each(styleCandles)
    .each(styleOHLC);

    function styleLines(d) {
        var trace = d[0].trace;
        var showFill = trace.visible && trace.fill && trace.fill !== 'none';
        var showLine = subTypes.hasLines(trace);
        var contours = trace.contours;

        if(contours && contours.type === 'constraint') {
            showLine = contours.showlines;
            showFill = contours._operation !== '=';
        }

        var fill = d3.select(this).select('.legendfill').selectAll('path')
            .data(showFill ? [d] : []);
        fill.enter().append('path').classed('js-fill', true);
        fill.exit().remove();
        fill.attr('d', 'M5,0h30v6h-30z')
            .call(Drawing.fillGroupStyle);

        var line = d3.select(this).select('.legendlines').selectAll('path')
            .data(showLine ? [d] : []);
        line.enter().append('path').classed('js-line', true)
            .attr('d', 'M5,0h30');
        line.exit().remove();
        line.call(Drawing.lineGroupStyle);
    }

    function stylePoints(d) {
        var d0 = d[0],
            trace = d0.trace,
            showMarkers = subTypes.hasMarkers(trace),
            showText = subTypes.hasText(trace),
            showLines = subTypes.hasLines(trace);

        var dMod, tMod;

        // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet;
        // use d0.trace to infer arrayOk attributes

        function boundVal(attrIn, arrayToValFn, bounds) {
            var valIn = Lib.nestedProperty(trace, attrIn).get(),
                valToBound = (Array.isArray(valIn) && arrayToValFn) ?
                    arrayToValFn(valIn) : valIn;

            if(bounds) {
                if(valToBound < bounds[0]) return bounds[0];
                else if(valToBound > bounds[1]) return bounds[1];
            }
            return valToBound;
        }

        function pickFirst(array) { return array[0]; }

        // constrain text, markers, etc so they'll fit on the legend
        if(showMarkers || showText || showLines) {
            var dEdit = {};
            var tEdit = {};

            if(showMarkers) {
                dEdit.mc = boundVal('marker.color', pickFirst);
                dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
                dEdit.ms = boundVal('marker.size', Lib.mean, [2, 16]);
                dEdit.mlc = boundVal('marker.line.color', pickFirst);
                dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5]);
                tEdit.marker = {
                    sizeref: 1,
                    sizemin: 1,
                    sizemode: 'diameter'
                };
            }

            if(showLines) {
                tEdit.line = {
                    width: boundVal('line.width', pickFirst, [0, 10])
                };
            }

            if(showText) {
                dEdit.tx = 'Aa';
                dEdit.tp = boundVal('textposition', pickFirst);
                dEdit.ts = 10;
                dEdit.tc = boundVal('textfont.color', pickFirst);
                dEdit.tf = boundVal('textfont.family', pickFirst);
            }

            dMod = [Lib.minExtend(d0, dEdit)];
            tMod = Lib.minExtend(trace, tEdit);

            // always show legend items in base state
            tMod.selectedpoints = null;
        }

        var ptgroup = d3.select(this).select('g.legendpoints');

        var pts = ptgroup.selectAll('path.scatterpts')
            .data(showMarkers ? dMod : []);
        pts.enter().append('path').classed('scatterpts', true)
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();
        pts.call(Drawing.pointStyle, tMod, gd);

        // 'mrc' is set in pointStyle and used in textPointStyle:
        // constrain it here
        if(showMarkers) dMod[0].mrc = 3;

        var txt = ptgroup.selectAll('g.pointtext')
            .data(showText ? dMod : []);
        txt.enter()
            .append('g').classed('pointtext', true)
                .append('text').attr('transform', 'translate(20,0)');
        txt.exit().remove();
        txt.selectAll('text').call(Drawing.textPointStyle, tMod, gd);
    }

    function styleBars(d) {
        var trace = d[0].trace,
            marker = trace.marker || {},
            markerLine = marker.line || {},
            barpath = d3.select(this).select('g.legendpoints')
                .selectAll('path.legendbar')
                .data(Registry.traceIs(trace, 'bar') ? [d] : []);
        barpath.enter().append('path').classed('legendbar', true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        barpath.exit().remove();
        barpath.each(function(d) {
            var p = d3.select(this),
                d0 = d[0],
                w = (d0.mlw + 1 || markerLine.width + 1) - 1;

            p.style('stroke-width', w + 'px')
                .call(Color.fill, d0.mc || marker.color);

            if(w) {
                p.call(Color.stroke, d0.mlc || markerLine.color);
            }
        });
    }

    function styleBoxes(d) {
        var trace = d[0].trace,
            pts = d3.select(this).select('g.legendpoints')
                .selectAll('path.legendbox')
                .data(Registry.traceIs(trace, 'box-violin') && trace.visible ? [d] : []);
        pts.enter().append('path').classed('legendbox', true)
            // if we want the median bar, prepend M6,0H-6
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();
        pts.each(function() {
            var w = trace.line.width,
                p = d3.select(this);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, trace.fillcolor);

            if(w) {
                Color.stroke(p, trace.line.color);
            }
        });
    }

    function styleCandles(d) {
        var trace = d[0].trace,
            pts = d3.select(this).select('g.legendpoints')
                .selectAll('path.legendcandle')
                .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []);
        pts.enter().append('path').classed('legendcandle', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing
                return 'M15,0H8M8,-6V6H-8Z'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();
        pts.each(function(_, i) {
            var container = trace[i ? 'increasing' : 'decreasing'];
            var w = container.line.width,
                p = d3.select(this);

            p.style('stroke-width', w + 'px')
                .call(Color.fill, container.fillcolor);

            if(w) {
                Color.stroke(p, container.line.color);
            }
        });
    }

    function styleOHLC(d) {
        var trace = d[0].trace,
            pts = d3.select(this).select('g.legendpoints')
                .selectAll('path.legendohlc')
                .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []);
        pts.enter().append('path').classed('legendohlc', true)
            .attr('d', function(_, i) {
                if(i) return 'M-15,0H0M-8,-6V0'; // increasing
                return 'M15,0H0M8,6V0'; // decreasing
            })
            .attr('transform', 'translate(20,0)')
            .style('stroke-miterlimit', 1);
        pts.exit().remove();
        pts.each(function(_, i) {
            var container = trace[i ? 'increasing' : 'decreasing'];
            var w = container.line.width,
                p = d3.select(this);

            p.style('fill', 'none')
                .call(Drawing.dashLine, container.line.dash, w);

            if(w) {
                Color.stroke(p, container.line.color);
            }
        });
    }

    function stylePies(d) {
        var trace = d[0].trace,
            pts = d3.select(this).select('g.legendpoints')
                .selectAll('path.legendpie')
                .data(Registry.traceIs(trace, 'pie') && trace.visible ? [d] : []);
        pts.enter().append('path').classed('legendpie', true)
            .attr('d', 'M6,6H-6V-6H6Z')
            .attr('transform', 'translate(20,0)');
        pts.exit().remove();

        if(pts.size()) pts.call(stylePie, d[0], trace);
    }
};

},{"../../lib":164,"../../registry":254,"../../traces/pie/style_one":264,"../../traces/scatter/subtypes":288,"../color":43,"../drawing":68,"d3":6}],105:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var Plots = require('../../plots/plots');
var axisIds = require('../../plots/cartesian/axis_ids');
var Lib = require('../../lib');
var Icons = require('../../../build/ploticon');

var _ = Lib._;

var modeBarButtons = module.exports = {};

/**
 * ModeBar buttons configuration
 *
 * @param {string} name
 *      name / id of the buttons (for tracking)
 * @param {string} title
 *      text that appears while hovering over the button,
 *      enter null, false or '' for no hover text
 * @param {string} icon
 *      svg icon object associated with the button
 *      can be linked to Plotly.Icons to use the default plotly icons
 * @param {string} [gravity]
 *      icon positioning
 * @param {function} click
 *      click handler associated with the button, a function of
 *      'gd' (the main graph object) and
 *      'ev' (the event object)
 * @param {string} [attr]
 *      attribute associated with button,
 *      use this with 'val' to keep track of the state
 * @param {*} [val]
 *      initial 'attr' value, can be a function of gd
 * @param {boolean} [toggle]
 *      is the button a toggle button?
 */

modeBarButtons.toImage = {
    name: 'toImage',
    title: function(gd) { return _(gd, 'Download plot as a png'); },
    icon: Icons.camera,
    click: function(gd) {
        var format = 'png';

        Lib.notifier(_(gd, 'Taking snapshot - this may take a few seconds'), 'long');

        if(Lib.isIE()) {
            Lib.notifier(_(gd, 'IE only supports svg.  Changing format to svg.'), 'long');
            format = 'svg';
        }

        Registry.call('downloadImage', gd, {'format': format})
          .then(function(filename) {
              Lib.notifier(_(gd, 'Snapshot succeeded') + ' - ' + filename, 'long');
          })
          .catch(function() {
              Lib.notifier(_(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long');
          });
    }
};

modeBarButtons.sendDataToCloud = {
    name: 'sendDataToCloud',
    title: function(gd) { return _(gd, 'Edit in Chart Studio'); },
    icon: Icons.disk,
    click: function(gd) {
        Plots.sendDataToCloud(gd);
    }
};

modeBarButtons.zoom2d = {
    name: 'zoom2d',
    title: function(gd) { return _(gd, 'Zoom'); },
    attr: 'dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleCartesian
};

modeBarButtons.pan2d = {
    name: 'pan2d',
    title: function(gd) { return _(gd, 'Pan'); },
    attr: 'dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleCartesian
};

modeBarButtons.select2d = {
    name: 'select2d',
    title: function(gd) { return _(gd, 'Box Select'); },
    attr: 'dragmode',
    val: 'select',
    icon: Icons.selectbox,
    click: handleCartesian
};

modeBarButtons.lasso2d = {
    name: 'lasso2d',
    title: function(gd) { return _(gd, 'Lasso Select'); },
    attr: 'dragmode',
    val: 'lasso',
    icon: Icons.lasso,
    click: handleCartesian
};

modeBarButtons.zoomIn2d = {
    name: 'zoomIn2d',
    title: function(gd) { return _(gd, 'Zoom in'); },
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleCartesian
};

modeBarButtons.zoomOut2d = {
    name: 'zoomOut2d',
    title: function(gd) { return _(gd, 'Zoom out'); },
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleCartesian
};

modeBarButtons.autoScale2d = {
    name: 'autoScale2d',
    title: function(gd) { return _(gd, 'Autoscale'); },
    attr: 'zoom',
    val: 'auto',
    icon: Icons.autoscale,
    click: handleCartesian
};

modeBarButtons.resetScale2d = {
    name: 'resetScale2d',
    title: function(gd) { return _(gd, 'Reset axes'); },
    attr: 'zoom',
    val: 'reset',
    icon: Icons.home,
    click: handleCartesian
};

modeBarButtons.hoverClosestCartesian = {
    name: 'hoverClosestCartesian',
    title: function(gd) { return _(gd, 'Show closest data on hover'); },
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleCartesian
};

modeBarButtons.hoverCompareCartesian = {
    name: 'hoverCompareCartesian',
    title: function(gd) { return _(gd, 'Compare data on hover'); },
    attr: 'hovermode',
    val: function(gd) {
        return gd._fullLayout._isHoriz ? 'y' : 'x';
    },
    icon: Icons.tooltip_compare,
    gravity: 'ne',
    click: handleCartesian
};

function handleCartesian(gd, ev) {
    var button = ev.currentTarget;
    var astr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var fullLayout = gd._fullLayout;
    var aobj = {};
    var axList = axisIds.list(gd, null, true);
    var allSpikesEnabled = 'on';

    var ax, i;

    if(astr === 'zoom') {
        var mag = (val === 'in') ? 0.5 : 2,
            r0 = (1 + mag) / 2,
            r1 = (1 - mag) / 2;

        var axName;

        for(i = 0; i < axList.length; i++) {
            ax = axList[i];

            if(!ax.fixedrange) {
                axName = ax._name;
                if(val === 'auto') aobj[axName + '.autorange'] = true;
                else if(val === 'reset') {
                    if(ax._rangeInitial === undefined) {
                        aobj[axName + '.autorange'] = true;
                    }
                    else {
                        var rangeInitial = ax._rangeInitial.slice();
                        aobj[axName + '.range[0]'] = rangeInitial[0];
                        aobj[axName + '.range[1]'] = rangeInitial[1];
                    }
                    if(ax._showSpikeInitial !== undefined) {
                        aobj[axName + '.showspikes'] = ax._showSpikeInitial;
                        if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) {
                            allSpikesEnabled = 'off';
                        }
                    }
                }
                else {
                    var rangeNow = [
                        ax.r2l(ax.range[0]),
                        ax.r2l(ax.range[1]),
                    ];

                    var rangeNew = [
                        r0 * rangeNow[0] + r1 * rangeNow[1],
                        r0 * rangeNow[1] + r1 * rangeNow[0]
                    ];

                    aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]);
                    aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]);
                }
            }
        }
        fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
    }
    else {
        // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
        if(astr === 'hovermode' && (val === 'x' || val === 'y')) {
            val = fullLayout._isHoriz ? 'y' : 'x';
            button.setAttribute('data-val', val);
        } else if(astr === 'hovermode' && val === 'closest') {
            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if(allSpikesEnabled === 'on' && !ax.showspikes) {
                    allSpikesEnabled = 'off';
                }
            }
            fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
        }

        aobj[astr] = val;
    }

    Registry.call('relayout', gd, aobj);
}

modeBarButtons.zoom3d = {
    name: 'zoom3d',
    title: function(gd) { return _(gd, 'Zoom'); },
    attr: 'scene.dragmode',
    val: 'zoom',
    icon: Icons.zoombox,
    click: handleDrag3d
};

modeBarButtons.pan3d = {
    name: 'pan3d',
    title: function(gd) { return _(gd, 'Pan'); },
    attr: 'scene.dragmode',
    val: 'pan',
    icon: Icons.pan,
    click: handleDrag3d
};

modeBarButtons.orbitRotation = {
    name: 'orbitRotation',
    title: function(gd) { return _(gd, 'Orbital rotation'); },
    attr: 'scene.dragmode',
    val: 'orbit',
    icon: Icons['3d_rotate'],
    click: handleDrag3d
};

modeBarButtons.tableRotation = {
    name: 'tableRotation',
    title: function(gd) { return _(gd, 'Turntable rotation'); },
    attr: 'scene.dragmode',
    val: 'turntable',
    icon: Icons['z-axis'],
    click: handleDrag3d
};

function handleDrag3d(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var sceneIds = gd._fullLayout._subplots.gl3d;
    var layoutUpdate = {};

    var parts = attr.split('.');

    for(var i = 0; i < sceneIds.length; i++) {
        layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
    }

    // for multi-type subplots
    var val2d = (val === 'pan') ? val : 'zoom';
    layoutUpdate.dragmode = val2d;

    Registry.call('relayout', gd, layoutUpdate);
}

modeBarButtons.resetCameraDefault3d = {
    name: 'resetCameraDefault3d',
    title: function(gd) { return _(gd, 'Reset camera to default'); },
    attr: 'resetDefault',
    icon: Icons.home,
    click: handleCamera3d
};

modeBarButtons.resetCameraLastSave3d = {
    name: 'resetCameraLastSave3d',
    title: function(gd) { return _(gd, 'Reset camera to last save'); },
    attr: 'resetLastSave',
    icon: Icons.movie,
    click: handleCamera3d
};

function handleCamera3d(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;
    var aobj = {};

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneId = sceneIds[i],
            key = sceneId + '.camera',
            scene = fullLayout[sceneId]._scene;

        if(attr === 'resetDefault') {
            aobj[key] = null;
        }
        else if(attr === 'resetLastSave') {
            aobj[key] = Lib.extendDeep({}, scene.cameraInitial);
        }
    }

    Registry.call('relayout', gd, aobj);
}

modeBarButtons.hoverClosest3d = {
    name: 'hoverClosest3d',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: handleHover3d
};

function handleHover3d(gd, ev) {
    var button = ev.currentTarget;
    var val = button._previousVal || false;
    var layout = gd.layout;
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;

    var axes = ['xaxis', 'yaxis', 'zaxis'];
    var spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor'];

    // initialize 'current spike' object to be stored in the DOM
    var currentSpikes = {};
    var axisSpikes = {};
    var layoutUpdate = {};

    if(val) {
        layoutUpdate = Lib.extendDeep(layout, val);
        button._previousVal = null;
    }
    else {
        layoutUpdate = {
            'allaxes.showspikes': false
        };

        for(var i = 0; i < sceneIds.length; i++) {
            var sceneId = sceneIds[i],
                sceneLayout = fullLayout[sceneId],
                sceneSpikes = currentSpikes[sceneId] = {};

            sceneSpikes.hovermode = sceneLayout.hovermode;
            layoutUpdate[sceneId + '.hovermode'] = false;

            // copy all the current spike attrs
            for(var j = 0; j < 3; j++) {
                var axis = axes[j];
                axisSpikes = sceneSpikes[axis] = {};

                for(var k = 0; k < spikeAttrs.length; k++) {
                    var spikeAttr = spikeAttrs[k];
                    axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr];
                }
            }
        }

        button._previousVal = Lib.extendDeep({}, currentSpikes);
    }

    Registry.call('relayout', gd, layoutUpdate);
}

modeBarButtons.zoomInGeo = {
    name: 'zoomInGeo',
    title: function(gd) { return _(gd, 'Zoom in'); },
    attr: 'zoom',
    val: 'in',
    icon: Icons.zoom_plus,
    click: handleGeo
};

modeBarButtons.zoomOutGeo = {
    name: 'zoomOutGeo',
    title: function(gd) { return _(gd, 'Zoom out'); },
    attr: 'zoom',
    val: 'out',
    icon: Icons.zoom_minus,
    click: handleGeo
};

modeBarButtons.resetGeo = {
    name: 'resetGeo',
    title: function(gd) { return _(gd, 'Reset'); },
    attr: 'reset',
    val: null,
    icon: Icons.autoscale,
    click: handleGeo
};

modeBarButtons.hoverClosestGeo = {
    name: 'hoverClosestGeo',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function handleGeo(gd, ev) {
    var button = ev.currentTarget;
    var attr = button.getAttribute('data-attr');
    var val = button.getAttribute('data-val') || true;
    var fullLayout = gd._fullLayout;
    var geoIds = fullLayout._subplots.geo;

    for(var i = 0; i < geoIds.length; i++) {
        var id = geoIds[i];
        var geoLayout = fullLayout[id];

        if(attr === 'zoom') {
            var scale = geoLayout.projection.scale;
            var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;

            Registry.call('relayout', gd, id + '.projection.scale', newScale);
        } else if(attr === 'reset') {
            resetView(gd, 'geo');
        }
    }
}

modeBarButtons.hoverClosestGl2d = {
    name: 'hoverClosestGl2d',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

modeBarButtons.hoverClosestPie = {
    name: 'hoverClosestPie',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: 'closest',
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: toggleHover
};

function toggleHover(gd) {
    var fullLayout = gd._fullLayout;

    var onHoverVal;
    if(fullLayout._has('cartesian')) {
        onHoverVal = fullLayout._isHoriz ? 'y' : 'x';
    }
    else onHoverVal = 'closest';

    var newHover = gd._fullLayout.hovermode ? false : onHoverVal;

    Registry.call('relayout', gd, 'hovermode', newHover);
}

// buttons when more then one plot types are present

modeBarButtons.toggleHover = {
    name: 'toggleHover',
    title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
    attr: 'hovermode',
    val: null,
    toggle: true,
    icon: Icons.tooltip_basic,
    gravity: 'ne',
    click: function(gd, ev) {
        toggleHover(gd);

        // the 3d hovermode update must come
        // last so that layout.hovermode update does not
        // override scene?.hovermode?.layout.
        handleHover3d(gd, ev);
    }
};

modeBarButtons.resetViews = {
    name: 'resetViews',
    title: function(gd) { return _(gd, 'Reset views'); },
    icon: Icons.home,
    click: function(gd, ev) {
        var button = ev.currentTarget;

        button.setAttribute('data-attr', 'zoom');
        button.setAttribute('data-val', 'reset');
        handleCartesian(gd, ev);

        button.setAttribute('data-attr', 'resetLastSave');
        handleCamera3d(gd, ev);

        resetView(gd, 'geo');
        resetView(gd, 'mapbox');
    }
};

modeBarButtons.toggleSpikelines = {
    name: 'toggleSpikelines',
    title: function(gd) { return _(gd, 'Toggle Spike Lines'); },
    icon: Icons.spikeline,
    attr: '_cartesianSpikesEnabled',
    val: 'on',
    click: function(gd) {
        var fullLayout = gd._fullLayout;

        fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on';

        var aobj = setSpikelineVisibility(gd);

        Registry.call('relayout', gd, aobj);
    }
};

function setSpikelineVisibility(gd) {
    var fullLayout = gd._fullLayout;
    var axList = axisIds.list(gd, null, true);
    var aobj = {};

    var ax, axName;

    for(var i = 0; i < axList.length; i++) {
        ax = axList[i];
        axName = ax._name;
        aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial;
    }

    return aobj;
}

modeBarButtons.resetViewMapbox = {
    name: 'resetViewMapbox',
    title: function(gd) { return _(gd, 'Reset view'); },
    attr: 'reset',
    icon: Icons.home,
    click: function(gd) {
        resetView(gd, 'mapbox');
    }
};

function resetView(gd, subplotType) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[subplotType];
    var aObj = {};

    for(var i = 0; i < subplotIds.length; i++) {
        var id = subplotIds[i];
        var subplotObj = fullLayout[id]._subplot;
        var viewInitial = subplotObj.viewInitial;
        var viewKeys = Object.keys(viewInitial);

        for(var j = 0; j < viewKeys.length; j++) {
            var key = viewKeys[j];
            aObj[id + '.' + key] = viewInitial[key];
        }
    }

    Registry.call('relayout', gd, aObj);
}

},{"../../../build/ploticon":2,"../../lib":164,"../../plots/cartesian/axis_ids":209,"../../plots/plots":245,"../../registry":254}],106:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.manage = require('./manage');

},{"./manage":107}],107:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var axisIds = require('../../plots/cartesian/axis_ids');
var scatterSubTypes = require('../../traces/scatter/subtypes');
var Registry = require('../../registry');

var createModeBar = require('./modebar');
var modeBarButtons = require('./buttons');

/**
 * ModeBar wrapper around 'create' and 'update',
 * chooses buttons to pass to ModeBar constructor based on
 * plot type and plot config.
 *
 * @param {object} gd main plot object
 *
 */
module.exports = function manageModeBar(gd) {
    var fullLayout = gd._fullLayout,
        context = gd._context,
        modeBar = fullLayout._modeBar;

    if(!context.displayModeBar) {
        if(modeBar) {
            modeBar.destroy();
            delete fullLayout._modeBar;
        }
        return;
    }

    if(!Array.isArray(context.modeBarButtonsToRemove)) {
        throw new Error([
            '*modeBarButtonsToRemove* configuration options',
            'must be an array.'
        ].join(' '));
    }

    if(!Array.isArray(context.modeBarButtonsToAdd)) {
        throw new Error([
            '*modeBarButtonsToAdd* configuration options',
            'must be an array.'
        ].join(' '));
    }

    var customButtons = context.modeBarButtons;
    var buttonGroups;

    if(Array.isArray(customButtons) && customButtons.length) {
        buttonGroups = fillCustomButton(customButtons);
    }
    else {
        buttonGroups = getButtonGroups(
            gd,
            context.modeBarButtonsToRemove,
            context.modeBarButtonsToAdd
        );
    }

    if(modeBar) modeBar.update(gd, buttonGroups);
    else fullLayout._modeBar = createModeBar(gd, buttonGroups);
};

// logic behind which buttons are displayed by default
function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) {
    var fullLayout = gd._fullLayout;
    var fullData = gd._fullData;

    var hasCartesian = fullLayout._has('cartesian');
    var hasGL3D = fullLayout._has('gl3d');
    var hasGeo = fullLayout._has('geo');
    var hasPie = fullLayout._has('pie');
    var hasGL2D = fullLayout._has('gl2d');
    var hasTernary = fullLayout._has('ternary');
    var hasMapbox = fullLayout._has('mapbox');
    var hasPolar = fullLayout._has('polar');
    var allAxesFixed = areAllAxesFixed(fullLayout);

    var groups = [];

    function addGroup(newGroup) {
        if(!newGroup.length) return;

        var out = [];

        for(var i = 0; i < newGroup.length; i++) {
            var button = newGroup[i];
            if(buttonsToRemove.indexOf(button) !== -1) continue;
            out.push(modeBarButtons[button]);
        }

        groups.push(out);
    }

    // buttons common to all plot types
    addGroup(['toImage', 'sendDataToCloud']);

    var zoomGroup = [];
    var hoverGroup = [];
    var resetGroup = [];
    var dragModeGroup = [];

    if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) {
        // graphs with more than one plot types get 'union buttons'
        // which reset the view or toggle hover labels across all subplots.
        hoverGroup = ['toggleHover'];
        resetGroup = ['resetViews'];
    }
    else if(hasGeo) {
        zoomGroup = ['zoomInGeo', 'zoomOutGeo'];
        hoverGroup = ['hoverClosestGeo'];
        resetGroup = ['resetGeo'];
    }
    else if(hasGL3D) {
        hoverGroup = ['hoverClosest3d'];
        resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d'];
    }
    else if(hasMapbox) {
        hoverGroup = ['toggleHover'];
        resetGroup = ['resetViewMapbox'];
    }
    else if(hasGL2D) {
        hoverGroup = ['hoverClosestGl2d'];
    }
    else if(hasPie) {
        hoverGroup = ['hoverClosestPie'];
    }
    else { // hasPolar, hasTernary
        // always show at least one hover icon.
        hoverGroup = ['toggleHover'];
    }
    // if we have cartesian, allow switching between closest and compare
    // regardless of what other types are on the plot, since they'll all
    // just treat any truthy hovermode as 'closest'
    if(hasCartesian) {
        hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian'];
    }

    if((hasCartesian || hasGL2D) && !allAxesFixed) {
        zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d'];
        if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d'];
    }

    if(hasGL3D) {
        dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation'];
    }
    else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) {
        dragModeGroup = ['zoom2d', 'pan2d'];
    }
    else if(hasMapbox || hasGeo) {
        dragModeGroup = ['pan2d'];
    }
    else if(hasPolar) {
        dragModeGroup = ['zoom2d'];
    }
    if(isSelectable(fullData)) {
        dragModeGroup.push('select2d', 'lasso2d');
    }

    addGroup(dragModeGroup);
    addGroup(zoomGroup.concat(resetGroup));
    addGroup(hoverGroup);

    return appendButtonsToGroups(groups, buttonsToAdd);
}

function areAllAxesFixed(fullLayout) {
    var axList = axisIds.list({_fullLayout: fullLayout}, null, true);

    for(var i = 0; i < axList.length; i++) {
        if(!axList[i].fixedrange) {
            return false;
        }
    }

    return true;
}

// look for traces that support selection
// to be updated as we add more selectPoints handlers
function isSelectable(fullData) {
    var selectable = false;

    for(var i = 0; i < fullData.length; i++) {
        if(selectable) break;

        var trace = fullData[i];

        if(!trace._module || !trace._module.selectPoints) continue;

        if(Registry.traceIs(trace, 'scatter-like')) {
            if(scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
                selectable = true;
            }
        } else if(Registry.traceIs(trace, 'box-violin')) {
            if(trace.boxpoints === 'all' || trace.points === 'all') {
                selectable = true;
            }
        }
        // assume that in general if the trace module has selectPoints,
        // then it's selectable. Scatter is an exception to this because it must
        // have markers or text, not just be a scatter type.
        else selectable = true;
    }

    return selectable;
}

function appendButtonsToGroups(groups, buttons) {
    if(buttons.length) {
        if(Array.isArray(buttons[0])) {
            for(var i = 0; i < buttons.length; i++) {
                groups.push(buttons[i]);
            }
        }
        else groups.push(buttons);
    }

    return groups;
}

// fill in custom buttons referring to default mode bar buttons
function fillCustomButton(customButtons) {
    for(var i = 0; i < customButtons.length; i++) {
        var buttonGroup = customButtons[i];

        for(var j = 0; j < buttonGroup.length; j++) {
            var button = buttonGroup[j];

            if(typeof button === 'string') {
                if(modeBarButtons[button] !== undefined) {
                    customButtons[i][j] = modeBarButtons[button];
                }
                else {
                    throw new Error([
                        '*modeBarButtons* configuration options',
                        'invalid button name'
                    ].join(' '));
                }
            }
        }
    }

    return customButtons;
}

},{"../../plots/cartesian/axis_ids":209,"../../registry":254,"../../traces/scatter/subtypes":288,"./buttons":105,"./modebar":108}],108:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Lib = require('../../lib');
var Icons = require('../../../build/ploticon');


/**
 * UI controller for interactive plots
 * @Class
 * @Param {object} opts
 * @Param {object} opts.buttons    nested arrays of grouped buttons config objects
 * @Param {object} opts.container  container div to append modeBar
 * @Param {object} opts.graphInfo  primary plot object containing data and layout
 */
function ModeBar(opts) {
    this.container = opts.container;
    this.element = document.createElement('div');

    this.update(opts.graphInfo, opts.buttons);

    this.container.appendChild(this.element);
}

var proto = ModeBar.prototype;

/**
 * Update modeBar (buttons and logo)
 *
 * @param {object} graphInfo  primary plot object containing data and layout
 * @param {array of arrays} buttons nested arrays of grouped buttons to initialize
 *
 */
proto.update = function(graphInfo, buttons) {
    this.graphInfo = graphInfo;

    var context = this.graphInfo._context;

    if(context.displayModeBar === 'hover') {
        this.element.className = 'modebar modebar--hover';
    }
    else this.element.className = 'modebar';

    // if buttons or logo have changed, redraw modebar interior
    var needsNewButtons = !this.hasButtons(buttons);
    var needsNewLogo = (this.hasLogo !== context.displaylogo);
    var needsNewLocale = (this.locale !== context.locale);

    this.locale = context.locale;

    if(needsNewButtons || needsNewLogo || needsNewLocale) {
        this.removeAllButtons();

        this.updateButtons(buttons);

        if(context.displaylogo) {
            this.element.appendChild(this.getLogo());
            this.hasLogo = true;
        }
    }

    this.updateActiveButton();
};

proto.updateButtons = function(buttons) {
    var _this = this;

    this.buttons = buttons;
    this.buttonElements = [];
    this.buttonsNames = [];

    this.buttons.forEach(function(buttonGroup) {
        var group = _this.createGroup();

        buttonGroup.forEach(function(buttonConfig) {
            var buttonName = buttonConfig.name;
            if(!buttonName) {
                throw new Error('must provide button \'name\' in button config');
            }
            if(_this.buttonsNames.indexOf(buttonName) !== -1) {
                throw new Error('button name \'' + buttonName + '\' is taken');
            }
            _this.buttonsNames.push(buttonName);

            var button = _this.createButton(buttonConfig);
            _this.buttonElements.push(button);
            group.appendChild(button);
        });

        _this.element.appendChild(group);
    });
};

/**
 * Empty div for containing a group of buttons
 * @Return {HTMLelement}
 */
proto.createGroup = function() {
    var group = document.createElement('div');
    group.className = 'modebar-group';

    return group;
};

/**
 * Create a new button div and set constant and configurable attributes
 * @Param {object} config (see ./buttons.js for more info)
 * @Return {HTMLelement}
 */
proto.createButton = function(config) {
    var _this = this,
        button = document.createElement('a');

    button.setAttribute('rel', 'tooltip');
    button.className = 'modebar-btn';

    var title = config.title;
    if(title === undefined) title = config.name;
    // for localization: allow title to be a callable that takes gd as arg
    else if(typeof title === 'function') title = title(this.graphInfo);

    if(title || title === 0) button.setAttribute('data-title', title);

    if(config.attr !== undefined) button.setAttribute('data-attr', config.attr);

    var val = config.val;
    if(val !== undefined) {
        if(typeof val === 'function') val = val(this.graphInfo);
        button.setAttribute('data-val', val);
    }

    var click = config.click;
    if(typeof click !== 'function') {
        throw new Error('must provide button \'click\' function in button config');
    }
    else {
        button.addEventListener('click', function(ev) {
            config.click(_this.graphInfo, ev);

            // only needed for 'hoverClosestGeo' which does not call relayout
            _this.updateActiveButton(ev.currentTarget);
        });
    }

    button.setAttribute('data-toggle', config.toggle || false);
    if(config.toggle) d3.select(button).classed('active', true);

    button.appendChild(this.createIcon(config.icon || Icons.question, config.name));
    button.setAttribute('data-gravity', config.gravity || 'n');

    return button;
};

/**
 * Add an icon to a button
 * @Param {object} thisIcon
 * @Param {number} thisIcon.width
 * @Param {string} thisIcon.path
 * @Return {HTMLelement}
 */
proto.createIcon = function(thisIcon, name) {
    var iconHeight = thisIcon.ascent - thisIcon.descent,
        svgNS = 'http://www.w3.org/2000/svg',
        icon = document.createElementNS(svgNS, 'svg'),
        path = document.createElementNS(svgNS, 'path');

    icon.setAttribute('height', '1em');
    icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em');
    icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' '));

    var transform = name === 'toggleSpikelines' ?
        'matrix(1.5 0 0 -1.5 0 ' + thisIcon.ascent + ')' :
        'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')';

    path.setAttribute('d', thisIcon.path);
    path.setAttribute('transform', transform);
    icon.appendChild(path);

    return icon;
};

/**
 * Updates active button with attribute specified in layout
 * @Param {object} graphInfo plot object containing data and layout
 * @Return {HTMLelement}
 */
proto.updateActiveButton = function(buttonClicked) {
    var fullLayout = this.graphInfo._fullLayout,
        dataAttrClicked = (buttonClicked !== undefined) ?
            buttonClicked.getAttribute('data-attr') :
            null;

    this.buttonElements.forEach(function(button) {
        var thisval = button.getAttribute('data-val') || true,
            dataAttr = button.getAttribute('data-attr'),
            isToggleButton = (button.getAttribute('data-toggle') === 'true'),
            button3 = d3.select(button);

        // Use 'data-toggle' and 'buttonClicked' to toggle buttons
        // that have no one-to-one equivalent in fullLayout
        if(isToggleButton) {
            if(dataAttr === dataAttrClicked) {
                button3.classed('active', !button3.classed('active'));
            }
        }
        else {
            var val = (dataAttr === null) ?
                dataAttr :
                Lib.nestedProperty(fullLayout, dataAttr).get();

            button3.classed('active', val === thisval);
        }

    });
};

/**
 * Check if modeBar is configured as button configuration argument
 *
 * @Param {object} buttons 2d array of grouped button config objects
 * @Return {boolean}
 */
proto.hasButtons = function(buttons) {
    var currentButtons = this.buttons;

    if(!currentButtons) return false;

    if(buttons.length !== currentButtons.length) return false;

    for(var i = 0; i < buttons.length; ++i) {
        if(buttons[i].length !== currentButtons[i].length) return false;
        for(var j = 0; j < buttons[i].length; j++) {
            if(buttons[i][j].name !== currentButtons[i][j].name) return false;
        }
    }

    return true;
};

/**
 * @return {HTMLDivElement} The logo image wrapped in a group
 */
proto.getLogo = function() {
    var group = this.createGroup(),
        a = document.createElement('a');

    a.href = 'https://plot.ly/';
    a.target = '_blank';
    a.setAttribute('data-title', Lib._(this.graphInfo, 'Produced with Plotly'));
    a.className = 'modebar-btn plotlyjsicon modebar-btn--logo';

    a.appendChild(this.createIcon(Icons.plotlylogo));

    group.appendChild(a);
    return group;
};

proto.removeAllButtons = function() {
    while(this.element.firstChild) {
        this.element.removeChild(this.element.firstChild);
    }

    this.hasLogo = false;
};

proto.destroy = function() {
    Lib.removeElement(this.container.querySelector('.modebar'));
};

function createModeBar(gd, buttons) {
    var fullLayout = gd._fullLayout;

    var modeBar = new ModeBar({
        graphInfo: gd,
        container: fullLayout._paperdiv.node(),
        buttons: buttons
    });

    if(fullLayout._privateplot) {
        d3.select(modeBar.element).append('span')
            .classed('badge-private float--left', true)
            .text('PRIVATE');
    }

    return modeBar;
}

module.exports = createModeBar;

},{"../../../build/ploticon":2,"../../lib":164,"d3":6}],109:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('../../plots/font_attributes');
var colorAttrs = require('../color/attributes');
var extendFlat = require('../../lib/extend').extendFlat;
var buttonAttrs = require('./button_attributes');

buttonAttrs = extendFlat(buttonAttrs, {
    _isLinkedToArray: 'button',

    
});

module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'plot',
        
    },

    buttons: buttonAttrs,

    x: {
        valType: 'number',
        min: -2,
        max: 3,
        
        editType: 'plot',
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        editType: 'plot',
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        
        editType: 'plot',
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'bottom',
        
        editType: 'plot',
        
    },

    font: fontAttrs({
        editType: 'plot',
        
    }),

    bgcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'plot',
        
    },
    activecolor: {
        valType: 'color',
        
        editType: 'plot',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'plot',
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 0,
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

},{"../../lib/extend":157,"../../plots/font_attributes":232,"../color/attributes":42,"./button_attributes":110}],110:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    step: {
        valType: 'enumerated',
        
        values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'],
        dflt: 'month',
        editType: 'plot',
        
    },
    stepmode: {
        valType: 'enumerated',
        
        values: ['backward', 'todate'],
        dflt: 'backward',
        editType: 'plot',
        
    },
    count: {
        valType: 'number',
        
        min: 0,
        dflt: 1,
        editType: 'plot',
        
    },
    label: {
        valType: 'string',
        
        editType: 'plot',
        
    },
    editType: 'plot'
};

},{}],111:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {

    // 'y' position pad above counter axis domain
    yPad: 0.02,

    // minimum button width (regardless of text size)
    minButtonWidth: 30,

    // buttons rect radii
    rx: 3,
    ry: 3,

    // light fraction used to compute the 'activecolor' default
    lightAmount: 25,
    darkAmount: 10
};

},{}],112:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Color = require('../color');

var attributes = require('./attributes');
var buttonAttrs = require('./button_attributes');
var constants = require('./constants');


module.exports = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) {
    var selectorIn = containerIn.rangeselector || {},
        selectorOut = containerOut.rangeselector = {};

    function coerce(attr, dflt) {
        return Lib.coerce(selectorIn, selectorOut, attributes, attr, dflt);
    }

    var buttons = buttonsDefaults(selectorIn, selectorOut, calendar);

    var visible = coerce('visible', buttons.length > 0);
    if(!visible) return;

    var posDflt = getPosDflt(containerOut, layout, counterAxes);
    coerce('x', posDflt[0]);
    coerce('y', posDflt[1]);
    Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    Lib.coerceFont(coerce, 'font', layout.font);

    var bgColor = coerce('bgcolor');
    coerce('activecolor', Color.contrast(bgColor, constants.lightAmount, constants.darkAmount));
    coerce('bordercolor');
    coerce('borderwidth');
};

function buttonsDefaults(containerIn, containerOut, calendar) {
    var buttonsIn = containerIn.buttons || [],
        buttonsOut = containerOut.buttons = [];

    var buttonIn, buttonOut;

    function coerce(attr, dflt) {
        return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
    }

    for(var i = 0; i < buttonsIn.length; i++) {
        buttonIn = buttonsIn[i];
        buttonOut = {};

        if(!Lib.isPlainObject(buttonIn)) continue;

        var step = coerce('step');
        if(step !== 'all') {
            if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) {
                buttonOut.stepmode = 'backward';
            }
            else {
                coerce('stepmode');
            }

            coerce('count');
        }

        coerce('label');

        buttonOut._index = i;
        buttonsOut.push(buttonOut);
    }

    return buttonsOut;
}

function getPosDflt(containerOut, layout, counterAxes) {
    var anchoredList = counterAxes.filter(function(ax) {
        return layout[ax].anchor === containerOut._id;
    });

    var posY = 0;
    for(var i = 0; i < anchoredList.length; i++) {
        var domain = layout[anchoredList[i]].domain;
        if(domain) posY = Math.max(domain[1], posY);
    }

    return [containerOut.domain[0], posY + constants.yPad];
}

},{"../../lib":164,"../color":43,"./attributes":109,"./button_attributes":110,"./constants":111}],113:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Plots = require('../../plots/plots');
var Color = require('../color');
var Drawing = require('../drawing');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');
var axisIds = require('../../plots/cartesian/axis_ids');
var anchorUtils = require('../legend/anchor_utils');

var alignmentConstants = require('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

var constants = require('./constants');
var getUpdateObject = require('./get_update_object');


module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout;

    var selectors = fullLayout._infolayer.selectAll('.rangeselector')
        .data(makeSelectorData(gd), selectorKeyFunc);

    selectors.enter().append('g')
        .classed('rangeselector', true);

    selectors.exit().remove();

    selectors.style({
        cursor: 'pointer',
        'pointer-events': 'all'
    });

    selectors.each(function(d) {
        var selector = d3.select(this),
            axisLayout = d,
            selectorLayout = axisLayout.rangeselector;

        var buttons = selector.selectAll('g.button')
            .data(selectorLayout.buttons);

        buttons.enter().append('g')
            .classed('button', true);

        buttons.exit().remove();

        buttons.each(function(d) {
            var button = d3.select(this);
            var update = getUpdateObject(axisLayout, d);

            d._isActive = isActive(axisLayout, d, update);

            button.call(drawButtonRect, selectorLayout, d);
            button.call(drawButtonText, selectorLayout, d, gd);

            button.on('click', function() {
                if(gd._dragged) return;

                Registry.call('relayout', gd, update);
            });

            button.on('mouseover', function() {
                d._isHovered = true;
                button.call(drawButtonRect, selectorLayout, d);
            });

            button.on('mouseout', function() {
                d._isHovered = false;
                button.call(drawButtonRect, selectorLayout, d);
            });
        });

        reposition(gd, buttons, selectorLayout, axisLayout._name, selector);
    });

};

function makeSelectorData(gd) {
    var axes = axisIds.list(gd, 'x', true);
    var data = [];

    for(var i = 0; i < axes.length; i++) {
        var axis = axes[i];

        if(axis.rangeselector && axis.rangeselector.visible) {
            data.push(axis);
        }
    }

    return data;
}

function selectorKeyFunc(d) {
    return d._id;
}

function isActive(axisLayout, opts, update) {
    if(opts.step === 'all') {
        return axisLayout.autorange === true;
    }
    else {
        var keys = Object.keys(update);

        return (
            axisLayout.range[0] === update[keys[0]] &&
            axisLayout.range[1] === update[keys[1]]
        );
    }
}

function drawButtonRect(button, selectorLayout, d) {
    var rect = Lib.ensureSingle(button, 'rect', 'selector-rect', function(s) {
        s.attr('shape-rendering', 'crispEdges');
    });

    rect.attr({
        'rx': constants.rx,
        'ry': constants.ry
    });

    rect.call(Color.stroke, selectorLayout.bordercolor)
        .call(Color.fill, getFillColor(selectorLayout, d))
        .style('stroke-width', selectorLayout.borderwidth + 'px');
}

function getFillColor(selectorLayout, d) {
    return (d._isActive || d._isHovered) ?
        selectorLayout.activecolor :
        selectorLayout.bgcolor;
}

function drawButtonText(button, selectorLayout, d, gd) {
    function textLayout(s) {
        svgTextUtils.convertToTspans(s, gd);
    }

    var text = Lib.ensureSingle(button, 'text', 'selector-text', function(s) {
        s.classed('user-select-none', true)
            .attr('text-anchor', 'middle');
    });

    text.call(Drawing.font, selectorLayout.font)
        .text(getLabel(d))
        .call(textLayout);
}

function getLabel(opts) {
    if(opts.label) return opts.label;

    if(opts.step === 'all') return 'all';

    return opts.count + opts.step.charAt(0);
}

function reposition(gd, buttons, opts, axName, selector) {
    var width = 0;
    var height = 0;

    var borderWidth = opts.borderwidth;

    buttons.each(function() {
        var button = d3.select(this);
        var text = button.select('.selector-text');

        var tHeight = opts.font.size * LINE_SPACING;
        var hEff = Math.max(tHeight * svgTextUtils.lineCount(text), 16) + 3;

        height = Math.max(height, hEff);
    });

    buttons.each(function() {
        var button = d3.select(this);
        var rect = button.select('.selector-rect');
        var text = button.select('.selector-text');

        var tWidth = text.node() && Drawing.bBox(text.node()).width;
        var tHeight = opts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);

        var wEff = Math.max(tWidth + 10, constants.minButtonWidth);

        // TODO add MathJax support

        // TODO add buttongap attribute

        button.attr('transform', 'translate(' +
            (borderWidth + width) + ',' + borderWidth +
        ')');

        rect.attr({
            x: 0,
            y: 0,
            width: wEff,
            height: height
        });

        svgTextUtils.positionText(text, wEff / 2,
            height / 2 - ((tLines - 1) * tHeight / 2) + 3);

        width += wEff + 5;
    });

    var graphSize = gd._fullLayout._size;
    var lx = graphSize.l + graphSize.w * opts.x;
    var ly = graphSize.t + graphSize.h * (1 - opts.y);

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(opts)) {
        lx -= width;
        xanchor = 'right';
    }
    if(anchorUtils.isCenterAnchor(opts)) {
        lx -= width / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(anchorUtils.isBottomAnchor(opts)) {
        ly -= height;
        yanchor = 'bottom';
    }
    if(anchorUtils.isMiddleAnchor(opts)) {
        ly -= height / 2;
        yanchor = 'middle';
    }

    width = Math.ceil(width);
    height = Math.ceil(height);
    lx = Math.round(lx);
    ly = Math.round(ly);

    Plots.autoMargin(gd, axName + '-range-selector', {
        x: opts.x,
        y: opts.y,
        l: width * FROM_TL[xanchor],
        r: width * FROM_BR[xanchor],
        b: height * FROM_BR[yanchor],
        t: height * FROM_TL[yanchor]
    });

    selector.attr('transform', 'translate(' + lx + ',' + ly + ')');
}

},{"../../constants/alignment":143,"../../lib":164,"../../lib/svg_text_utils":185,"../../plots/cartesian/axis_ids":209,"../../plots/plots":245,"../../registry":254,"../color":43,"../drawing":68,"../legend/anchor_utils":95,"./constants":111,"./get_update_object":114,"d3":6}],114:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

module.exports = function getUpdateObject(axisLayout, buttonLayout) {
    var axName = axisLayout._name;
    var update = {};

    if(buttonLayout.step === 'all') {
        update[axName + '.autorange'] = true;
    }
    else {
        var xrange = getXRange(axisLayout, buttonLayout);

        update[axName + '.range[0]'] = xrange[0];
        update[axName + '.range[1]'] = xrange[1];
    }

    return update;
};

function getXRange(axisLayout, buttonLayout) {
    var currentRange = axisLayout.range;
    var base = new Date(axisLayout.r2l(currentRange[1]));

    var step = buttonLayout.step,
        count = buttonLayout.count;

    var range0;

    switch(buttonLayout.stepmode) {
        case 'backward':
            range0 = axisLayout.l2r(+d3.time[step].utc.offset(base, -count));
            break;

        case 'todate':
            var base2 = d3.time[step].utc.offset(base, -count);

            range0 = axisLayout.l2r(+d3.time[step].utc.ceil(base2));
            break;
    }

    var range1 = currentRange[1];

    return [range0, range1];
}

},{"d3":6}],115:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'component',
    name: 'rangeselector',

    schema: {
        subplots: {
            xaxis: {rangeselector: require('./attributes')}
        }
    },

    layoutAttributes: require('./attributes'),
    handleDefaults: require('./defaults'),

    draw: require('./draw')
};

},{"./attributes":109,"./defaults":112,"./draw":113}],116:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = require('../color/attributes');

module.exports = {
    bgcolor: {
        valType: 'color',
        dflt: colorAttributes.background,
        
        editType: 'plot',
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttributes.defaultLine,
        
        editType: 'plot',
        
    },
    borderwidth: {
        valType: 'integer',
        dflt: 0,
        min: 0,
        
        editType: 'plot',
        
    },
    autorange: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}
        ],
        editType: 'calc',
        impliedEdits: {'autorange': false},
        
    },
    thickness: {
        valType: 'number',
        dflt: 0.15,
        min: 0,
        max: 1,
        
        editType: 'plot',
        
    },
    visible: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'calc',
        
    },
    editType: 'calc'
};

},{"../color/attributes":42}],117:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var listAxes = require('../../plots/cartesian/axis_ids').list;
var getAutoRange = require('../../plots/cartesian/autorange').getAutoRange;
var constants = require('./constants');

module.exports = function calcAutorange(gd) {
    var axes = listAxes(gd, 'x', true);

    // Compute new slider range using axis autorange if necessary.
    //
    // Copy back range to input range slider container to skip
    // this step in subsequent draw calls.

    for(var i = 0; i < axes.length; i++) {
        var ax = axes[i],
            opts = ax[constants.name];

        // Don't try calling getAutoRange if _min and _max are filled in.
        // This happens on updates where the calc step is skipped.

        if(opts && opts.visible && opts.autorange && ax._min.length && ax._max.length) {
            opts._input.autorange = true;
            opts._input.range = opts.range = getAutoRange(ax);
        }
    }
};

},{"../../plots/cartesian/autorange":205,"../../plots/cartesian/axis_ids":209,"./constants":118}],118:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {

    // attribute container name
    name: 'rangeslider',

    // class names

    containerClassName: 'rangeslider-container',
    bgClassName: 'rangeslider-bg',
    rangePlotClassName: 'rangeslider-rangeplot',

    maskMinClassName: 'rangeslider-mask-min',
    maskMaxClassName: 'rangeslider-mask-max',
    slideBoxClassName: 'rangeslider-slidebox',

    grabberMinClassName: 'rangeslider-grabber-min',
    grabAreaMinClassName: 'rangeslider-grabarea-min',
    handleMinClassName: 'rangeslider-handle-min',

    grabberMaxClassName: 'rangeslider-grabber-max',
    grabAreaMaxClassName: 'rangeslider-grabarea-max',
    handleMaxClassName: 'rangeslider-handle-max',

    maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis',
    maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis',

    // style constants

    maskColor: 'rgba(0,0,0,0.4)',
    maskOppAxisColor: 'rgba(0,0,0,0.2)',

    slideBoxFill: 'transparent',
    slideBoxCursor: 'ew-resize',

    grabAreaFill: 'transparent',
    grabAreaCursor: 'col-resize',
    grabAreaWidth: 10,

    handleWidth: 4,
    handleRadius: 1,
    handleStrokeWidth: 1,

    extraPad: 15
};

},{}],119:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var attributes = require('./attributes');
var oppAxisAttrs = require('./oppaxis_attributes');
var axisIds = require('../../plots/cartesian/axis_ids');

module.exports = function handleDefaults(layoutIn, layoutOut, axName) {
    var axIn = layoutIn[axName];
    var axOut = layoutOut[axName];

    if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return;

    // not super proud of this (maybe store _ in axis object instead
    if(!Lib.isPlainObject(axIn.rangeslider)) {
        axIn.rangeslider = {};
    }

    var containerIn = axIn.rangeslider;
    var containerOut = axOut.rangeslider = {};

    function coerce(attr, dflt) {
        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
    }

    function coerceRange(rangeContainerIn, rangeContainerOut, attr, dflt) {
        return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt);
    }

    var visible = coerce('visible');
    if(!visible) return;

    coerce('bgcolor', layoutOut.plot_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('thickness');

    axOut._rangesliderAutorange = coerce('autorange', !axOut.isValidRange(containerIn.range));
    coerce('range');

    var subplots = layoutOut._subplots;
    if(subplots) {
        var yIds = subplots.cartesian
            .filter(function(subplotId) {
                return subplotId.substr(0, subplotId.indexOf('y')) === axisIds.name2id(axName);
            })
            .map(function(subplotId) {
                return subplotId.substr(subplotId.indexOf('y'), subplotId.length);
            });
        var yNames = Lib.simpleMap(yIds, axisIds.id2name);
        for(var i = 0; i < yNames.length; i++) {
            var yName = yNames[i];

            var rangeContainerIn = containerIn[yName] || {};
            var rangeContainerOut = containerOut[yName] = {};

            var yAxOut = layoutOut[yName];

            var rangemodeDflt;
            if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) {
                rangemodeDflt = 'fixed';
            }

            var rangeMode = coerceRange(rangeContainerIn, rangeContainerOut, 'rangemode', rangemodeDflt);
            if(rangeMode !== 'match') {
                coerceRange(rangeContainerIn, rangeContainerOut, 'range', yAxOut.range.slice());
            }
            yAxOut._rangesliderAutorange = (rangeMode === 'auto');
        }
    }

    // to map back range slider (auto) range
    containerOut._input = containerIn;
};

},{"../../lib":164,"../../plots/cartesian/axis_ids":209,"./attributes":116,"./oppaxis_attributes":122}],120:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Plots = require('../../plots/plots');

var Lib = require('../../lib');
var Drawing = require('../drawing');
var Color = require('../color');
var Titles = require('../titles');

var Cartesian = require('../../plots/cartesian');
var Axes = require('../../plots/cartesian/axes');

var dragElement = require('../dragelement');
var setCursor = require('../../lib/setcursor');

var constants = require('./constants');

module.exports = function(gd) {
    var fullLayout = gd._fullLayout,
        rangeSliderData = makeRangeSliderData(fullLayout);

    /*
     * <g container />
     *  <rect bg />
     *  < .... range plot />
     *  <rect mask-min />
     *  <rect mask-max />
     *  <rect slidebox />
     *  <g grabber-min />
     *      <rect handle-min />
     *      <rect grabare-min />
     *  <g grabber-max />
     *      <rect handle-max />
     *      <rect grabare-max />
     *
     *  ...
     */

    function keyFunction(axisOpts) {
        return axisOpts._name;
    }

    var rangeSliders = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(rangeSliderData, keyFunction);

    rangeSliders.enter().append('g')
        .classed(constants.containerClassName, true)
        .attr('pointer-events', 'all');

    // remove exiting sliders and their corresponding clip paths
    rangeSliders.exit().each(function(axisOpts) {
        var rangeSlider = d3.select(this),
            opts = axisOpts[constants.name];

        rangeSlider.remove();
        fullLayout._topdefs.select('#' + opts._clipId).remove();
    });

    // remove push margin object(s)
    if(rangeSliders.exit().size()) clearPushMargins(gd);

    // return early if no range slider is visible
    if(rangeSliderData.length === 0) return;

    // for all present range sliders
    rangeSliders.each(function(axisOpts) {
        var rangeSlider = d3.select(this),
            opts = axisOpts[constants.name],
            oppAxisOpts = fullLayout[Axes.id2name(axisOpts.anchor)],
            oppAxisRangeOpts = opts[Axes.id2name(axisOpts.anchor)];

        // update range
        // Expand slider range to the axis range
        // TODO: what if the ranges are reversed?
        if(opts.range) {
            var outRange = opts.range;
            var axRange = axisOpts.range;

            outRange[0] = axisOpts.l2r(Math.min(axisOpts.r2l(outRange[0]), axisOpts.r2l(axRange[0])));
            outRange[1] = axisOpts.l2r(Math.max(axisOpts.r2l(outRange[1]), axisOpts.r2l(axRange[1])));
            opts._input.range = outRange.slice();
        }

        axisOpts.cleanRange('rangeslider.range');


        // update range slider dimensions

        var margin = fullLayout.margin;
        var graphSize = fullLayout._size;
        var domain = axisOpts.domain;
        var tickHeight = (axisOpts._boundingBox || {}).height || 0;

        var oppBottom = Infinity;
        var subplotData = Axes.getSubplots(gd, axisOpts);
        for(var i = 0; i < subplotData.length; i++) {
            var oppAxis = Axes.getFromId(gd, subplotData[i].substr(subplotData[i].indexOf('y')));
            oppBottom = Math.min(oppBottom, oppAxis.domain[0]);
        }

        opts._id = constants.name + axisOpts._id;
        opts._clipId = opts._id + '-' + fullLayout._uid;

        opts._width = graphSize.w * (domain[1] - domain[0]);
        opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness;
        opts._offsetShift = Math.floor(opts.borderwidth / 2);

        var x = Math.round(margin.l + (graphSize.w * domain[0]));

        var y = Math.round(
            graphSize.t + graphSize.h * (1 - oppBottom) +
            tickHeight +
            opts._offsetShift + constants.extraPad
        );

        rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')');

        // update data <--> pixel coordinate conversion methods

        var range0 = axisOpts.r2l(opts.range[0]),
            range1 = axisOpts.r2l(opts.range[1]),
            dist = range1 - range0;

        opts.p2d = function(v) {
            return (v / opts._width) * dist + range0;
        };

        opts.d2p = function(v) {
            return (v - range0) / dist * opts._width;
        };

        opts._rl = [range0, range1];

        if(oppAxisRangeOpts.rangemode !== 'match') {
            var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]),
                range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]),
                distOppAxis = range1OppAxis - range0OppAxis;

            opts.d2pOppAxis = function(v) {
                return (v - range0OppAxis) / distOppAxis * opts._height;
            };
        }

        // update inner nodes

        rangeSlider
            .call(drawBg, gd, axisOpts, opts)
            .call(addClipPath, gd, axisOpts, opts)
            .call(drawRangePlot, gd, axisOpts, opts)
            .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts)
            .call(drawSlideBox, gd, axisOpts, opts)
            .call(drawGrabbers, gd, axisOpts, opts);

        // setup drag element
        setupDragElement(rangeSlider, gd, axisOpts, opts);

        // update current range
        setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts);

        // title goes next to range slider instead of tick labels, so
        // just take it over and draw it from here
        if(axisOpts.side === 'bottom') {
            Titles.draw(gd, axisOpts._id + 'title', {
                propContainer: axisOpts,
                propName: axisOpts._name + '.title',
                placeholder: fullLayout._dfltTitle.x,
                attributes: {
                    x: axisOpts._offset + axisOpts._length / 2,
                    y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.titlefont.size,
                    'text-anchor': 'middle'
                }
            });
        }

        // update margins
        Plots.autoMargin(gd, opts._id, {
            x: domain[0],
            y: oppBottom,
            l: 0,
            r: 0,
            t: 0,
            b: opts._height + margin.b + tickHeight,
            pad: constants.extraPad + opts._offsetShift * 2
        });
    });
};

function makeRangeSliderData(fullLayout) {
    var axes = Axes.list({ _fullLayout: fullLayout }, 'x', true),
        name = constants.name,
        out = [];

    if(fullLayout._has('gl2d')) return out;

    for(var i = 0; i < axes.length; i++) {
        var ax = axes[i];

        if(ax[name] && ax[name].visible) out.push(ax);
    }

    return out;
}

function setupDragElement(rangeSlider, gd, axisOpts, opts) {
    var slideBox = rangeSlider.select('rect.' + constants.slideBoxClassName).node(),
        grabAreaMin = rangeSlider.select('rect.' + constants.grabAreaMinClassName).node(),
        grabAreaMax = rangeSlider.select('rect.' + constants.grabAreaMaxClassName).node();

    rangeSlider.on('mousedown', function() {
        var event = d3.event,
            target = event.target,
            startX = event.clientX,
            offsetX = startX - rangeSlider.node().getBoundingClientRect().left,
            minVal = opts.d2p(axisOpts._rl[0]),
            maxVal = opts.d2p(axisOpts._rl[1]);

        var dragCover = dragElement.coverSlip();

        dragCover.addEventListener('mousemove', mouseMove);
        dragCover.addEventListener('mouseup', mouseUp);

        function mouseMove(e) {
            var delta = +e.clientX - startX;
            var pixelMin, pixelMax, cursor;

            switch(target) {
                case slideBox:
                    cursor = 'ew-resize';
                    pixelMin = minVal + delta;
                    pixelMax = maxVal + delta;
                    break;

                case grabAreaMin:
                    cursor = 'col-resize';
                    pixelMin = minVal + delta;
                    pixelMax = maxVal;
                    break;

                case grabAreaMax:
                    cursor = 'col-resize';
                    pixelMin = minVal;
                    pixelMax = maxVal + delta;
                    break;

                default:
                    cursor = 'ew-resize';
                    pixelMin = offsetX;
                    pixelMax = offsetX + delta;
                    break;
            }

            if(pixelMax < pixelMin) {
                var tmp = pixelMax;
                pixelMax = pixelMin;
                pixelMin = tmp;
            }

            opts._pixelMin = pixelMin;
            opts._pixelMax = pixelMax;

            setCursor(d3.select(dragCover), cursor);
            setDataRange(rangeSlider, gd, axisOpts, opts);
        }

        function mouseUp() {
            dragCover.removeEventListener('mousemove', mouseMove);
            dragCover.removeEventListener('mouseup', mouseUp);
            Lib.removeElement(dragCover);
        }
    });
}

function setDataRange(rangeSlider, gd, axisOpts, opts) {

    function clamp(v) {
        return axisOpts.l2r(Lib.constrain(v, opts._rl[0], opts._rl[1]));
    }

    var dataMin = clamp(opts.p2d(opts._pixelMin)),
        dataMax = clamp(opts.p2d(opts._pixelMax));

    window.requestAnimationFrame(function() {
        Registry.call('relayout', gd, axisOpts._name + '.range', [dataMin, dataMax]);
    });
}

function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) {
    var hw2 = constants.handleWidth / 2;

    function clamp(v) {
        return Lib.constrain(v, 0, opts._width);
    }

    function clampOppAxis(v) {
        return Lib.constrain(v, 0, opts._height);
    }

    function clampHandle(v) {
        return Lib.constrain(v, -hw2, opts._width + hw2);
    }

    var pixelMin = clamp(opts.d2p(axisOpts._rl[0])),
        pixelMax = clamp(opts.d2p(axisOpts._rl[1]));

    rangeSlider.select('rect.' + constants.slideBoxClassName)
        .attr('x', pixelMin)
        .attr('width', pixelMax - pixelMin);

    rangeSlider.select('rect.' + constants.maskMinClassName)
        .attr('width', pixelMin);

    rangeSlider.select('rect.' + constants.maskMaxClassName)
        .attr('x', pixelMax)
        .attr('width', opts._width - pixelMax);

    if(oppAxisRangeOpts.rangemode !== 'match') {
        var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])),
            pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0]));

        rangeSlider.select('rect.' + constants.maskMinOppAxisClassName)
            .attr('x', pixelMin)
            .attr('height', pixelMinOppAxis)
            .attr('width', pixelMax - pixelMin);

        rangeSlider.select('rect.' + constants.maskMaxOppAxisClassName)
            .attr('x', pixelMin)
            .attr('y', pixelMaxOppAxis)
            .attr('height', opts._height - pixelMaxOppAxis)
            .attr('width', pixelMax - pixelMin);

        rangeSlider.select('rect.' + constants.slideBoxClassName)
            .attr('y', pixelMinOppAxis)
            .attr('height', pixelMaxOppAxis - pixelMinOppAxis);
    }

    // add offset for crispier corners
    // https://github.com/plotly/plotly.js/pull/1409
    var offset = 0.5;

    var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset,
        xMax = Math.round(clampHandle(pixelMax - hw2)) + offset;

    rangeSlider.select('g.' + constants.grabberMinClassName)
        .attr('transform', 'translate(' + xMin + ',' + offset + ')');

    rangeSlider.select('g.' + constants.grabberMaxClassName)
        .attr('transform', 'translate(' + xMax + ',' + offset + ')');
}

function drawBg(rangeSlider, gd, axisOpts, opts) {
    var bg = Lib.ensureSingle(rangeSlider, 'rect', constants.bgClassName, function(s) {
        s.attr({
            x: 0,
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    var borderCorrect = (opts.borderwidth % 2) === 0 ?
            opts.borderwidth :
            opts.borderwidth - 1;

    var offsetShift = -opts._offsetShift;
    var lw = Drawing.crispRound(gd, opts.borderwidth);

    bg.attr({
        width: opts._width + borderCorrect,
        height: opts._height + borderCorrect,
        transform: 'translate(' + offsetShift + ',' + offsetShift + ')',
        fill: opts.bgcolor,
        stroke: opts.bordercolor,
        'stroke-width': lw
    });
}

function addClipPath(rangeSlider, gd, axisOpts, opts) {
    var fullLayout = gd._fullLayout;

    var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) {
        s.append('rect').attr({ x: 0, y: 0 });
    });

    clipPath.select('rect').attr({
        width: opts._width,
        height: opts._height
    });
}

function drawRangePlot(rangeSlider, gd, axisOpts, opts) {
    var subplotData = Axes.getSubplots(gd, axisOpts),
        calcData = gd.calcdata;

    var rangePlots = rangeSlider.selectAll('g.' + constants.rangePlotClassName)
        .data(subplotData, Lib.identity);

    rangePlots.enter().append('g')
        .attr('class', function(id) { return constants.rangePlotClassName + ' ' + id; })
        .call(Drawing.setClipUrl, opts._clipId);

    rangePlots.order();

    rangePlots.exit().remove();

    var mainplotinfo;

    rangePlots.each(function(id, i) {
        var plotgroup = d3.select(this),
            isMainPlot = (i === 0);

        var oppAxisOpts = Axes.getFromId(gd, id, 'y'),
            oppAxisName = oppAxisOpts._name,
            oppAxisRangeOpts = opts[oppAxisName];

        var mockFigure = {
            data: [],
            layout: {
                xaxis: {
                    type: axisOpts.type,
                    domain: [0, 1],
                    range: opts.range.slice(),
                    calendar: axisOpts.calendar
                },
                width: opts._width,
                height: opts._height,
                margin: { t: 0, b: 0, l: 0, r: 0 }
            },
            _context: gd._context
        };

        mockFigure.layout[oppAxisName] = {
            type: oppAxisOpts.type,
            domain: [0, 1],
            range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(),
            calendar: oppAxisOpts.calendar
        };

        Plots.supplyDefaults(mockFigure);

        var xa = mockFigure._fullLayout.xaxis;
        var ya = mockFigure._fullLayout[oppAxisName];

        var plotinfo = {
            id: id,
            plotgroup: plotgroup,
            xaxis: xa,
            yaxis: ya,
            isRangePlot: true
        };

        if(isMainPlot) mainplotinfo = plotinfo;
        else {
            plotinfo.mainplot = 'xy';
            plotinfo.mainplotinfo = mainplotinfo;
        }

        Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id));
    });
}

function filterRangePlotCalcData(calcData, subplotId) {
    var out = [];

    for(var i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i],
            trace = calcTrace[0].trace;

        if(trace.xaxis + trace.yaxis === subplotId) {
            out.push(calcTrace);
        }
    }

    return out;
}

function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) {
    var maskMin = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinClassName, function(s) {
        s.attr({
            x: 0,
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    maskMin
        .attr('height', opts._height)
        .call(Color.fill, constants.maskColor);

    var maskMax = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxClassName, function(s) {
        s.attr({
            y: 0,
            'shape-rendering': 'crispEdges'
        });
    });

    maskMax
        .attr('height', opts._height)
        .call(Color.fill, constants.maskColor);

    // masks used for oppAxis zoom
    if(oppAxisRangeOpts.rangemode !== 'match') {
        var maskMinOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinOppAxisClassName, function(s) {
            s.attr({
                y: 0,
                'shape-rendering': 'crispEdges'
            });
        });

        maskMinOppAxis
            .attr('width', opts._width)
            .call(Color.fill, constants.maskOppAxisColor);

        var maskMaxOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxOppAxisClassName, function(s) {
            s.attr({
                y: 0,
                'shape-rendering': 'crispEdges'
            });
        });

        maskMaxOppAxis
            .attr('width', opts._width)
            .style('border-top', constants.maskOppBorder)
            .call(Color.fill, constants.maskOppAxisColor);
    }
}

function drawSlideBox(rangeSlider, gd, axisOpts, opts) {
    if(gd._context.staticPlot) return;

    var slideBox = Lib.ensureSingle(rangeSlider, 'rect', constants.slideBoxClassName, function(s) {
        s.attr({
            y: 0,
            cursor: constants.slideBoxCursor,
            'shape-rendering': 'crispEdges'
        });
    });

    slideBox.attr({
        height: opts._height,
        fill: constants.slideBoxFill
    });
}

function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
    // <g grabber />
    var grabberMin = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMinClassName);
    var grabberMax = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMaxClassName);

    // <g handle />
    var handleFixAttrs = {
        x: 0,
        width: constants.handleWidth,
        rx: constants.handleRadius,
        fill: Color.background,
        stroke: Color.defaultLine,
        'stroke-width': constants.handleStrokeWidth,
        'shape-rendering': 'crispEdges'
    };
    var handleDynamicAttrs = {
        y: Math.round(opts._height / 4),
        height: Math.round(opts._height / 2),
    };
    var handleMin = Lib.ensureSingle(grabberMin, 'rect', constants.handleMinClassName, function(s) {
        s.attr(handleFixAttrs);
    });
    handleMin.attr(handleDynamicAttrs);

    var handleMax = Lib.ensureSingle(grabberMax, 'rect', constants.handleMaxClassName, function(s) {
        s.attr(handleFixAttrs);
    });
    handleMax.attr(handleDynamicAttrs);

    // <g grabarea />
    if(gd._context.staticPlot) return;

    var grabAreaFixAttrs = {
        width: constants.grabAreaWidth,
        x: 0,
        y: 0,
        fill: constants.grabAreaFill,
        cursor: constants.grabAreaCursor
    };

    var grabAreaMin = Lib.ensureSingle(grabberMin, 'rect', constants.grabAreaMinClassName, function(s) {
        s.attr(grabAreaFixAttrs);
    });
    grabAreaMin.attr('height', opts._height);

    var grabAreaMax = Lib.ensureSingle(grabberMax, 'rect', constants.grabAreaMaxClassName, function(s) {
        s.attr(grabAreaFixAttrs);
    });
    grabAreaMax.attr('height', opts._height);
}

function clearPushMargins(gd) {
    var pushMargins = gd._fullLayout._pushmargin || {},
        keys = Object.keys(pushMargins);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        if(k.indexOf(constants.name) !== -1) {
            Plots.autoMargin(gd, k);
        }
    }
}

},{"../../lib":164,"../../lib/setcursor":183,"../../plots/cartesian":217,"../../plots/cartesian/axes":206,"../../plots/plots":245,"../../registry":254,"../color":43,"../dragelement":65,"../drawing":68,"../titles":136,"./constants":118,"d3":6}],121:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var attrs = require('./attributes');
var oppAxisAttrs = require('./oppaxis_attributes');

module.exports = {
    moduleType: 'component',
    name: 'rangeslider',

    schema: {
        subplots: {
            xaxis: {
                rangeslider: Lib.extendFlat({}, attrs, {
                    yaxis: oppAxisAttrs
                })
            }
        }
    },

    layoutAttributes: require('./attributes'),
    handleDefaults: require('./defaults'),
    calcAutorange: require('./calc_autorange'),
    draw: require('./draw')
};

},{"../../lib":164,"./attributes":116,"./calc_autorange":117,"./defaults":119,"./draw":120,"./oppaxis_attributes":122}],122:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    // not really a 'subplot' attribute container,
    // but this is the flag we use to denote attributes that
    // support yaxis, yaxis2, yaxis3, ... counters
    _isSubplotObj: true,

    rangemode: {
        valType: 'enumerated',
        values: ['auto', 'fixed', 'match'],
        dflt: 'match',
        
        editType: 'calc',
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'plot'},
            {valType: 'any', editType: 'plot'}
        ],
        editType: 'plot',
        
    },
    editType: 'calc'
};

},{}],123:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var annAttrs = require('../annotations/attributes');
var scatterLineAttrs = require('../../traces/scatter/attributes').line;
var dash = require('../drawing/attributes').dash;
var extendFlat = require('../../lib/extend').extendFlat;

module.exports = {
    _isLinkedToArray: 'shape',

    visible: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'calcIfAutorange+arraydraw',
        
    },

    type: {
        valType: 'enumerated',
        values: ['circle', 'rect', 'path', 'line'],
        
        editType: 'calcIfAutorange+arraydraw',
        
    },

    layer: {
        valType: 'enumerated',
        values: ['below', 'above'],
        dflt: 'above',
        
        editType: 'arraydraw',
        
    },

    xref: extendFlat({}, annAttrs.xref, {
        
    }),
    xsizemode: {
        valType: 'enumerated',
        values: ['scaled', 'pixel'],
        dflt: 'scaled',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    xanchor: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    x0: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    x1: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },

    yref: extendFlat({}, annAttrs.yref, {
        
    }),
    ysizemode: {
        valType: 'enumerated',
        values: ['scaled', 'pixel'],
        dflt: 'scaled',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    yanchor: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    y0: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },
    y1: {
        valType: 'any',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },

    path: {
        valType: 'string',
        
        editType: 'calcIfAutorange+arraydraw',
        
    },

    opacity: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 1,
        
        editType: 'arraydraw',
        
    },
    line: {
        color: extendFlat({}, scatterLineAttrs.color, {editType: 'arraydraw'}),
        width: extendFlat({}, scatterLineAttrs.width, {editType: 'calcIfAutorange+arraydraw'}),
        dash: extendFlat({}, dash, {editType: 'arraydraw'}),
        
        editType: 'calcIfAutorange+arraydraw'
    },
    fillcolor: {
        valType: 'color',
        dflt: 'rgba(0,0,0,0)',
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
};

},{"../../lib/extend":157,"../../traces/scatter/attributes":266,"../annotations/attributes":28,"../drawing/attributes":67}],124:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');

var constants = require('./constants');
var helpers = require('./helpers');


module.exports = function calcAutorange(gd) {
    var fullLayout = gd._fullLayout,
        shapeList = Lib.filterVisible(fullLayout.shapes);

    if(!shapeList.length || !gd._fullData.length) return;

    for(var i = 0; i < shapeList.length; i++) {
        var shape = shapeList[i];

        var ax, bounds;

        if(shape.xref !== 'paper') {
            var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0,
                vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1;
            ax = Axes.getFromId(gd, shape.xref);

            bounds = shapeBounds(ax, vx0, vx1, shape.path, constants.paramIsX);

            if(bounds) Axes.expand(ax, bounds, calcXPaddingOptions(shape));
        }

        if(shape.yref !== 'paper') {
            var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0,
                vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1;
            ax = Axes.getFromId(gd, shape.yref);

            bounds = shapeBounds(ax, vy0, vy1, shape.path, constants.paramIsY);
            if(bounds) Axes.expand(ax, bounds, calcYPaddingOptions(shape));
        }
    }
};

function calcXPaddingOptions(shape) {
    return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false);
}

function calcYPaddingOptions(shape) {
    return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true);
}

function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) {
    var ppad = lineWidth / 2,
        axisDirectionReverted = isYAxis;

    if(sizeMode === 'pixel') {
        var coords = path ?
          extractPathCoords(path, isYAxis ? constants.paramIsY : constants.paramIsX) :
          [v0, v1];
        var maxValue = Lib.aggNums(Math.max, null, coords),
            minValue = Lib.aggNums(Math.min, null, coords),
            beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad,
            afterPad = maxValue > 0 ? maxValue + ppad : ppad;

        return {
            ppad: ppad,
            ppadplus: axisDirectionReverted ? beforePad : afterPad,
            ppadminus: axisDirectionReverted ? afterPad : beforePad
        };
    } else {
        return {ppad: ppad};
    }
}

function extractPathCoords(path, paramsToUse) {
    var extractedCoordinates = [];

    var segments = path.match(constants.segmentRE);
    segments.forEach(function(segment) {
        var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn;
        if(relevantParamIdx === undefined) return;

        var params = segment.substr(1).match(constants.paramRE);
        if(!params || params.length < relevantParamIdx) return;

        extractedCoordinates.push(params[relevantParamIdx]);
    });

    return extractedCoordinates;
}

function shapeBounds(ax, v0, v1, path, paramsToUse) {
    var convertVal = (ax.type === 'category') ? ax.r2c : ax.d2c;

    if(v0 !== undefined) return [convertVal(v0), convertVal(v1)];
    if(!path) return;

    var min = Infinity,
        max = -Infinity,
        segments = path.match(constants.segmentRE),
        i,
        segment,
        drawnParam,
        params,
        val;

    if(ax.type === 'date') convertVal = helpers.decodeDate(convertVal);

    for(i = 0; i < segments.length; i++) {
        segment = segments[i];
        drawnParam = paramsToUse[segment.charAt(0)].drawn;
        if(drawnParam === undefined) continue;

        params = segments[i].substr(1).match(constants.paramRE);
        if(!params || params.length < drawnParam) continue;

        val = convertVal(params[drawnParam]);
        if(val < min) min = val;
        if(val > max) max = val;
    }
    if(max >= min) return [min, max];
}

},{"../../lib":164,"../../plots/cartesian/axes":206,"./constants":125,"./helpers":128}],125:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {
    segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
    paramRE: /[^\s,]+/g,

    // which numbers in each path segment are x (or y) values
    // drawn is which param is a drawn point, as opposed to a
    // control point (which doesn't count toward autorange.
    // TODO: this means curved paths could extend beyond the
    // autorange bounds. This is a bit tricky to get right
    // unless we revert to bounding boxes, but perhaps there's
    // a calculation we could do...)
    paramIsX: {
        M: {0: true, drawn: 0},
        L: {0: true, drawn: 0},
        H: {0: true, drawn: 0},
        V: {},
        Q: {0: true, 2: true, drawn: 2},
        C: {0: true, 2: true, 4: true, drawn: 4},
        T: {0: true, drawn: 0},
        S: {0: true, 2: true, drawn: 2},
        // A: {0: true, 5: true},
        Z: {}
    },

    paramIsY: {
        M: {1: true, drawn: 1},
        L: {1: true, drawn: 1},
        H: {},
        V: {0: true, drawn: 0},
        Q: {1: true, 3: true, drawn: 3},
        C: {1: true, 3: true, 5: true, drawn: 5},
        T: {1: true, drawn: 1},
        S: {1: true, 3: true, drawn: 5},
        // A: {1: true, 6: true},
        Z: {}
    },

    numParams: {
        M: 2,
        L: 2,
        H: 1,
        V: 1,
        Q: 4,
        C: 6,
        T: 2,
        S: 4,
        // A: 7,
        Z: 0
    }
};

},{}],126:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var handleArrayContainerDefaults = require('../../plots/array_container_defaults');
var handleShapeDefaults = require('./shape_defaults');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
    var opts = {
        name: 'shapes',
        handleItemDefaults: handleShapeDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};

},{"../../plots/array_container_defaults":202,"./shape_defaults":130}],127:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');
var Color = require('../color');
var Drawing = require('../drawing');

var dragElement = require('../dragelement');
var setCursor = require('../../lib/setcursor');

var constants = require('./constants');
var helpers = require('./helpers');


// Shapes are stored in gd.layout.shapes, an array of objects
// index can point to one item in this array,
//  or non-numeric to simply add a new one
//  or -1 to modify all existing
// opt can be the full options object, or one key (to be set to value)
//  or undefined to simply redraw
// if opt is blank, val can be 'add' or a full options object to add a new
//  annotation at that point in the array, or 'remove' to delete this one

module.exports = {
    draw: draw,
    drawOne: drawOne
};

function draw(gd) {
    var fullLayout = gd._fullLayout;

    // Remove previous shapes before drawing new in shapes in fullLayout.shapes
    fullLayout._shapeUpperLayer.selectAll('path').remove();
    fullLayout._shapeLowerLayer.selectAll('path').remove();

    for(var k in fullLayout._plots) {
        var shapelayer = fullLayout._plots[k].shapelayer;
        if(shapelayer) shapelayer.selectAll('path').remove();
    }

    for(var i = 0; i < fullLayout.shapes.length; i++) {
        if(fullLayout.shapes[i].visible) {
            drawOne(gd, i);
        }
    }

    // may need to resurrect this if we put text (LaTeX) in shapes
    // return Plots.previousPromises(gd);
}

function drawOne(gd, index) {
    // remove the existing shape if there is one.
    // because indices can change, we need to look in all shape layers
    gd._fullLayout._paperdiv
        .selectAll('.shapelayer [data-index="' + index + '"]')
        .remove();

    var optionsIn = (gd.layout.shapes || [])[index],
        options = gd._fullLayout.shapes[index];

    // this shape is gone - quit now after deleting it
    // TODO: use d3 idioms instead of deleting and redrawing every time
    if(!optionsIn || options.visible === false) return;

    if(options.layer !== 'below') {
        drawShape(gd._fullLayout._shapeUpperLayer);
    }
    else if(options.xref === 'paper' || options.yref === 'paper') {
        drawShape(gd._fullLayout._shapeLowerLayer);
    }
    else {
        var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
        if(plotinfo) {
            var mainPlot = plotinfo.mainplotinfo || plotinfo;
            drawShape(mainPlot.shapelayer);
        }
        else {
            // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist.
            // This can happen if you reference the shape to an x / y axis combination
            // that doesn't have any data on it (and layer is below)
            drawShape(gd._fullLayout._shapeLowerLayer);
        }
    }

    function drawShape(shapeLayer) {
        var attrs = {
                'data-index': index,
                'fill-rule': 'evenodd',
                d: getPathString(gd, options)
            },
            lineColor = options.line.width ?
                options.line.color : 'rgba(0,0,0,0)';

        var path = shapeLayer.append('path')
            .attr(attrs)
            .style('opacity', options.opacity)
            .call(Color.stroke, lineColor)
            .call(Color.fill, options.fillcolor)
            .call(Drawing.dashLine, options.line.dash, options.line.width);

        // note that for layer="below" the clipAxes can be different from the
        // subplot we're drawing this in. This could cause problems if the shape
        // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452
        var clipAxes = (options.xref + options.yref).replace(/paper/g, '');

        path.call(Drawing.setClipUrl, clipAxes ?
            ('clip' + gd._fullLayout._uid + clipAxes) :
            null
        );

        if(gd._context.edits.shapePosition) setupDragElement(gd, path, options, index);
    }
}

function setupDragElement(gd, shapePath, shapeOptions, index) {
    var MINWIDTH = 10,
        MINHEIGHT = 10;

    var xPixelSized = shapeOptions.xsizemode === 'pixel',
        yPixelSized = shapeOptions.ysizemode === 'pixel';

    var update;
    var x0, y0, x1, y1, xAnchor, yAnchor, astrX0, astrY0, astrX1, astrY1, astrXAnchor, astrYAnchor;
    var n0, s0, w0, e0, astrN, astrS, astrW, astrE, optN, optS, optW, optE;
    var pathIn, astrPath;

    var xa, ya, x2p, y2p, p2x, p2y;

    var dragOptions = {
            element: shapePath.node(),
            gd: gd,
            prepFn: startDrag,
            doneFn: endDrag
        },
        dragMode;

    dragElement.init(dragOptions);

    shapePath.node().onmousemove = updateDragMode;

    function updateDragMode(evt) {
        // element might not be on screen at time of setup,
        // so obtain bounding box here
        var dragBBox = dragOptions.element.getBoundingClientRect();

        // choose 'move' or 'resize'
        // based on initial position of cursor within the drag element
        var w = dragBBox.right - dragBBox.left,
            h = dragBBox.bottom - dragBBox.top,
            x = evt.clientX - dragBBox.left,
            y = evt.clientY - dragBBox.top,
            cursor = (w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ?
                dragElement.getCursor(x / w, 1 - y / h) :
                'move';

        setCursor(shapePath, cursor);

        // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w'
        dragMode = cursor.split('-')[0];
    }

    function startDrag(evt) {
        // setup conversion functions
        xa = Axes.getFromId(gd, shapeOptions.xref);
        ya = Axes.getFromId(gd, shapeOptions.yref);

        x2p = helpers.getDataToPixel(gd, xa);
        y2p = helpers.getDataToPixel(gd, ya, true);
        p2x = helpers.getPixelToData(gd, xa);
        p2y = helpers.getPixelToData(gd, ya, true);

        // setup update strings and initial values
        var astr = 'shapes[' + index + ']';

        if(xPixelSized) {
            xAnchor = x2p(shapeOptions.xanchor);
            astrXAnchor = astr + '.xanchor';
        }
        if(yPixelSized) {
            yAnchor = y2p(shapeOptions.yanchor);
            astrYAnchor = astr + '.yanchor';
        }

        if(shapeOptions.type === 'path') {
            pathIn = shapeOptions.path;
            astrPath = astr + '.path';
        }
        else {
            x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0);
            y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0);
            x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1);
            y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1);

            astrX0 = astr + '.x0';
            astrY0 = astr + '.y0';
            astrX1 = astr + '.x1';
            astrY1 = astr + '.y1';
        }

        if(x0 < x1) {
            w0 = x0; astrW = astr + '.x0'; optW = 'x0';
            e0 = x1; astrE = astr + '.x1'; optE = 'x1';
        }
        else {
            w0 = x1; astrW = astr + '.x1'; optW = 'x1';
            e0 = x0; astrE = astr + '.x0'; optE = 'x0';
        }

        // For fixed size shapes take opposing direction of y-axis into account.
        // Hint: For data sized shapes this is done by the y2p function.
        if((!yPixelSized && y0 < y1) || (yPixelSized && y0 > y1)) {
            n0 = y0; astrN = astr + '.y0'; optN = 'y0';
            s0 = y1; astrS = astr + '.y1'; optS = 'y1';
        }
        else {
            n0 = y1; astrN = astr + '.y1'; optN = 'y1';
            s0 = y0; astrS = astr + '.y0'; optS = 'y0';
        }

        update = {};

        // setup dragMode and the corresponding handler
        updateDragMode(evt);
        dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape;
    }

    function endDrag() {
        setCursor(shapePath);
        Registry.call('relayout', gd, update);
    }

    function moveShape(dx, dy) {
        if(shapeOptions.type === 'path') {
            var noOp = function(coord) { return coord; },
                moveX = noOp,
                moveY = noOp;

            if(xPixelSized) {
                update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx);
            } else {
                moveX = function moveX(x) { return p2x(x2p(x) + dx); };
                if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
            }

            if(yPixelSized) {
                update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy);
            } else {
                moveY = function moveY(y) { return p2y(y2p(y) + dy); };
                if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
            }

            shapeOptions.path = movePath(pathIn, moveX, moveY);
            update[astrPath] = shapeOptions.path;
        }
        else {
            if(xPixelSized) {
                update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx);
            } else {
                update[astrX0] = shapeOptions.x0 = p2x(x0 + dx);
                update[astrX1] = shapeOptions.x1 = p2x(x1 + dx);
            }

            if(yPixelSized) {
                update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy);
            } else {
                update[astrY0] = shapeOptions.y0 = p2y(y0 + dy);
                update[astrY1] = shapeOptions.y1 = p2y(y1 + dy);
            }
        }

        shapePath.attr('d', getPathString(gd, shapeOptions));
    }

    function resizeShape(dx, dy) {
        if(shapeOptions.type === 'path') {
            // TODO: implement path resize
            var noOp = function(coord) { return coord; },
                moveX = noOp,
                moveY = noOp;

            if(xPixelSized) {
                update[astrXAnchor] = shapeOptions.xanchor = p2x(xAnchor + dx);
            } else {
                moveX = function moveX(x) { return p2x(x2p(x) + dx); };
                if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
            }

            if(yPixelSized) {
                update[astrYAnchor] = shapeOptions.yanchor = p2y(yAnchor + dy);
            } else {
                moveY = function moveY(y) { return p2y(y2p(y) + dy); };
                if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
            }

            shapeOptions.path = movePath(pathIn, moveX, moveY);
            update[astrPath] = shapeOptions.path;
        }
        else {
            var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0,
                newS = (~dragMode.indexOf('s')) ? s0 + dy : s0,
                newW = (~dragMode.indexOf('w')) ? w0 + dx : w0,
                newE = (~dragMode.indexOf('e')) ? e0 + dx : e0;

            // Do things in opposing direction for y-axis.
            // Hint: for data-sized shapes the reversal of axis direction is done in p2y.
            if(~dragMode.indexOf('n') && yPixelSized) newN = n0 - dy;
            if(~dragMode.indexOf('s') && yPixelSized) newS = s0 - dy;

            // Update shape eventually. Again, be aware of the
            // opposing direction of the y-axis of fixed size shapes.
            if((!yPixelSized && newS - newN > MINHEIGHT) ||
              (yPixelSized && newN - newS > MINHEIGHT)) {
                update[astrN] = shapeOptions[optN] = yPixelSized ? newN : p2y(newN);
                update[astrS] = shapeOptions[optS] = yPixelSized ? newS : p2y(newS);
            }
            if(newE - newW > MINWIDTH) {
                update[astrW] = shapeOptions[optW] = xPixelSized ? newW : p2x(newW);
                update[astrE] = shapeOptions[optE] = xPixelSized ? newE : p2x(newE);
            }
        }

        shapePath.attr('d', getPathString(gd, shapeOptions));
    }
}

function getPathString(gd, options) {
    var type = options.type,
        xa = Axes.getFromId(gd, options.xref),
        ya = Axes.getFromId(gd, options.yref),
        gs = gd._fullLayout._size,
        x2r, x2p, y2r, y2p,
        x0, x1, y0, y1;

    if(xa) {
        x2r = helpers.shapePositionToRange(xa);
        x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); };
    }
    else {
        x2p = function(v) { return gs.l + gs.w * v; };
    }

    if(ya) {
        y2r = helpers.shapePositionToRange(ya);
        y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); };
    }
    else {
        y2p = function(v) { return gs.t + gs.h * (1 - v); };
    }

    if(type === 'path') {
        if(xa && xa.type === 'date') x2p = helpers.decodeDate(x2p);
        if(ya && ya.type === 'date') y2p = helpers.decodeDate(y2p);
        return convertPath(options, x2p, y2p);
    }

    if(options.xsizemode === 'pixel') {
        var xAnchorPos = x2p(options.xanchor);
        x0 = xAnchorPos + options.x0;
        x1 = xAnchorPos + options.x1;
    }
    else {
        x0 = x2p(options.x0);
        x1 = x2p(options.x1);
    }

    if(options.ysizemode === 'pixel') {
        var yAnchorPos = y2p(options.yanchor);
        y0 = yAnchorPos - options.y0;
        y1 = yAnchorPos - options.y1;
    }
    else {
        y0 = y2p(options.y0);
        y1 = y2p(options.y1);
    }

    if(type === 'line') return 'M' + x0 + ',' + y0 + 'L' + x1 + ',' + y1;
    if(type === 'rect') return 'M' + x0 + ',' + y0 + 'H' + x1 + 'V' + y1 + 'H' + x0 + 'Z';
    // circle
    var cx = (x0 + x1) / 2,
        cy = (y0 + y1) / 2,
        rx = Math.abs(cx - x0),
        ry = Math.abs(cy - y0),
        rArc = 'A' + rx + ',' + ry,
        rightPt = (cx + rx) + ',' + cy,
        topPt = cx + ',' + (cy - ry);
    return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt +
        rArc + ' 0 0,1 ' + rightPt + 'Z';
}


function convertPath(options, x2p, y2p) {
    var pathIn = options.path,
        xSizemode = options.xsizemode,
        ySizemode = options.ysizemode,
        xAnchor = options.xanchor,
        yAnchor = options.yanchor;


    return pathIn.replace(constants.segmentRE, function(segment) {
        var paramNumber = 0,
            segmentType = segment.charAt(0),
            xParams = constants.paramIsX[segmentType],
            yParams = constants.paramIsY[segmentType],
            nParams = constants.numParams[segmentType];

        var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
            if(xParams[paramNumber]) {
                if(xSizemode === 'pixel') param = x2p(xAnchor) + Number(param);
                else param = x2p(param);
            }
            else if(yParams[paramNumber]) {
                if(ySizemode === 'pixel') param = y2p(yAnchor) - Number(param);
                else param = y2p(param);
            }
            paramNumber++;

            if(paramNumber > nParams) param = 'X';
            return param;
        });

        if(paramNumber > nParams) {
            paramString = paramString.replace(/[\s,]*X.*/, '');
            Lib.log('Ignoring extra params in segment ' + segment);
        }

        return segmentType + paramString;
    });
}

function movePath(pathIn, moveX, moveY) {
    return pathIn.replace(constants.segmentRE, function(segment) {
        var paramNumber = 0,
            segmentType = segment.charAt(0),
            xParams = constants.paramIsX[segmentType],
            yParams = constants.paramIsY[segmentType],
            nParams = constants.numParams[segmentType];

        var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
            if(paramNumber >= nParams) return param;

            if(xParams[paramNumber]) param = moveX(param);
            else if(yParams[paramNumber]) param = moveY(param);

            paramNumber++;

            return param;
        });

        return segmentType + paramString;
    });
}

},{"../../lib":164,"../../lib/setcursor":183,"../../plots/cartesian/axes":206,"../../registry":254,"../color":43,"../dragelement":65,"../drawing":68,"./constants":125,"./helpers":128}],128:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// special position conversion functions... category axis positions can't be
// specified by their data values, because they don't make a continuous mapping.
// so these have to be specified in terms of the category serial numbers,
// but can take fractional values. Other axis types we specify position based on
// the actual data values.
// TODO: in V2.0 (when log axis ranges are in data units) range and shape position
// will be identical, so rangeToShapePosition and shapePositionToRange can be
// removed entirely.

exports.rangeToShapePosition = function(ax) {
    return (ax.type === 'log') ? ax.r2d : function(v) { return v; };
};

exports.shapePositionToRange = function(ax) {
    return (ax.type === 'log') ? ax.d2r : function(v) { return v; };
};

exports.decodeDate = function(convertToPx) {
    return function(v) {
        if(v.replace) v = v.replace('_', ' ');
        return convertToPx(v);
    };
};

exports.encodeDate = function(convertToDate) {
    return function(v) { return convertToDate(v).replace(' ', '_'); };
};

exports.getDataToPixel = function(gd, axis, isVertical) {
    var gs = gd._fullLayout._size,
        dataToPixel;

    if(axis) {
        var d2r = exports.shapePositionToRange(axis);

        dataToPixel = function(v) {
            return axis._offset + axis.r2p(d2r(v, true));
        };

        if(axis.type === 'date') dataToPixel = exports.decodeDate(dataToPixel);
    }
    else if(isVertical) {
        dataToPixel = function(v) { return gs.t + gs.h * (1 - v); };
    }
    else {
        dataToPixel = function(v) { return gs.l + gs.w * v; };
    }

    return dataToPixel;
};

exports.getPixelToData = function(gd, axis, isVertical) {
    var gs = gd._fullLayout._size,
        pixelToData;

    if(axis) {
        var r2d = exports.rangeToShapePosition(axis);
        pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); };
    }
    else if(isVertical) {
        pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; };
    }
    else {
        pixelToData = function(p) { return (p - gs.l) / gs.w; };
    }

    return pixelToData;
};

},{}],129:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var drawModule = require('./draw');

module.exports = {
    moduleType: 'component',
    name: 'shapes',

    layoutAttributes: require('./attributes'),
    supplyLayoutDefaults: require('./defaults'),
    includeBasePlot: require('../../plots/cartesian/include_components')('shapes'),

    calcAutorange: require('./calc_autorange'),
    draw: drawModule.draw,
    drawOne: drawModule.drawOne
};

},{"../../plots/cartesian/include_components":216,"./attributes":123,"./calc_autorange":124,"./defaults":126,"./draw":127}],130:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var Axes = require('../../plots/cartesian/axes');

var attributes = require('./attributes');
var helpers = require('./helpers');


module.exports = function handleShapeDefaults(shapeIn, shapeOut, fullLayout, opts, itemOpts) {
    opts = opts || {};
    itemOpts = itemOpts || {};

    function coerce(attr, dflt) {
        return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt);
    }

    var visible = coerce('visible', !itemOpts.itemIsNotPlainObject);

    if(!visible) return shapeOut;

    coerce('layer');
    coerce('opacity');
    coerce('fillcolor');
    coerce('line.color');
    coerce('line.width');
    coerce('line.dash');

    var dfltType = shapeIn.path ? 'path' : 'rect',
        shapeType = coerce('type', dfltType),
        xSizeMode = coerce('xsizemode'),
        ySizeMode = coerce('ysizemode');

    // positioning
    var axLetters = ['x', 'y'];
    for(var i = 0; i < 2; i++) {
        var axLetter = axLetters[i],
            attrAnchor = axLetter + 'anchor',
            sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode,
            gdMock = {_fullLayout: fullLayout},
            ax,
            pos2r,
            r2pos;

        // xref, yref
        var axRef = Axes.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper');

        if(axRef !== 'paper') {
            ax = Axes.getFromId(gdMock, axRef);
            r2pos = helpers.rangeToShapePosition(ax);
            pos2r = helpers.shapePositionToRange(ax);
        }
        else {
            pos2r = r2pos = Lib.identity;
        }

        // Coerce x0, x1, y0, y1
        if(shapeType !== 'path') {
            var dflt0 = 0.25,
                dflt1 = 0.75;

            // hack until V2.0 when log has regular range behavior - make it look like other
            // ranges to send to coerce, then put it back after
            // this is all to give reasonable default position behavior on log axes, which is
            // a pretty unimportant edge case so we could just ignore this.
            var attr0 = axLetter + '0',
                attr1 = axLetter + '1',
                in0 = shapeIn[attr0],
                in1 = shapeIn[attr1];
            shapeIn[attr0] = pos2r(shapeIn[attr0], true);
            shapeIn[attr1] = pos2r(shapeIn[attr1], true);

            if(sizeMode === 'pixel') {
                coerce(attr0, 0);
                coerce(attr1, 10);
            } else {
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0);
                Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1);
            }

            // hack part 2
            shapeOut[attr0] = r2pos(shapeOut[attr0]);
            shapeOut[attr1] = r2pos(shapeOut[attr1]);
            shapeIn[attr0] = in0;
            shapeIn[attr1] = in1;
        }

        // Coerce xanchor and yanchor
        if(sizeMode === 'pixel') {
            // Hack for log axis described above
            var inAnchor = shapeIn[attrAnchor];
            shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);

            Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25);

            // Hack part 2
            shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
            shapeIn[attrAnchor] = inAnchor;
        }
    }

    if(shapeType === 'path') {
        coerce('path');
    }
    else {
        Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']);
    }

    return shapeOut;
};

},{"../../lib":164,"../../plots/cartesian/axes":206,"./attributes":123,"./helpers":128}],131:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('../../plots/font_attributes');
var padAttrs = require('../../plots/pad_attributes');
var extendDeepAll = require('../../lib/extend').extendDeepAll;
var overrideAll = require('../../plot_api/edit_types').overrideAll;
var animationAttrs = require('../../plots/animation_attributes');
var constants = require('./constants');

var stepsAttrs = {
    _isLinkedToArray: 'step',

    method: {
        valType: 'enumerated',
        values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
        dflt: 'restyle',
        
        
    },
    args: {
        valType: 'info_array',
        
        freeLength: true,
        items: [
            { valType: 'any' },
            { valType: 'any' },
            { valType: 'any' }
        ],
        
    },
    label: {
        valType: 'string',
        
        
    },
    value: {
        valType: 'string',
        
        
    },
    execute: {
        valType: 'boolean',
        
        dflt: true,
        
    }
};

module.exports = overrideAll({
    _isLinkedToArray: 'slider',

    visible: {
        valType: 'boolean',
        
        dflt: true,
        
    },

    active: {
        valType: 'number',
        
        min: 0,
        dflt: 0,
        
    },

    steps: stepsAttrs,

    lenmode: {
        valType: 'enumerated',
        values: ['fraction', 'pixels'],
        
        dflt: 'fraction',
        
    },
    len: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 0,
        
        
    },
    pad: extendDeepAll({}, padAttrs, {
        
    }, {t: {dflt: 20}}),
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'left',
        
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 0,
        
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'top',
        
        
    },

    transition: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 150,
            
        },
        easing: {
            valType: 'enumerated',
            values: animationAttrs.transition.easing.values,
            
            dflt: 'cubic-in-out',
            
        }
    },

    currentvalue: {
        visible: {
            valType: 'boolean',
            
            dflt: true,
            
        },

        xanchor: {
            valType: 'enumerated',
            values: ['left', 'center', 'right'],
            dflt: 'left',
            
            
        },

        offset: {
            valType: 'number',
            dflt: 10,
            
            
        },

        prefix: {
            valType: 'string',
            
            
        },

        suffix: {
            valType: 'string',
            
            
        },

        font: fontAttrs({
            
        })
    },

    font: fontAttrs({
        
    }),

    activebgcolor: {
        valType: 'color',
        
        dflt: constants.gripBgActiveColor,
        
    },
    bgcolor: {
        valType: 'color',
        
        dflt: constants.railBgColor,
        
    },
    bordercolor: {
        valType: 'color',
        dflt: constants.railBorderColor,
        
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: constants.railBorderWidth,
        
        
    },
    ticklen: {
        valType: 'number',
        min: 0,
        dflt: constants.tickLength,
        
        
    },
    tickcolor: {
        valType: 'color',
        dflt: constants.tickColor,
        
        
    },
    tickwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        
    },
    minorticklen: {
        valType: 'number',
        min: 0,
        dflt: constants.minorTickLength,
        
        
    }
}, 'arraydraw', 'from-root');

},{"../../lib/extend":157,"../../plot_api/edit_types":191,"../../plots/animation_attributes":201,"../../plots/font_attributes":232,"../../plots/pad_attributes":244,"./constants":132}],132:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {

    // layout attribute name
    name: 'sliders',

    // class names
    containerClassName: 'slider-container',
    groupClassName: 'slider-group',
    inputAreaClass: 'slider-input-area',
    railRectClass: 'slider-rail-rect',
    railTouchRectClass: 'slider-rail-touch-rect',
    gripRectClass: 'slider-grip-rect',
    tickRectClass: 'slider-tick-rect',
    inputProxyClass: 'slider-input-proxy',
    labelsClass: 'slider-labels',
    labelGroupClass: 'slider-label-group',
    labelClass: 'slider-label',
    currentValueClass: 'slider-current-value',

    railHeight: 5,

    // DOM attribute name in button group keeping track
    // of active update menu
    menuIndexAttrName: 'slider-active-index',

    // id root pass to Plots.autoMargin
    autoMarginIdRoot: 'slider-',

    // min item width / height
    minWidth: 30,
    minHeight: 30,

    // padding around item text
    textPadX: 40,

    // arrow offset off right edge
    arrowOffsetX: 4,

    railRadius: 2,
    railWidth: 5,
    railBorder: 4,
    railBorderWidth: 1,
    railBorderColor: '#bec8d9',
    railBgColor: '#f8fafc',

    // The distance of the rail from the edge of the touchable area
    // Slightly less than the step inset because of the curved edges
    // of the rail
    railInset: 8,

    // The distance from the extremal tick marks to the edge of the
    // touchable area. This is basically the same as the grip radius,
    // but for other styles it wouldn't really need to be.
    stepInset: 10,

    gripRadius: 10,
    gripWidth: 20,
    gripHeight: 20,
    gripBorder: 20,
    gripBorderWidth: 1,
    gripBorderColor: '#bec8d9',
    gripBgColor: '#f6f8fa',
    gripBgActiveColor: '#dbdde0',

    labelPadding: 8,
    labelOffset: 0,

    tickWidth: 1,
    tickColor: '#333',
    tickOffset: 25,
    tickLength: 7,

    minorTickOffset: 25,
    minorTickColor: '#333',
    minorTickLength: 4,

    // Extra space below the current value label:
    currentValuePadding: 8,
    currentValueInset: 0,
};

},{}],133:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var handleArrayContainerDefaults = require('../../plots/array_container_defaults');

var attributes = require('./attributes');
var constants = require('./constants');

var name = constants.name;
var stepAttrs = attributes.steps;


module.exports = function slidersDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: sliderDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};

function sliderDefaults(sliderIn, sliderOut, layoutOut) {

    function coerce(attr, dflt) {
        return Lib.coerce(sliderIn, sliderOut, attributes, attr, dflt);
    }

    var steps = stepsDefaults(sliderIn, sliderOut);

    var visible = coerce('visible', steps.length > 0);
    if(!visible) return;

    coerce('active');

    coerce('x');
    coerce('y');
    Lib.noneOrAll(sliderIn, sliderOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    coerce('len');
    coerce('lenmode');

    coerce('pad.t');
    coerce('pad.r');
    coerce('pad.b');
    coerce('pad.l');

    Lib.coerceFont(coerce, 'font', layoutOut.font);

    var currentValueIsVisible = coerce('currentvalue.visible');

    if(currentValueIsVisible) {
        coerce('currentvalue.xanchor');
        coerce('currentvalue.prefix');
        coerce('currentvalue.suffix');
        coerce('currentvalue.offset');

        Lib.coerceFont(coerce, 'currentvalue.font', sliderOut.font);
    }

    coerce('transition.duration');
    coerce('transition.easing');

    coerce('bgcolor');
    coerce('activebgcolor');
    coerce('bordercolor');
    coerce('borderwidth');
    coerce('ticklen');
    coerce('tickwidth');
    coerce('tickcolor');
    coerce('minorticklen');
}

function stepsDefaults(sliderIn, sliderOut) {
    var valuesIn = sliderIn.steps || [],
        valuesOut = sliderOut.steps = [];

    var valueIn, valueOut;

    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, stepAttrs, attr, dflt);
    }

    for(var i = 0; i < valuesIn.length; i++) {
        valueIn = valuesIn[i];
        valueOut = {};

        coerce('method');

        if(!Lib.isPlainObject(valueIn) || (valueOut.method !== 'skip' && !Array.isArray(valueIn.args))) {
            continue;
        }

        coerce('args');
        coerce('label', 'step-' + i);
        coerce('value', valueOut.label);
        coerce('execute');

        valuesOut.push(valueOut);
    }

    return valuesOut;
}

},{"../../lib":164,"../../plots/array_container_defaults":202,"./attributes":131,"./constants":132}],134:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Plots = require('../../plots/plots');
var Color = require('../color');
var Drawing = require('../drawing');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');
var anchorUtils = require('../legend/anchor_utils');

var constants = require('./constants');
var alignmentConstants = require('../../constants/alignment');
var LINE_SPACING = alignmentConstants.LINE_SPACING;
var FROM_TL = alignmentConstants.FROM_TL;
var FROM_BR = alignmentConstants.FROM_BR;

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout,
        sliderData = makeSliderData(fullLayout, gd);

    // draw a container for *all* sliders:
    var sliders = fullLayout._infolayer
        .selectAll('g.' + constants.containerClassName)
        .data(sliderData.length > 0 ? [0] : []);

    sliders.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'ew-resize');

    sliders.exit().remove();

    // If no more sliders, clear the margisn:
    if(sliders.exit().size()) clearPushMargins(gd);

    // Return early if no menus visible:
    if(sliderData.length === 0) return;

    var sliderGroups = sliders.selectAll('g.' + constants.groupClassName)
        .data(sliderData, keyFunction);

    sliderGroups.enter().append('g')
        .classed(constants.groupClassName, true);

    sliderGroups.exit().each(function(sliderOpts) {
        d3.select(this).remove();

        sliderOpts._commandObserver.remove();
        delete sliderOpts._commandObserver;

        Plots.autoMargin(gd, constants.autoMarginIdRoot + sliderOpts._index);
    });

    // Find the dimensions of the sliders:
    for(var i = 0; i < sliderData.length; i++) {
        var sliderOpts = sliderData[i];
        findDimensions(gd, sliderOpts);
    }

    sliderGroups.each(function(sliderOpts) {
        // If it has fewer than two options, it's not really a slider:
        if(sliderOpts.steps.length < 2) return;

        var gSlider = d3.select(this);

        computeLabelSteps(sliderOpts);

        Plots.manageCommandObserver(gd, sliderOpts, sliderOpts.steps, function(data) {
            // NB: Same as below. This is *not* always the same as sliderOpts since
            // if a new set of steps comes in, the reference in this callback would
            // be invalid. We need to refetch it from the slider group, which is
            // the join data that creates this slider. So if this slider still exists,
            // the group should be valid, *to the best of my knowledge.* If not,
            // we'd have to look it up by d3 data join index/key.
            var opts = gSlider.data()[0];

            if(opts.active === data.index) return;
            if(opts._dragging) return;

            setActive(gd, gSlider, opts, data.index, false, true);
        });

        drawSlider(gd, d3.select(this), sliderOpts);
    });
};

// This really only just filters by visibility:
function makeSliderData(fullLayout, gd) {
    var contOpts = fullLayout[constants.name],
        sliderData = [];

    for(var i = 0; i < contOpts.length; i++) {
        var item = contOpts[i];
        if(!item.visible || !item.steps.length) continue;
        item._gd = gd;
        sliderData.push(item);
    }

    return sliderData;
}

// This is set in the defaults step:
function keyFunction(opts) {
    return opts._index;
}

// Compute the dimensions (mutates sliderOpts):
function findDimensions(gd, sliderOpts) {
    var sliderLabels = Drawing.tester.selectAll('g.' + constants.labelGroupClass)
        .data(sliderOpts.steps);

    sliderLabels.enter().append('g')
        .classed(constants.labelGroupClass, true);

    // loop over fake buttons to find width / height
    var maxLabelWidth = 0;
    var labelHeight = 0;
    sliderLabels.each(function(stepOpts) {
        var labelGroup = d3.select(this);

        var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts);

        var textNode = text.node();
        if(textNode) {
            var bBox = Drawing.bBox(textNode);
            labelHeight = Math.max(labelHeight, bBox.height);
            maxLabelWidth = Math.max(maxLabelWidth, bBox.width);
        }
    });

    sliderLabels.remove();

    var dims = sliderOpts._dims = {};

    dims.inputAreaWidth = Math.max(
        constants.railWidth,
        constants.gripHeight
    );

    // calculate some overall dimensions - some of these are needed for
    // calculating the currentValue dimensions
    var graphSize = gd._fullLayout._size;
    dims.lx = graphSize.l + graphSize.w * sliderOpts.x;
    dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y);

    if(sliderOpts.lenmode === 'fraction') {
        // fraction:
        dims.outerLength = Math.round(graphSize.w * sliderOpts.len);
    } else {
        // pixels:
        dims.outerLength = sliderOpts.len;
    }

    // The length of the rail, *excluding* padding on either end:
    dims.inputAreaStart = 0;
    dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r);

    var textableInputLength = dims.inputAreaLength - 2 * constants.stepInset;
    var availableSpacePerLabel = textableInputLength / (sliderOpts.steps.length - 1);
    var computedSpacePerLabel = maxLabelWidth + constants.labelPadding;
    dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel));
    dims.labelHeight = labelHeight;

    // loop over all possible values for currentValue to find the
    // area we need for it
    dims.currentValueMaxWidth = 0;
    dims.currentValueHeight = 0;
    dims.currentValueTotalHeight = 0;
    dims.currentValueMaxLines = 1;

    if(sliderOpts.currentvalue.visible) {
        // Get the dimensions of the current value label:
        var dummyGroup = Drawing.tester.append('g');

        sliderLabels.each(function(stepOpts) {
            var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label);
            var curValSize = (curValPrefix.node() && Drawing.bBox(curValPrefix.node())) || {width: 0, height: 0};
            var lines = svgTextUtils.lineCount(curValPrefix);
            dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width));
            dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height));
            dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines);
        });

        dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset;

        dummyGroup.remove();
    }

    dims.height = dims.currentValueTotalHeight + constants.tickOffset + sliderOpts.ticklen + constants.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b;

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(sliderOpts)) {
        dims.lx -= dims.outerLength;
        xanchor = 'right';
    }
    if(anchorUtils.isCenterAnchor(sliderOpts)) {
        dims.lx -= dims.outerLength / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(anchorUtils.isBottomAnchor(sliderOpts)) {
        dims.ly -= dims.height;
        yanchor = 'bottom';
    }
    if(anchorUtils.isMiddleAnchor(sliderOpts)) {
        dims.ly -= dims.height / 2;
        yanchor = 'middle';
    }

    dims.outerLength = Math.ceil(dims.outerLength);
    dims.height = Math.ceil(dims.height);
    dims.lx = Math.round(dims.lx);
    dims.ly = Math.round(dims.ly);

    Plots.autoMargin(gd, constants.autoMarginIdRoot + sliderOpts._index, {
        x: sliderOpts.x,
        y: sliderOpts.y,
        l: dims.outerLength * FROM_TL[xanchor],
        r: dims.outerLength * FROM_BR[xanchor],
        b: dims.height * FROM_BR[yanchor],
        t: dims.height * FROM_TL[yanchor]
    });
}

function drawSlider(gd, sliderGroup, sliderOpts) {
    // This is related to the other long notes in this file regarding what happens
    // when slider steps disappear. This particular fix handles what happens when
    // the *current* slider step is removed. The drawing functions will error out
    // when they fail to find it, so the fix for now is that it will just draw the
    // slider in the first position but will not execute the command.
    if(sliderOpts.active >= sliderOpts.steps.length) {
        sliderOpts.active = 0;
    }

    // These are carefully ordered for proper z-ordering:
    sliderGroup
        .call(drawCurrentValue, sliderOpts)
        .call(drawRail, sliderOpts)
        .call(drawLabelGroup, sliderOpts)
        .call(drawTicks, sliderOpts)
        .call(drawTouchRect, gd, sliderOpts)
        .call(drawGrip, gd, sliderOpts);

    var dims = sliderOpts._dims;

    // Position the rectangle:
    Drawing.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t);

    sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), false);
    sliderGroup.call(drawCurrentValue, sliderOpts);

}

function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) {
    if(!sliderOpts.currentvalue.visible) return;

    var dims = sliderOpts._dims;
    var x0, textAnchor;

    switch(sliderOpts.currentvalue.xanchor) {
        case 'right':
            // This is anchored left and adjusted by the width of the longest label
            // so that the prefix doesn't move. The goal of this is to emphasize
            // what's actually changing and make the update less distracting.
            x0 = dims.inputAreaLength - constants.currentValueInset - dims.currentValueMaxWidth;
            textAnchor = 'left';
            break;
        case 'center':
            x0 = dims.inputAreaLength * 0.5;
            textAnchor = 'middle';
            break;
        default:
            x0 = constants.currentValueInset;
            textAnchor = 'left';
    }

    var text = Lib.ensureSingle(sliderGroup, 'text', constants.labelClass, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': textAnchor,
                'data-notex': 1
            });
    });

    var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : '';

    if(typeof valueOverride === 'string') {
        str += valueOverride;
    } else {
        var curVal = sliderOpts.steps[sliderOpts.active].label;
        str += curVal;
    }

    if(sliderOpts.currentvalue.suffix) {
        str += sliderOpts.currentvalue.suffix;
    }

    text.call(Drawing.font, sliderOpts.currentvalue.font)
        .text(str)
        .call(svgTextUtils.convertToTspans, sliderOpts._gd);

    var lines = svgTextUtils.lineCount(text);

    var y0 = (dims.currentValueMaxLines + 1 - lines) *
        sliderOpts.currentvalue.font.size * LINE_SPACING;

    svgTextUtils.positionText(text, x0, y0);

    return text;
}

function drawGrip(sliderGroup, gd, sliderOpts) {
    var grip = Lib.ensureSingle(sliderGroup, 'rect', constants.gripRectClass, function(s) {
        s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
            .style('pointer-events', 'all');
    });

    grip.attr({
        width: constants.gripWidth,
        height: constants.gripHeight,
        rx: constants.gripRadius,
        ry: constants.gripRadius,
    })
    .call(Color.stroke, sliderOpts.bordercolor)
    .call(Color.fill, sliderOpts.bgcolor)
    .style('stroke-width', sliderOpts.borderwidth + 'px');
}

function drawLabel(item, data, sliderOpts) {
    var text = Lib.ensureSingle(item, 'text', constants.labelClass, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': 'middle',
                'data-notex': 1
            });
    });

    text.call(Drawing.font, sliderOpts.font)
        .text(data.step.label)
        .call(svgTextUtils.convertToTspans, sliderOpts._gd);

    return text;
}

function drawLabelGroup(sliderGroup, sliderOpts) {
    var labels = Lib.ensureSingle(sliderGroup, 'g', constants.labelsClass);
    var dims = sliderOpts._dims;

    var labelItems = labels.selectAll('g.' + constants.labelGroupClass)
        .data(dims.labelSteps);

    labelItems.enter().append('g')
        .classed(constants.labelGroupClass, true);

    labelItems.exit().remove();

    labelItems.each(function(d) {
        var item = d3.select(this);

        item.call(drawLabel, d, sliderOpts);

        Drawing.setTranslate(item,
            normalizedValueToPosition(sliderOpts, d.fraction),
            constants.tickOffset +
                sliderOpts.ticklen +
                // position is the baseline of the top line of text only, even
                // if the label spans multiple lines
                sliderOpts.font.size * LINE_SPACING +
                constants.labelOffset +
                dims.currentValueTotalHeight
        );
    });

}

function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) {
    var quantizedPosition = Math.round(normalizedPosition * (sliderOpts.steps.length - 1));

    if(quantizedPosition !== sliderOpts.active) {
        setActive(gd, sliderGroup, sliderOpts, quantizedPosition, true, doTransition);
    }
}

function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) {
    var previousActive = sliderOpts.active;
    sliderOpts._input.active = sliderOpts.active = index;

    var step = sliderOpts.steps[sliderOpts.active];

    sliderGroup.call(setGripPosition, sliderOpts, sliderOpts.active / (sliderOpts.steps.length - 1), doTransition);
    sliderGroup.call(drawCurrentValue, sliderOpts);

    gd.emit('plotly_sliderchange', {
        slider: sliderOpts,
        step: sliderOpts.steps[sliderOpts.active],
        interaction: doCallback,
        previousActive: previousActive
    });

    if(step && step.method && doCallback) {
        if(sliderGroup._nextMethod) {
            // If we've already queued up an update, just overwrite it with the most recent:
            sliderGroup._nextMethod.step = step;
            sliderGroup._nextMethod.doCallback = doCallback;
            sliderGroup._nextMethod.doTransition = doTransition;
        } else {
            sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition};
            sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() {
                var _step = sliderGroup._nextMethod.step;
                if(!_step.method) return;

                if(_step.execute) {
                    Plots.executeAPICommand(gd, _step.method, _step.args);
                }

                sliderGroup._nextMethod = null;
                sliderGroup._nextMethodRaf = null;
            });
        }
    }
}

function attachGripEvents(item, gd, sliderGroup) {
    var node = sliderGroup.node();
    var $gd = d3.select(gd);

    // NB: This is *not* the same as sliderOpts itself! These callbacks
    // are in a closure so this array won't actually be correct if the
    // steps have changed since this was initialized. The sliderGroup,
    // however, has not changed since that *is* the slider, so it must
    // be present to receive mouse events.
    function getSliderOpts() {
        return sliderGroup.data()[0];
    }

    item.on('mousedown', function() {
        var sliderOpts = getSliderOpts();
        gd.emit('plotly_sliderstart', {slider: sliderOpts});

        var grip = sliderGroup.select('.' + constants.gripRectClass);

        d3.event.stopPropagation();
        d3.event.preventDefault();
        grip.call(Color.fill, sliderOpts.activebgcolor);

        var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
        handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true);
        sliderOpts._dragging = true;

        $gd.on('mousemove', function() {
            var sliderOpts = getSliderOpts();
            var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
            handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false);
        });

        $gd.on('mouseup', function() {
            var sliderOpts = getSliderOpts();
            sliderOpts._dragging = false;
            grip.call(Color.fill, sliderOpts.bgcolor);
            $gd.on('mouseup', null);
            $gd.on('mousemove', null);

            gd.emit('plotly_sliderend', {
                slider: sliderOpts,
                step: sliderOpts.steps[sliderOpts.active]
            });
        });
    });
}

function drawTicks(sliderGroup, sliderOpts) {
    var tick = sliderGroup.selectAll('rect.' + constants.tickRectClass)
        .data(sliderOpts.steps);
    var dims = sliderOpts._dims;

    tick.enter().append('rect')
        .classed(constants.tickRectClass, true);

    tick.exit().remove();

    tick.attr({
        width: sliderOpts.tickwidth + 'px',
        'shape-rendering': 'crispEdges'
    });

    tick.each(function(d, i) {
        var isMajor = i % dims.labelStride === 0;
        var item = d3.select(this);

        item
            .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen})
            .call(Color.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor);

        Drawing.setTranslate(item,
            normalizedValueToPosition(sliderOpts, i / (sliderOpts.steps.length - 1)) - 0.5 * sliderOpts.tickwidth,
            (isMajor ? constants.tickOffset : constants.minorTickOffset) + dims.currentValueTotalHeight
        );
    });

}

function computeLabelSteps(sliderOpts) {
    var dims = sliderOpts._dims;
    dims.labelSteps = [];
    var i0 = 0;
    var nsteps = sliderOpts.steps.length;

    for(var i = i0; i < nsteps; i += dims.labelStride) {
        dims.labelSteps.push({
            fraction: i / (nsteps - 1),
            step: sliderOpts.steps[i]
        });
    }
}

function setGripPosition(sliderGroup, sliderOpts, position, doTransition) {
    var grip = sliderGroup.select('rect.' + constants.gripRectClass);

    var x = normalizedValueToPosition(sliderOpts, position);

    // If this is true, then *this component* is already invoking its own command
    // and has triggered its own animation.
    if(sliderOpts._invokingCommand) return;

    var el = grip;
    if(doTransition && sliderOpts.transition.duration > 0) {
        el = el.transition()
            .duration(sliderOpts.transition.duration)
            .ease(sliderOpts.transition.easing);
    }

    // Drawing.setTranslate doesn't work here becasue of the transition duck-typing.
    // It's also not necessary because there are no other transitions to preserve.
    el.attr('transform', 'translate(' + (x - constants.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')');
}

// Convert a number from [0-1] to a pixel position relative to the slider group container:
function normalizedValueToPosition(sliderOpts, normalizedPosition) {
    var dims = sliderOpts._dims;
    return dims.inputAreaStart + constants.stepInset +
        (dims.inputAreaLength - 2 * constants.stepInset) * Math.min(1, Math.max(0, normalizedPosition));
}

// Convert a position relative to the slider group to a nubmer in [0, 1]
function positionToNormalizedValue(sliderOpts, position) {
    var dims = sliderOpts._dims;
    return Math.min(1, Math.max(0, (position - constants.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants.stepInset - 2 * dims.inputAreaStart)));
}

function drawTouchRect(sliderGroup, gd, sliderOpts) {
    var dims = sliderOpts._dims;
    var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railTouchRectClass, function(s) {
        s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
            .style('pointer-events', 'all');
    });

    rect.attr({
        width: dims.inputAreaLength,
        height: Math.max(dims.inputAreaWidth, constants.tickOffset + sliderOpts.ticklen + dims.labelHeight)
    })
        .call(Color.fill, sliderOpts.bgcolor)
        .attr('opacity', 0);

    Drawing.setTranslate(rect, 0, dims.currentValueTotalHeight);
}

function drawRail(sliderGroup, sliderOpts) {
    var dims = sliderOpts._dims;
    var computedLength = dims.inputAreaLength - constants.railInset * 2;
    var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railRectClass);

    rect.attr({
        width: computedLength,
        height: constants.railWidth,
        rx: constants.railRadius,
        ry: constants.railRadius,
        'shape-rendering': 'crispEdges'
    })
    .call(Color.stroke, sliderOpts.bordercolor)
    .call(Color.fill, sliderOpts.bgcolor)
    .style('stroke-width', sliderOpts.borderwidth + 'px');

    Drawing.setTranslate(rect,
        constants.railInset,
        (dims.inputAreaWidth - constants.railWidth) * 0.5 + dims.currentValueTotalHeight
    );
}

function clearPushMargins(gd) {
    var pushMargins = gd._fullLayout._pushmargin || {},
        keys = Object.keys(pushMargins);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        if(k.indexOf(constants.autoMarginIdRoot) !== -1) {
            Plots.autoMargin(gd, k);
        }
    }
}

},{"../../constants/alignment":143,"../../lib":164,"../../lib/svg_text_utils":185,"../../plots/plots":245,"../color":43,"../drawing":68,"../legend/anchor_utils":95,"./constants":132,"d3":6}],135:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var constants = require('./constants');

module.exports = {
    moduleType: 'component',
    name: constants.name,

    layoutAttributes: require('./attributes'),
    supplyLayoutDefaults: require('./defaults'),

    draw: require('./draw')
};

},{"./attributes":131,"./constants":132,"./defaults":133,"./draw":134}],136:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var Plots = require('../../plots/plots');
var Registry = require('../../registry');
var Lib = require('../../lib');
var Drawing = require('../drawing');
var Color = require('../color');
var svgTextUtils = require('../../lib/svg_text_utils');
var interactConstants = require('../../constants/interactions');

module.exports = {
    draw: draw
};

var numStripRE = / [XY][0-9]* /;

/**
 * Titles - (re)draw titles on the axes and plot:
 * @param {DOM element} gd - the graphDiv
 * @param {string} titleClass - the css class of this title
 * @param {object} options - how and what to draw
 *      propContainer - the layout object containing `title` and `titlefont`
 *          attributes that apply to this title
 *      propName - the full name of the title property (for Plotly.relayout)
 *      [traceIndex] - include only if this property applies to one trace
 *          (such as a colorbar title) - then editing pipes to Plotly.restyle
 *          instead of Plotly.relayout
 *      placeholder - placeholder text for an empty editable title
 *      [avoid] {object} - include if this title should move to avoid other elements
 *          selection - d3 selection of elements to avoid
 *          side - which direction to move if there is a conflict
 *          [offsetLeft] - if these elements are subject to a translation
 *              wrt the title element
 *          [offsetTop]
 *      attributes {object} - position and alignment attributes
 *          x - pixels
 *          y - pixels
 *          text-anchor - start|middle|end
 *      transform {object} - how to transform the title after positioning
 *          rotate - degrees
 *          offset - shift up/down in the rotated frame (unused?)
 *      containerGroup - if an svg <g> element already exists to hold this
 *          title, include here. Otherwise it will go in fullLayout._infolayer
 *
 *  @return {selection} d3 selection of title container group
 */
function draw(gd, titleClass, options) {
    var cont = options.propContainer;
    var prop = options.propName;
    var placeholder = options.placeholder;
    var traceIndex = options.traceIndex;
    var avoid = options.avoid || {};
    var attributes = options.attributes;
    var transform = options.transform;
    var group = options.containerGroup;

    var fullLayout = gd._fullLayout;
    var titlefont = cont.titlefont || {};
    var font = titlefont.family;
    var fontSize = titlefont.size;
    var fontColor = titlefont.color;

    var opacity = 1;
    var isplaceholder = false;
    var txt = (cont.title || '').trim();

    // only make this title editable if we positively identify its property
    // as one that has editing enabled.
    var editAttr;
    if(prop === 'title') editAttr = 'titleText';
    else if(prop.indexOf('axis') !== -1) editAttr = 'axisTitleText';
    else if(prop.indexOf('colorbar' !== -1)) editAttr = 'colorbarTitleText';
    var editable = gd._context.edits[editAttr];

    if(txt === '') opacity = 0;
    // look for placeholder text while stripping out numbers from eg X2, Y3
    // this is just for backward compatibility with the old version that had
    // "Click to enter X2 title" and may have gotten saved in some old plots,
    // we don't want this to show up when these are displayed.
    else if(txt.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ')) {
        opacity = 0.2;
        isplaceholder = true;
        if(!editable) txt = '';
    }

    var elShouldExist = txt || editable;

    if(!group) {
        group = Lib.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass);
    }

    var el = group.selectAll('text')
        .data(elShouldExist ? [0] : []);
    el.enter().append('text');
    el.text(txt)
        // this is hacky, but convertToTspans uses the class
        // to determine whether to rotate mathJax...
        // so we need to clear out any old class and put the
        // correct one (only relevant for colorbars, at least
        // for now) - ie don't use .classed
        .attr('class', titleClass);
    el.exit().remove();

    if(!elShouldExist) return group;

    function titleLayout(titleEl) {
        Lib.syncOrAsync([drawTitle, scootTitle], titleEl);
    }

    function drawTitle(titleEl) {
        var transformVal;

        if(transform) {
            transformVal = '';
            if(transform.rotate) {
                transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')';
            }
            if(transform.offset) {
                transformVal += 'translate(0, ' + transform.offset + ')';
            }
        } else {
            transformVal = null;
        }

        titleEl.attr('transform', transformVal);

        titleEl.style({
            'font-family': font,
            'font-size': d3.round(fontSize, 2) + 'px',
            fill: Color.rgb(fontColor),
            opacity: opacity * Color.opacity(fontColor),
            'font-weight': Plots.fontWeight
        })
        .attr(attributes)
        .call(svgTextUtils.convertToTspans, gd);

        return Plots.previousPromises(gd);
    }

    function scootTitle(titleElIn) {
        var titleGroup = d3.select(titleElIn.node().parentNode);

        if(avoid && avoid.selection && avoid.side && txt) {
            titleGroup.attr('transform', null);

            // move toward avoid.side (= left, right, top, bottom) if needed
            // can include pad (pixels, default 2)
            var shift = 0;
            var backside = {
                left: 'right',
                right: 'left',
                top: 'bottom',
                bottom: 'top'
            }[avoid.side];
            var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ?
                    -1 : 1;
            var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
            var titlebb = Drawing.bBox(titleGroup.node());
            var paperbb = {
                left: 0,
                top: 0,
                right: fullLayout.width,
                bottom: fullLayout.height
            };
            var maxshift = avoid.maxShift || (
                (paperbb[avoid.side] - titlebb[avoid.side]) *
                ((avoid.side === 'left' || avoid.side === 'top') ? -1 : 1));
            // Prevent the title going off the paper
            if(maxshift < 0) shift = maxshift;
            else {
                // so we don't have to offset each avoided element,
                // give the title the opposite offset
                var offsetLeft = avoid.offsetLeft || 0;
                var offsetTop = avoid.offsetTop || 0;
                titlebb.left -= offsetLeft;
                titlebb.right -= offsetLeft;
                titlebb.top -= offsetTop;
                titlebb.bottom -= offsetTop;

                // iterate over a set of elements (avoid.selection)
                // to avoid collisions with
                avoid.selection.each(function() {
                    var avoidbb = Drawing.bBox(this);

                    if(Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
                        shift = Math.max(shift, shiftSign * (
                            avoidbb[avoid.side] - titlebb[backside]) + pad);
                    }
                });
                shift = Math.min(maxshift, shift);
            }
            if(shift > 0 || maxshift < 0) {
                var shiftTemplate = {
                    left: [-shift, 0],
                    right: [shift, 0],
                    top: [0, -shift],
                    bottom: [0, shift]
                }[avoid.side];
                titleGroup.attr('transform',
                    'translate(' + shiftTemplate + ')');
            }
        }
    }

    el.call(titleLayout);

    function setPlaceholder() {
        opacity = 0;
        isplaceholder = true;
        el.text(placeholder)
            .on('mouseover.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.SHOW_PLACEHOLDER).style('opacity', 1);
            })
            .on('mouseout.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.HIDE_PLACEHOLDER).style('opacity', 0);
            });
    }

    if(editable) {
        if(!txt) setPlaceholder();
        else el.on('.opacity', null);

        el.call(svgTextUtils.makeEditable, {gd: gd})
            .on('edit', function(text) {
                if(traceIndex !== undefined) {
                    Registry.call('restyle', gd, prop, text, traceIndex);
                } else {
                    Registry.call('relayout', gd, prop, text);
                }
            })
            .on('cancel', function() {
                this.text(this.attr('data-unformatted'))
                    .call(titleLayout);
            })
            .on('input', function(d) {
                this.text(d || ' ')
                    .call(svgTextUtils.positionText, attributes.x, attributes.y);
            });
    }
    el.classed('js-placeholder', isplaceholder);

    return group;
}

},{"../../constants/interactions":144,"../../lib":164,"../../lib/svg_text_utils":185,"../../plots/plots":245,"../../registry":254,"../color":43,"../drawing":68,"d3":6,"fast-isnumeric":9}],137:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('../../plots/font_attributes');
var colorAttrs = require('../color/attributes');
var extendFlat = require('../../lib/extend').extendFlat;
var overrideAll = require('../../plot_api/edit_types').overrideAll;
var padAttrs = require('../../plots/pad_attributes');

var buttonsAttrs = {
    _isLinkedToArray: 'button',

    method: {
        valType: 'enumerated',
        values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
        dflt: 'restyle',
        
        
    },
    args: {
        valType: 'info_array',
        
        freeLength: true,
        items: [
            {valType: 'any'},
            {valType: 'any'},
            {valType: 'any'}
        ],
        
    },
    label: {
        valType: 'string',
        
        dflt: '',
        
    },
    execute: {
        valType: 'boolean',
        
        dflt: true,
        
    }
};

module.exports = overrideAll({
    _isLinkedToArray: 'updatemenu',
    _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],

    visible: {
        valType: 'boolean',
        
        
    },

    type: {
        valType: 'enumerated',
        values: ['dropdown', 'buttons'],
        dflt: 'dropdown',
        
        
    },

    direction: {
        valType: 'enumerated',
        values: ['left', 'right', 'up', 'down'],
        dflt: 'down',
        
        
    },

    active: {
        valType: 'integer',
        
        min: -1,
        dflt: 0,
        
    },

    showactive: {
        valType: 'boolean',
        
        dflt: true,
        
    },

    buttons: buttonsAttrs,

    x: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: -0.05,
        
        
    },
    xanchor: {
        valType: 'enumerated',
        values: ['auto', 'left', 'center', 'right'],
        dflt: 'right',
        
        
    },
    y: {
        valType: 'number',
        min: -2,
        max: 3,
        dflt: 1,
        
        
    },
    yanchor: {
        valType: 'enumerated',
        values: ['auto', 'top', 'middle', 'bottom'],
        dflt: 'top',
        
        
    },

    pad: extendFlat({}, padAttrs, {
        
    }),

    font: fontAttrs({
        
    }),

    bgcolor: {
        valType: 'color',
        
        
    },
    bordercolor: {
        valType: 'color',
        dflt: colorAttrs.borderLine,
        
        
    },
    borderwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'arraydraw',
        
    }
}, 'arraydraw', 'from-root');

},{"../../lib/extend":157,"../../plot_api/edit_types":191,"../../plots/font_attributes":232,"../../plots/pad_attributes":244,"../color/attributes":42}],138:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = {

    // layout attribute name
    name: 'updatemenus',

    // class names
    containerClassName: 'updatemenu-container',
    headerGroupClassName: 'updatemenu-header-group',
    headerClassName: 'updatemenu-header',
    headerArrowClassName: 'updatemenu-header-arrow',
    dropdownButtonGroupClassName: 'updatemenu-dropdown-button-group',
    dropdownButtonClassName: 'updatemenu-dropdown-button',
    buttonClassName: 'updatemenu-button',
    itemRectClassName: 'updatemenu-item-rect',
    itemTextClassName: 'updatemenu-item-text',

    // DOM attribute name in button group keeping track
    // of active update menu
    menuIndexAttrName: 'updatemenu-active-index',

    // id root pass to Plots.autoMargin
    autoMarginIdRoot: 'updatemenu-',

    // options when 'active: -1'
    blankHeaderOpts: { label: '  ' },

    // min item width / height
    minWidth: 30,
    minHeight: 30,

    // padding around item text
    textPadX: 24,
    arrowPadX: 16,

    // item rect radii
    rx: 2,
    ry: 2,

    // item  text x offset off left edge
    textOffsetX: 12,

    // item  text y offset (w.r.t. middle)
    textOffsetY: 3,

    // arrow offset off right edge
    arrowOffsetX: 4,

    // gap between header and buttons
    gapButtonHeader: 5,

    // gap between between buttons
    gapButton: 2,

    // color given to active buttons
    activeColor: '#F4FAFF',

    // color given to hovered buttons
    hoverColor: '#F4FAFF',

    // symbol for menu open arrow
    arrowSymbol: {
        left: '◄',
        right: '►',
        up: '▲',
        down: '▼'
    }
};

},{}],139:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var handleArrayContainerDefaults = require('../../plots/array_container_defaults');

var attributes = require('./attributes');
var constants = require('./constants');

var name = constants.name;
var buttonAttrs = attributes.buttons;


module.exports = function updateMenusDefaults(layoutIn, layoutOut) {
    var opts = {
        name: name,
        handleItemDefaults: menuDefaults
    };

    handleArrayContainerDefaults(layoutIn, layoutOut, opts);
};

function menuDefaults(menuIn, menuOut, layoutOut) {

    function coerce(attr, dflt) {
        return Lib.coerce(menuIn, menuOut, attributes, attr, dflt);
    }

    var buttons = buttonsDefaults(menuIn, menuOut);

    var visible = coerce('visible', buttons.length > 0);
    if(!visible) return;

    coerce('active');
    coerce('direction');
    coerce('type');
    coerce('showactive');

    coerce('x');
    coerce('y');
    Lib.noneOrAll(menuIn, menuOut, ['x', 'y']);

    coerce('xanchor');
    coerce('yanchor');

    coerce('pad.t');
    coerce('pad.r');
    coerce('pad.b');
    coerce('pad.l');

    Lib.coerceFont(coerce, 'font', layoutOut.font);

    coerce('bgcolor', layoutOut.paper_bgcolor);
    coerce('bordercolor');
    coerce('borderwidth');
}

function buttonsDefaults(menuIn, menuOut) {
    var buttonsIn = menuIn.buttons || [],
        buttonsOut = menuOut.buttons = [];

    var buttonIn, buttonOut;

    function coerce(attr, dflt) {
        return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
    }

    for(var i = 0; i < buttonsIn.length; i++) {
        buttonIn = buttonsIn[i];
        buttonOut = {};

        coerce('method');

        if(!Lib.isPlainObject(buttonIn) || (buttonOut.method !== 'skip' && !Array.isArray(buttonIn.args))) {
            continue;
        }

        coerce('args');
        coerce('label');
        coerce('execute');

        buttonOut._index = i;
        buttonsOut.push(buttonOut);
    }

    return buttonsOut;
}

},{"../../lib":164,"../../plots/array_container_defaults":202,"./attributes":137,"./constants":138}],140:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Plots = require('../../plots/plots');
var Color = require('../color');
var Drawing = require('../drawing');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');
var anchorUtils = require('../legend/anchor_utils');

var LINE_SPACING = require('../../constants/alignment').LINE_SPACING;

var constants = require('./constants');
var ScrollBox = require('./scrollbox');

module.exports = function draw(gd) {
    var fullLayout = gd._fullLayout,
        menuData = makeMenuData(fullLayout);

    /* Update menu data is bound to the header-group.
     * The items in the header group are always present.
     *
     * Upon clicking on a header its corresponding button
     * data is bound to the button-group.
     *
     * We draw all headers in one group before all buttons
     * so that the buttons *always* appear above the headers.
     *
     * Note that only one set of buttons are visible at once.
     *
     * <g container />
     *
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     <g header-group />
     *         <g item header />
     *         <text item header-arrow />
     *     ...
     *
     *     <g button-group />
     *         <g item button />
     *         <g item button />
     *         ...
     */

    // draw update menu container
    var menus = fullLayout._menulayer
        .selectAll('g.' + constants.containerClassName)
        .data(menuData.length > 0 ? [0] : []);

    menus.enter().append('g')
        .classed(constants.containerClassName, true)
        .style('cursor', 'pointer');

    menus.exit().remove();

    // remove push margin object(s)
    if(menus.exit().size()) clearPushMargins(gd);

    // return early if no update menus are visible
    if(menuData.length === 0) return;

    // join header group
    var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName)
        .data(menuData, keyFunction);

    headerGroups.enter().append('g')
        .classed(constants.headerGroupClassName, true);

    // draw dropdown button container
    var gButton = Lib.ensureSingle(menus, 'g', constants.dropdownButtonGroupClassName, function(s) {
        s.style('pointer-events', 'all');
    });

    // find dimensions before plotting anything (this mutates menuOpts)
    for(var i = 0; i < menuData.length; i++) {
        var menuOpts = menuData[i];
        findDimensions(gd, menuOpts);
    }

    // setup scrollbox
    var scrollBoxId = 'updatemenus' + fullLayout._uid,
        scrollBox = new ScrollBox(gd, gButton, scrollBoxId);

    // remove exiting header, remove dropped buttons and reset margins
    if(headerGroups.enter().size()) {
        // make sure gButton is on top of all headers
        gButton.node().parentNode.appendChild(gButton.node());

        gButton
            .call(removeAllButtons)
            .attr(constants.menuIndexAttrName, '-1');
    }

    headerGroups.exit().each(function(menuOpts) {
        d3.select(this).remove();

        gButton
            .call(removeAllButtons)
            .attr(constants.menuIndexAttrName, '-1');

        Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index);
    });

    // draw headers!
    headerGroups.each(function(menuOpts) {
        var gHeader = d3.select(this);

        var _gButton = menuOpts.type === 'dropdown' ? gButton : null;
        Plots.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) {
            setActive(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true);
        });

        if(menuOpts.type === 'dropdown') {
            drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);

            // if this menu is active, update the dropdown container
            if(isActive(gButton, menuOpts)) {
                drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
            }
        } else {
            drawButtons(gd, gHeader, null, null, menuOpts);
        }

    });
};

/**
 * get only visible menus for display
 */
function makeMenuData(fullLayout) {
    var contOpts = fullLayout[constants.name];
    var menuData = [];

    for(var i = 0; i < contOpts.length; i++) {
        var item = contOpts[i];

        if(item.visible) menuData.push(item);
    }

    return menuData;
}

// Note that '_index' is set at the default step,
// it corresponds to the menu index in the user layout update menu container.
// Because a menu can be set invisible,
// this is a more 'consistent' field than the index in the menuData.
function keyFunction(menuOpts) {
    return menuOpts._index;
}

function isFolded(gButton) {
    return +gButton.attr(constants.menuIndexAttrName) === -1;
}

function isActive(gButton, menuOpts) {
    return +gButton.attr(constants.menuIndexAttrName) === menuOpts._index;
}

function setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) {
    // update 'active' attribute in menuOpts
    menuOpts._input.active = menuOpts.active = buttonIndex;

    if(menuOpts.type === 'buttons') {
        drawButtons(gd, gHeader, null, null, menuOpts);
    }
    else if(menuOpts.type === 'dropdown') {
        // fold up buttons and redraw header
        gButton.attr(constants.menuIndexAttrName, '-1');

        drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);

        if(!isSilentUpdate) {
            drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
        }
    }
}

function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
    var header = Lib.ensureSingle(gHeader, 'g', constants.headerClassName, function(s) {
        s.style('pointer-events', 'all');
    });

    var dims = menuOpts._dims;
    var active = menuOpts.active;
    var headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts;
    var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 };
    var positionOverrides = {
        width: dims.headerWidth,
        height: dims.headerHeight
    };

    header
        .call(drawItem, menuOpts, headerOpts, gd)
        .call(setItemPosition, menuOpts, posOpts, positionOverrides);

    // draw drop arrow at the right edge
    var arrow = Lib.ensureSingle(gHeader, 'text', constants.headerArrowClassName, function(s) {
        s.classed('user-select-none', true)
            .attr('text-anchor', 'end')
            .call(Drawing.font, menuOpts.font)
            .text(constants.arrowSymbol[menuOpts.direction]);
    });

    arrow.attr({
        x: dims.headerWidth - constants.arrowOffsetX + menuOpts.pad.l,
        y: dims.headerHeight / 2 + constants.textOffsetY + menuOpts.pad.t
    });

    header.on('click', function() {
        gButton.call(removeAllButtons);


        // if this menu is active, fold the dropdown container
        // otherwise, make this menu active
        gButton.attr(
            constants.menuIndexAttrName,
            isActive(gButton, menuOpts) ?
                -1 :
                String(menuOpts._index)
        );

        drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
    });

    header.on('mouseover', function() {
        header.call(styleOnMouseOver);
    });

    header.on('mouseout', function() {
        header.call(styleOnMouseOut, menuOpts);
    });

    // translate header group
    Drawing.setTranslate(gHeader, dims.lx, dims.ly);
}

function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) {
    // If this is a set of buttons, set pointer events = all since we play
    // some minor games with which container is which in order to simplify
    // the drawing of *either* buttons or menus
    if(!gButton) {
        gButton = gHeader;
        gButton.attr('pointer-events', 'all');
    }

    var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ?
        menuOpts.buttons :
        [];

    var klass = menuOpts.type === 'dropdown' ? constants.dropdownButtonClassName : constants.buttonClassName;

    var buttons = gButton.selectAll('g.' + klass)
        .data(buttonData);

    var enter = buttons.enter().append('g')
        .classed(klass, true);

    var exit = buttons.exit();

    if(menuOpts.type === 'dropdown') {
        enter.attr('opacity', '0')
            .transition()
            .attr('opacity', '1');

        exit.transition()
            .attr('opacity', '0')
            .remove();
    } else {
        exit.remove();
    }

    var x0 = 0;
    var y0 = 0;
    var dims = menuOpts._dims;

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;

    if(menuOpts.type === 'dropdown') {
        if(isVertical) {
            y0 = dims.headerHeight + constants.gapButtonHeader;
        } else {
            x0 = dims.headerWidth + constants.gapButtonHeader;
        }
    }

    if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') {
        y0 = -constants.gapButtonHeader + constants.gapButton - dims.openHeight;
    }

    if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') {
        x0 = -constants.gapButtonHeader + constants.gapButton - dims.openWidth;
    }

    var posOpts = {
        x: dims.lx + x0 + menuOpts.pad.l,
        y: dims.ly + y0 + menuOpts.pad.t,
        yPad: constants.gapButton,
        xPad: constants.gapButton,
        index: 0,
    };

    var scrollBoxPosition = {
        l: posOpts.x + menuOpts.borderwidth,
        t: posOpts.y + menuOpts.borderwidth
    };

    buttons.each(function(buttonOpts, buttonIndex) {
        var button = d3.select(this);

        button
            .call(drawItem, menuOpts, buttonOpts, gd)
            .call(setItemPosition, menuOpts, posOpts);

        button.on('click', function() {
            // skip `dragend` events
            if(d3.event.defaultPrevented) return;

            setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex);

            if(buttonOpts.execute) {
                Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args);
            }

            gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active});
        });

        button.on('mouseover', function() {
            button.call(styleOnMouseOver);
        });

        button.on('mouseout', function() {
            button.call(styleOnMouseOut, menuOpts);
            buttons.call(styleButtons, menuOpts);
        });
    });

    buttons.call(styleButtons, menuOpts);

    if(isVertical) {
        scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth);
        scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t;
    }
    else {
        scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l;
        scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight);
    }

    scrollBoxPosition.direction = menuOpts.direction;

    if(scrollBox) {
        if(buttons.size()) {
            drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition);
        }
        else {
            hideScrollBox(scrollBox);
        }
    }
}

function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) {
    // enable the scrollbox
    var direction = menuOpts.direction;
    var isVertical = (direction === 'up' || direction === 'down');
    var dims = menuOpts._dims;

    var active = menuOpts.active,
        translateX, translateY,
        i;
    if(isVertical) {
        translateY = 0;
        for(i = 0; i < active; i++) {
            translateY += dims.heights[i] + constants.gapButton;
        }
    }
    else {
        translateX = 0;
        for(i = 0; i < active; i++) {
            translateX += dims.widths[i] + constants.gapButton;
        }
    }

    scrollBox.enable(position, translateX, translateY);

    if(scrollBox.hbar) {
        scrollBox.hbar
            .attr('opacity', '0')
            .transition()
            .attr('opacity', '1');
    }

    if(scrollBox.vbar) {
        scrollBox.vbar
            .attr('opacity', '0')
            .transition()
            .attr('opacity', '1');
    }
}

function hideScrollBox(scrollBox) {
    var hasHBar = !!scrollBox.hbar,
        hasVBar = !!scrollBox.vbar;

    if(hasHBar) {
        scrollBox.hbar
            .transition()
            .attr('opacity', '0')
            .each('end', function() {
                hasHBar = false;
                if(!hasVBar) scrollBox.disable();
            });
    }

    if(hasVBar) {
        scrollBox.vbar
            .transition()
            .attr('opacity', '0')
            .each('end', function() {
                hasVBar = false;
                if(!hasHBar) scrollBox.disable();
            });
    }
}

function drawItem(item, menuOpts, itemOpts, gd) {
    item.call(drawItemRect, menuOpts)
        .call(drawItemText, menuOpts, itemOpts, gd);
}

function drawItemRect(item, menuOpts) {
    var rect = Lib.ensureSingle(item, 'rect', constants.itemRectClassName, function(s) {
        s.attr({
            rx: constants.rx,
            ry: constants.ry,
            'shape-rendering': 'crispEdges'
        });
    });

    rect.call(Color.stroke, menuOpts.bordercolor)
        .call(Color.fill, menuOpts.bgcolor)
        .style('stroke-width', menuOpts.borderwidth + 'px');
}

function drawItemText(item, menuOpts, itemOpts, gd) {
    var text = Lib.ensureSingle(item, 'text', constants.itemTextClassName, function(s) {
        s.classed('user-select-none', true)
            .attr({
                'text-anchor': 'start',
                'data-notex': 1
            });
    });

    text.call(Drawing.font, menuOpts.font)
        .text(itemOpts.label)
        .call(svgTextUtils.convertToTspans, gd);
}

function styleButtons(buttons, menuOpts) {
    var active = menuOpts.active;

    buttons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        if(i === active && menuOpts.showactive) {
            button.select('rect.' + constants.itemRectClassName)
                .call(Color.fill, constants.activeColor);
        }
    });
}

function styleOnMouseOver(item) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, constants.hoverColor);
}

function styleOnMouseOut(item, menuOpts) {
    item.select('rect.' + constants.itemRectClassName)
        .call(Color.fill, menuOpts.bgcolor);
}

// find item dimensions (this mutates menuOpts)
function findDimensions(gd, menuOpts) {
    var dims = menuOpts._dims = {
        width1: 0,
        height1: 0,
        heights: [],
        widths: [],
        totalWidth: 0,
        totalHeight: 0,
        openWidth: 0,
        openHeight: 0,
        lx: 0,
        ly: 0
    };

    var fakeButtons = Drawing.tester.selectAll('g.' + constants.dropdownButtonClassName)
        .data(menuOpts.buttons);

    fakeButtons.enter().append('g')
        .classed(constants.dropdownButtonClassName, true);

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;

    // loop over fake buttons to find width / height
    fakeButtons.each(function(buttonOpts, i) {
        var button = d3.select(this);

        button.call(drawItem, menuOpts, buttonOpts, gd);

        var text = button.select('.' + constants.itemTextClassName);

        // width is given by max width of all buttons
        var tWidth = text.node() && Drawing.bBox(text.node()).width;
        var wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);

        // height is determined by item text
        var tHeight = menuOpts.font.size * LINE_SPACING;
        var tLines = svgTextUtils.lineCount(text);
        var hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;

        hEff = Math.ceil(hEff);
        wEff = Math.ceil(wEff);

        // Store per-item sizes since a row of horizontal buttons, for example,
        // don't all need to be the same width:
        dims.widths[i] = wEff;
        dims.heights[i] = hEff;

        // Height and width of individual element:
        dims.height1 = Math.max(dims.height1, hEff);
        dims.width1 = Math.max(dims.width1, wEff);

        if(isVertical) {
            dims.totalWidth = Math.max(dims.totalWidth, wEff);
            dims.openWidth = dims.totalWidth;
            dims.totalHeight += hEff + constants.gapButton;
            dims.openHeight += hEff + constants.gapButton;
        } else {
            dims.totalWidth += wEff + constants.gapButton;
            dims.openWidth += wEff + constants.gapButton;
            dims.totalHeight = Math.max(dims.totalHeight, hEff);
            dims.openHeight = dims.totalHeight;
        }
    });

    if(isVertical) {
        dims.totalHeight -= constants.gapButton;
    } else {
        dims.totalWidth -= constants.gapButton;
    }


    dims.headerWidth = dims.width1 + constants.arrowPadX;
    dims.headerHeight = dims.height1;

    if(menuOpts.type === 'dropdown') {
        if(isVertical) {
            dims.width1 += constants.arrowPadX;
            dims.totalHeight = dims.height1;
        } else {
            dims.totalWidth = dims.width1;
        }
        dims.totalWidth += constants.arrowPadX;
    }

    fakeButtons.remove();

    var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r;
    var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b;

    var graphSize = gd._fullLayout._size;
    dims.lx = graphSize.l + graphSize.w * menuOpts.x;
    dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);

    var xanchor = 'left';
    if(anchorUtils.isRightAnchor(menuOpts)) {
        dims.lx -= paddedWidth;
        xanchor = 'right';
    }
    if(anchorUtils.isCenterAnchor(menuOpts)) {
        dims.lx -= paddedWidth / 2;
        xanchor = 'center';
    }

    var yanchor = 'top';
    if(anchorUtils.isBottomAnchor(menuOpts)) {
        dims.ly -= paddedHeight;
        yanchor = 'bottom';
    }
    if(anchorUtils.isMiddleAnchor(menuOpts)) {
        dims.ly -= paddedHeight / 2;
        yanchor = 'middle';
    }

    dims.totalWidth = Math.ceil(dims.totalWidth);
    dims.totalHeight = Math.ceil(dims.totalHeight);
    dims.lx = Math.round(dims.lx);
    dims.ly = Math.round(dims.ly);

    Plots.autoMargin(gd, constants.autoMarginIdRoot + menuOpts._index, {
        x: menuOpts.x,
        y: menuOpts.y,
        l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0),
        r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0),
        b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0),
        t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0)
    });
}

// set item positions (mutates posOpts)
function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
    overrideOpts = overrideOpts || {};
    var rect = item.select('.' + constants.itemRectClassName);
    var text = item.select('.' + constants.itemTextClassName);
    var borderWidth = menuOpts.borderwidth;
    var index = posOpts.index;
    var dims = menuOpts._dims;

    Drawing.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y);

    var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
    var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1);

    rect.attr({
        x: 0,
        y: 0,
        width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]),
        height: finalHeight
    });

    var tHeight = menuOpts.font.size * LINE_SPACING;
    var tLines = svgTextUtils.lineCount(text);
    var spanOffset = ((tLines - 1) * tHeight / 2);

    svgTextUtils.positionText(text, constants.textOffsetX,
        finalHeight / 2 - spanOffset + constants.textOffsetY);

    if(isVertical) {
        posOpts.y += dims.heights[index] + posOpts.yPad;
    } else {
        posOpts.x += dims.widths[index] + posOpts.xPad;
    }

    posOpts.index++;
}

function removeAllButtons(gButton) {
    gButton.selectAll('g.' + constants.dropdownButtonClassName).remove();
}

function clearPushMargins(gd) {
    var pushMargins = gd._fullLayout._pushmargin || {};
    var keys = Object.keys(pushMargins);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        if(k.indexOf(constants.autoMarginIdRoot) !== -1) {
            Plots.autoMargin(gd, k);
        }
    }
}

},{"../../constants/alignment":143,"../../lib":164,"../../lib/svg_text_utils":185,"../../plots/plots":245,"../color":43,"../drawing":68,"../legend/anchor_utils":95,"./constants":138,"./scrollbox":142,"d3":6}],141:[function(require,module,exports){
arguments[4][135][0].apply(exports,arguments)
},{"./attributes":137,"./constants":138,"./defaults":139,"./draw":140,"dup":135}],142:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = ScrollBox;

var d3 = require('d3');

var Color = require('../color');
var Drawing = require('../drawing');

var Lib = require('../../lib');

/**
 * Helper class to setup a scroll box
 *
 * @class
 * @param           gd          Plotly's graph div
 * @param           container   Container to be scroll-boxed (as a D3 selection)
 * @param {string}  id          Id for the clip path to implement the scroll box
 */
function ScrollBox(gd, container, id) {
    this.gd = gd;
    this.container = container;
    this.id = id;

    // See ScrollBox.prototype.enable for further definition
    this.position = null;  // scrollbox position
    this.translateX = null;  // scrollbox horizontal translation
    this.translateY = null;  // scrollbox vertical translation
    this.hbar = null;  // horizontal scrollbar D3 selection
    this.vbar = null;  // vertical scrollbar D3 selection

    // <rect> element to capture pointer events
    this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]);

    this.bg.exit()
        .on('.drag', null)
        .on('wheel', null)
        .remove();

    this.bg.enter().append('rect')
        .classed('scrollbox-bg', true)
        .style('pointer-events', 'all')
        .attr({
            opacity: 0,
            x: 0,
            y: 0,
            width: 0,
            height: 0
        });
}

// scroll bar dimensions
ScrollBox.barWidth = 2;
ScrollBox.barLength = 20;
ScrollBox.barRadius = 2;
ScrollBox.barPad = 1;
ScrollBox.barColor = '#808BA4';

/**
 * If needed, setup a clip path and scrollbars
 *
 * @method
 * @param {Object}  position
 * @param {number}  position.l  Left side position (in pixels)
 * @param {number}  position.t  Top side (in pixels)
 * @param {number}  position.w  Width (in pixels)
 * @param {number}  position.h  Height (in pixels)
 * @param {string}  [position.direction='down']
 *                  Either 'down', 'left', 'right' or 'up'
 * @param {number}  [translateX=0]  Horizontal offset (in pixels)
 * @param {number}  [translateY=0]  Vertical offset (in pixels)
 */
ScrollBox.prototype.enable = function enable(position, translateX, translateY) {
    var fullLayout = this.gd._fullLayout,
        fullWidth = fullLayout.width,
        fullHeight = fullLayout.height;

    // compute position of scrollbox
    this.position = position;

    var l = this.position.l,
        w = this.position.w,
        t = this.position.t,
        h = this.position.h,
        direction = this.position.direction,
        isDown = (direction === 'down'),
        isLeft = (direction === 'left'),
        isRight = (direction === 'right'),
        isUp = (direction === 'up'),
        boxW = w,
        boxH = h,
        boxL, boxR,
        boxT, boxB;

    if(!isDown && !isLeft && !isRight && !isUp) {
        this.position.direction = 'down';
        isDown = true;
    }

    var isVertical = isDown || isUp;
    if(isVertical) {
        boxL = l;
        boxR = boxL + boxW;

        if(isDown) {
            // anchor to top side
            boxT = t;
            boxB = Math.min(boxT + boxH, fullHeight);
            boxH = boxB - boxT;
        }
        else {
            // anchor to bottom side
            boxB = t + boxH;
            boxT = Math.max(boxB - boxH, 0);
            boxH = boxB - boxT;
        }
    }
    else {
        boxT = t;
        boxB = boxT + boxH;

        if(isLeft) {
            // anchor to right side
            boxR = l + boxW;
            boxL = Math.max(boxR - boxW, 0);
            boxW = boxR - boxL;
        }
        else {
            // anchor to left side
            boxL = l;
            boxR = Math.min(boxL + boxW, fullWidth);
            boxW = boxR - boxL;
        }
    }

    this._box = {
        l: boxL,
        t: boxT,
        w: boxW,
        h: boxH
    };

    // compute position of horizontal scroll bar
    var needsHorizontalScrollBar = (w > boxW),
        hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad,
        hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad,
        // draw horizontal scrollbar on the bottom side
        hbarL = l,
        hbarT = t + h;

    if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH;

    var hbar = this.container.selectAll('rect.scrollbar-horizontal').data(
            (needsHorizontalScrollBar) ? [0] : []);

    hbar.exit()
        .on('.drag', null)
        .remove();

    hbar.enter().append('rect')
        .classed('scrollbar-horizontal', true)
        .call(Color.fill, ScrollBox.barColor);

    if(needsHorizontalScrollBar) {
        this.hbar = hbar.attr({
            'rx': ScrollBox.barRadius,
            'ry': ScrollBox.barRadius,
            'x': hbarL,
            'y': hbarT,
            'width': hbarW,
            'height': hbarH
        });

        // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax
        this._hbarXMin = hbarL + hbarW / 2;
        this._hbarTranslateMax = boxW - hbarW;
    }
    else {
        delete this.hbar;
        delete this._hbarXMin;
        delete this._hbarTranslateMax;
    }

    // compute position of vertical scroll bar
    var needsVerticalScrollBar = (h > boxH),
        vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad,
        vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad,
        // draw vertical scrollbar on the right side
        vbarL = l + w,
        vbarT = t;

    if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW;

    var vbar = this.container.selectAll('rect.scrollbar-vertical').data(
            (needsVerticalScrollBar) ? [0] : []);

    vbar.exit()
        .on('.drag', null)
        .remove();

    vbar.enter().append('rect')
        .classed('scrollbar-vertical', true)
        .call(Color.fill, ScrollBox.barColor);

    if(needsVerticalScrollBar) {
        this.vbar = vbar.attr({
            'rx': ScrollBox.barRadius,
            'ry': ScrollBox.barRadius,
            'x': vbarL,
            'y': vbarT,
            'width': vbarW,
            'height': vbarH
        });

        // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax
        this._vbarYMin = vbarT + vbarH / 2;
        this._vbarTranslateMax = boxH - vbarH;
    }
    else {
        delete this.vbar;
        delete this._vbarYMin;
        delete this._vbarTranslateMax;
    }

    // setup a clip path (if scroll bars are needed)
    var clipId = this.id,
        clipL = boxL - 0.5,
        clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5,
        clipT = boxT - 0.5,
        clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5;

    var clipPath = fullLayout._topdefs.selectAll('#' + clipId)
        .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []);

    clipPath.exit().remove();

    clipPath.enter()
        .append('clipPath').attr('id', clipId)
        .append('rect');

    if(needsHorizontalScrollBar || needsVerticalScrollBar) {
        this._clipRect = clipPath.select('rect').attr({
            x: Math.floor(clipL),
            y: Math.floor(clipT),
            width: Math.ceil(clipR) - Math.floor(clipL),
            height: Math.ceil(clipB) - Math.floor(clipT)
        });

        this.container.call(Drawing.setClipUrl, clipId);

        this.bg.attr({
            x: l,
            y: t,
            width: w,
            height: h
        });
    }
    else {
        this.bg.attr({
            width: 0,
            height: 0
        });
        this.container
            .on('wheel', null)
            .on('.drag', null)
            .call(Drawing.setClipUrl, null);
        delete this._clipRect;
    }

    // set up drag listeners (if scroll bars are needed)
    if(needsHorizontalScrollBar || needsVerticalScrollBar) {
        var onBoxDrag = d3.behavior.drag()
            .on('dragstart', function() {
                d3.event.sourceEvent.preventDefault();
            })
            .on('drag', this._onBoxDrag.bind(this));

        this.container
            .on('wheel', null)
            .on('wheel', this._onBoxWheel.bind(this))
            .on('.drag', null)
            .call(onBoxDrag);

        var onBarDrag = d3.behavior.drag()
            .on('dragstart', function() {
                d3.event.sourceEvent.preventDefault();
                d3.event.sourceEvent.stopPropagation();
            })
            .on('drag', this._onBarDrag.bind(this));

        if(needsHorizontalScrollBar) {
            this.hbar
                .on('.drag', null)
                .call(onBarDrag);
        }

        if(needsVerticalScrollBar) {
            this.vbar
                .on('.drag', null)
                .call(onBarDrag);
        }
    }

    // set scrollbox translation
    this.setTranslate(translateX, translateY);
};

/**
 * If present, remove clip-path and scrollbars
 *
 * @method
 */
ScrollBox.prototype.disable = function disable() {
    if(this.hbar || this.vbar) {
        this.bg.attr({
            width: 0,
            height: 0
        });
        this.container
            .on('wheel', null)
            .on('.drag', null)
            .call(Drawing.setClipUrl, null);
        delete this._clipRect;
    }

    if(this.hbar) {
        this.hbar.on('.drag', null);
        this.hbar.remove();
        delete this.hbar;
        delete this._hbarXMin;
        delete this._hbarTranslateMax;
    }

    if(this.vbar) {
        this.vbar.on('.drag', null);
        this.vbar.remove();
        delete this.vbar;
        delete this._vbarYMin;
        delete this._vbarTranslateMax;
    }
};

/**
 * Handles scroll box drag events
 *
 * @method
 */
ScrollBox.prototype._onBoxDrag = function onBarDrag() {
    var translateX = this.translateX,
        translateY = this.translateY;

    if(this.hbar) {
        translateX -= d3.event.dx;
    }

    if(this.vbar) {
        translateY -= d3.event.dy;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Handles scroll box wheel events
 *
 * @method
 */
ScrollBox.prototype._onBoxWheel = function onBarWheel() {
    var translateX = this.translateX,
        translateY = this.translateY;

    if(this.hbar) {
        translateX += d3.event.deltaY;
    }

    if(this.vbar) {
        translateY += d3.event.deltaY;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Handles scroll bar drag events
 *
 * @method
 */
ScrollBox.prototype._onBarDrag = function onBarDrag() {
    var translateX = this.translateX,
        translateY = this.translateY;

    if(this.hbar) {
        var xMin = translateX + this._hbarXMin,
            xMax = xMin + this._hbarTranslateMax,
            x = Lib.constrain(d3.event.x, xMin, xMax),
            xf = (x - xMin) / (xMax - xMin);

        var translateXMax = this.position.w - this._box.w;

        translateX = xf * translateXMax;
    }

    if(this.vbar) {
        var yMin = translateY + this._vbarYMin,
            yMax = yMin + this._vbarTranslateMax,
            y = Lib.constrain(d3.event.y, yMin, yMax),
            yf = (y - yMin) / (yMax - yMin);

        var translateYMax = this.position.h - this._box.h;

        translateY = yf * translateYMax;
    }

    this.setTranslate(translateX, translateY);
};

/**
 * Set clip path and scroll bar translate transform
 *
 * @method
 * @param {number}  [translateX=0]  Horizontal offset (in pixels)
 * @param {number}  [translateY=0]  Vertical offset (in pixels)
 */
ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) {
    // store translateX and translateY (needed by mouse event handlers)
    var translateXMax = this.position.w - this._box.w,
        translateYMax = this.position.h - this._box.h;

    translateX = Lib.constrain(translateX || 0, 0, translateXMax);
    translateY = Lib.constrain(translateY || 0, 0, translateYMax);

    this.translateX = translateX;
    this.translateY = translateY;

    this.container.call(Drawing.setTranslate,
        this._box.l - this.position.l - translateX,
        this._box.t - this.position.t - translateY);

    if(this._clipRect) {
        this._clipRect.attr({
            x: Math.floor(this.position.l + translateX - 0.5),
            y: Math.floor(this.position.t + translateY - 0.5)
        });
    }

    if(this.hbar) {
        var xf = translateX / translateXMax;

        this.hbar.call(Drawing.setTranslate,
            translateX + xf * this._hbarTranslateMax,
            translateY);
    }

    if(this.vbar) {
        var yf = translateY / translateYMax;

        this.vbar.call(Drawing.setTranslate,
            translateX,
            translateY + yf * this._vbarTranslateMax);
    }
};

},{"../../lib":164,"../color":43,"../drawing":68,"d3":6}],143:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// fraction of some size to get to a named position
module.exports = {
    // from bottom left: this is the origin of our paper-reference
    // positioning system
    FROM_BL: {
        left: 0,
        center: 0.5,
        right: 1,
        bottom: 0,
        middle: 0.5,
        top: 1
    },
    // from top left: this is the screen pixel positioning origin
    FROM_TL: {
        left: 0,
        center: 0.5,
        right: 1,
        bottom: 1,
        middle: 0.5,
        top: 0
    },
    // from bottom right: sometimes you just need the opposite of ^^
    FROM_BR: {
        left: 1,
        center: 0.5,
        right: 0,
        bottom: 0,
        middle: 0.5,
        top: 1
    },
    // multiple of fontSize to get the vertical offset between lines
    LINE_SPACING: 1.3,

    // multiple of fontSize to shift from the baseline to the midline
    // (to use when we don't calculate this shift from Drawing.bBox)
    // To be precise this should be half the cap height (capital letter)
    // of the font, and according to wikipedia:
    //   an "average" font might have a cap height of 70% of the em
    // https://en.wikipedia.org/wiki/Em_(typography)#History
    MID_SHIFT: 0.35,

    OPPOSITE_SIDE: {
        left: 'right',
        right: 'left',
        top: 'bottom',
        bottom: 'top'
    }
};

},{}],144:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    /**
     * Timing information for interactive elements
     */
    SHOW_PLACEHOLDER: 100,
    HIDE_PLACEHOLDER: 1000,

    // ms between first mousedown and 2nd mouseup to constitute dblclick...
    // we don't seem to have access to the system setting
    DBLCLICKDELAY: 300,

    // opacity dimming fraction for points that are not in selection
    DESELECTDIM: 0.2
};

},{}],145:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    /**
     * Standardize all missing data in calcdata to use undefined
     * never null or NaN.
     * That way we can use !==undefined, or !== BADNUM,
     * to test for real data
     */
    BADNUM: undefined,

    /*
     * Limit certain operations to well below floating point max value
     * to avoid glitches: Make sure that even when you multiply it by the
     * number of pixels on a giant screen it still works
     */
    FP_SAFE: Number.MAX_VALUE / 10000,

    /*
     * conversion of date units to milliseconds
     * year and month constants are marked "AVG"
     * to remind us that not all years and months
     * have the same length
     */
    ONEAVGYEAR: 31557600000, // 365.25 days
    ONEAVGMONTH: 2629800000, // 1/12 of ONEAVGYEAR
    ONEDAY: 86400000,
    ONEHOUR: 3600000,
    ONEMIN: 60000,
    ONESEC: 1000,

    /*
     * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
     * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
     */
    EPOCHJD: 2440587.5,

    /*
     * Are two values nearly equal? Compare to 1PPM
     */
    ALMOST_EQUAL: 1 - 1e-6,

    /*
     * not a number, but for displaying numbers: the "minus sign" symbol is
     * wider than the regular ascii dash "-"
     */
    MINUS_SIGN: '\u2212'
};

},{}],146:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// N.B. HTML entities are listed without the leading '&' and trailing ';'
// https://www.freeformatter.com/html-entities.html

module.exports = {
    entityToUnicode: {
        'mu': 'μ',
        '#956': 'μ',

        'amp': '&',
        '#28': '&',

        'lt': '<',
        '#60': '<',

        'gt': '>',
        '#62': '>',

        'nbsp': ' ',
        '#160': ' ',

        'times': '×',
        '#215': '×',

        'plusmn': '±',
        '#177': '±',

        'deg': '°',
        '#176': '°'
    }
};

},{}],147:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


exports.xmlns = 'http://www.w3.org/2000/xmlns/';
exports.svg = 'http://www.w3.org/2000/svg';
exports.xlink = 'http://www.w3.org/1999/xlink';

// the 'old' d3 quirk got fix in v3.5.7
// https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed
exports.svgAttrs = {
    xmlns: exports.svg,
    'xmlns:xlink': exports.xlink
};

},{}],148:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// package version injected by `npm run preprocess`
exports.version = '1.37.1';

// inject promise polyfill
require('es6-promise').polyfill();

// inject plot css
require('../build/plotcss');

// inject default MathJax config
require('./fonts/mathjax_config');

// include registry module and expose register method
var Registry = require('./registry');
var register = exports.register = Registry.register;

// expose plot api methods
var plotApi = require('./plot_api');
var methodNames = Object.keys(plotApi);
for(var i = 0; i < methodNames.length; i++) {
    var name = methodNames[i];
    exports[name] = plotApi[name];
    register({
        moduleType: 'apiMethod',
        name: name,
        fn: plotApi[name]
    });
}

// scatter is the only trace included by default
register(require('./traces/scatter'));

// register all registrable components modules
register([
    require('./components/fx'),
    require('./components/legend'),
    require('./components/annotations'),
    require('./components/annotations3d'),
    require('./components/shapes'),
    require('./components/images'),
    require('./components/updatemenus'),
    require('./components/sliders'),
    require('./components/rangeslider'),
    require('./components/rangeselector'),
    require('./components/grid'),
    require('./components/errorbars')
]);

// locales en and en-US are required for default behavior
register([
    require('./locale-en'),
    require('./locale-en-us')
]);

// plot icons
exports.Icons = require('../build/ploticon');

// unofficial 'beta' plot methods, use at your own risk
exports.Plots = require('./plots/plots');
exports.Fx = require('./components/fx');
exports.Snapshot = require('./snapshot');
exports.PlotSchema = require('./plot_api/plot_schema');
exports.Queue = require('./lib/queue');

// export d3 used in the bundle
exports.d3 = require('d3');

},{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":36,"./components/annotations3d":41,"./components/errorbars":74,"./components/fx":85,"./components/grid":89,"./components/images":94,"./components/legend":103,"./components/rangeselector":115,"./components/rangeslider":121,"./components/shapes":129,"./components/sliders":135,"./components/updatemenus":141,"./fonts/mathjax_config":149,"./lib/queue":178,"./locale-en":189,"./locale-en-us":188,"./plot_api":193,"./plot_api/plot_schema":197,"./plots/plots":245,"./registry":254,"./snapshot":259,"./traces/scatter":278,"d3":6,"es6-promise":7}],149:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* global MathJax:false */

/**
 * Check and configure MathJax
 */
if(typeof MathJax !== 'undefined') {
    exports.MathJax = true;

    MathJax.Hub.Config({
        messageStyle: 'none',
        skipStartupTypeset: true,
        displayAlign: 'left',
        tex2jax: {
            inlineMath: [['$', '$'], ['\\(', '\\)']]
        }
    });

    MathJax.Hub.Configured();
} else {
    exports.MathJax = false;
}

},{}],150:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var PI = Math.PI;

exports.deg2rad = function(deg) {
    return deg / 180 * PI;
};

exports.rad2deg = function(rad) {
    return rad / PI * 180;
};

exports.wrap360 = function(deg) {
    var out = deg % 360;
    return out < 0 ? out + 360 : out;
};

exports.wrap180 = function(deg) {
    if(Math.abs(deg) > 180) deg -= Math.round(deg / 360) * 360;
    return deg;
};

},{}],151:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var BADNUM = require('../constants/numerical').BADNUM;

// precompile for speed
var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;

/**
 * cleanNumber: remove common leading and trailing cruft
 * Always returns either a number or BADNUM.
 */
module.exports = function cleanNumber(v) {
    if(typeof v === 'string') {
        v = v.replace(JUNK, '');
    }

    if(isNumeric(v)) return Number(v);

    return BADNUM;
};

},{"../constants/numerical":145,"fast-isnumeric":9}],152:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Clear gl frame (if any). This is a common pattern as
 * we usually set `preserveDrawingBuffer: true` during
 * gl context creation (e.g. via `reglUtils.prepare`).
 *
 * @param {DOM node or object} gd : graph div object
 */
module.exports = function clearGlCanvases(gd) {
    var fullLayout = gd._fullLayout;

    if(fullLayout._glcanvas && fullLayout._glcanvas.size()) {
        fullLayout._glcanvas.each(function(d) {
            if(d.regl) d.regl.clear({color: true, depth: true});
        });
    }
};

},{}],153:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var tinycolor = require('tinycolor2');

var baseTraceAttrs = require('../plots/attributes');
var getColorscale = require('../components/colorscale/get_scale');
var colorscaleNames = Object.keys(require('../components/colorscale/scales'));
var nestedProperty = require('./nested_property');
var counterRegex = require('./regex').counter;
var DESELECTDIM = require('../constants/interactions').DESELECTDIM;
var wrap180 = require('./angles').wrap180;
var isArrayOrTypedArray = require('./is_array').isArrayOrTypedArray;

exports.valObjectMeta = {
    data_array: {
        // You can use *dflt=[] to force said array to exist though.
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also
            if(isArrayOrTypedArray(v)) propOut.set(v);
            else if(dflt !== undefined) propOut.set(dflt);
        }
    },
    enumerated: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(opts.coerceNumber) v = +v;
            if(opts.values.indexOf(v) === -1) propOut.set(dflt);
            else propOut.set(v);
        },
        validateFunction: function(v, opts) {
            if(opts.coerceNumber) v = +v;

            var values = opts.values;
            for(var i = 0; i < values.length; i++) {
                var k = String(values[i]);

                if((k.charAt(0) === '/' && k.charAt(k.length - 1) === '/')) {
                    var regex = new RegExp(k.substr(1, k.length - 2));
                    if(regex.test(v)) return true;
                } else if(v === values[i]) return true;
            }
            return false;
        }
    },
    'boolean': {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === true || v === false) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    number: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(!isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    integer: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(v % 1 || !isNumeric(v) ||
                    (opts.min !== undefined && v < opts.min) ||
                    (opts.max !== undefined && v > opts.max)) {
                propOut.set(dflt);
            }
            else propOut.set(+v);
        }
    },
    string: {
        
        
        // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                var okToCoerce = (typeof v === 'number');

                if(opts.strict === true || !okToCoerce) propOut.set(dflt);
                else propOut.set(String(v));
            }
            else if(opts.noBlank && !v) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    color: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(tinycolor(v).isValid()) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorlist: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            function isColor(color) {
                return tinycolor(color).isValid();
            }
            if(!Array.isArray(v) || !v.length) propOut.set(dflt);
            else if(v.every(isColor)) propOut.set(v);
            else propOut.set(dflt);
        }
    },
    colorscale: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            propOut.set(getColorscale(v, dflt));
        }
    },
    angle: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === 'auto') propOut.set('auto');
            else if(!isNumeric(v)) propOut.set(dflt);
            else propOut.set(wrap180(+v));
        }
    },
    subplotid: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            var regex = opts.regex || counterRegex(dflt);
            if(typeof v === 'string' && regex.test(v)) {
                propOut.set(v);
                return;
            }
            propOut.set(dflt);
        },
        validateFunction: function(v, opts) {
            var dflt = opts.dflt;

            if(v === dflt) return true;
            if(typeof v !== 'string') return false;
            if(counterRegex(dflt).test(v)) return true;

            return false;
        }
    },
    flaglist: {
        
        
        
        coerceFunction: function(v, propOut, dflt, opts) {
            if(typeof v !== 'string') {
                propOut.set(dflt);
                return;
            }
            if((opts.extras || []).indexOf(v) !== -1) {
                propOut.set(v);
                return;
            }
            var vParts = v.split('+'),
                i = 0;
            while(i < vParts.length) {
                var vi = vParts[i];
                if(opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
                    vParts.splice(i, 1);
                }
                else i++;
            }
            if(!vParts.length) propOut.set(dflt);
            else propOut.set(vParts.join('+'));
        }
    },
    any: {
        
        
        
        coerceFunction: function(v, propOut, dflt) {
            if(v === undefined) propOut.set(dflt);
            else propOut.set(v);
        }
    },
    info_array: {
        
        
        // set `dimensions=2` for a 2D array or '1-2' for either
        // `items` may be a single object instead of an array, in which case
        // `freeLength` must be true.
        // if `dimensions='1-2'` and items is a 1D array, then the value can
        // either be a matching 1D array or an array of such matching 1D arrays
        
        coerceFunction: function(v, propOut, dflt, opts) {

            // simplified coerce function just for array items
            function coercePart(v, opts, dflt) {
                var out;
                var propPart = {set: function(v) { out = v; }};

                if(dflt === undefined) dflt = opts.dflt;

                exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);

                return out;
            }

            var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0]));

            if(!Array.isArray(v)) {
                propOut.set(dflt);
                return;
            }

            var items = opts.items;
            var vOut = [];
            var arrayItems = Array.isArray(items);
            var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]);
            var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
            var len = (arrayItems && !innerItemsOnly) ? items.length : v.length;

            var i, j, row, item, len2, vNew;

            dflt = Array.isArray(dflt) ? dflt : [];

            if(twoD) {
                for(i = 0; i < len; i++) {
                    vOut[i] = [];
                    row = Array.isArray(v[i]) ? v[i] : [];
                    if(innerItemsOnly) len2 = items.length;
                    else if(arrayItems) len2 = items[i].length;
                    else len2 = row.length;

                    for(j = 0; j < len2; j++) {
                        if(innerItemsOnly) item = items[j];
                        else if(arrayItems) item = items[i][j];
                        else item = items;

                        vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
                        if(vNew !== undefined) vOut[i][j] = vNew;
                    }
                }
            }
            else {
                for(i = 0; i < len; i++) {
                    vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
                    if(vNew !== undefined) vOut[i] = vNew;
                }
            }

            propOut.set(vOut);
        },
        validateFunction: function(v, opts) {
            if(!Array.isArray(v)) return false;

            var items = opts.items;
            var arrayItems = Array.isArray(items);
            var twoD = opts.dimensions === 2;

            // when free length is off, input and declared lengths must match
            if(!opts.freeLength && v.length !== items.length) return false;

            // valid when all input items are valid
            for(var i = 0; i < v.length; i++) {
                if(twoD) {
                    if(!Array.isArray(v[i]) || (!opts.freeLength && v[i].length !== items[i].length)) {
                        return false;
                    }
                    for(var j = 0; j < v[i].length; j++) {
                        if(!exports.validate(v[i][j], arrayItems ? items[i][j] : items)) {
                            return false;
                        }
                    }
                }
                else if(!exports.validate(v[i], arrayItems ? items[i] : items)) return false;
            }

            return true;
        }
    }
};

/**
 * Ensures that container[attribute] has a valid value.
 *
 * attributes[attribute] is an object with possible keys:
 * - valType: data_array, enumerated, boolean, ... as in valObjectMeta
 * - values: (enumerated only) array of allowed vals
 * - min, max: (number, integer only) inclusive bounds on allowed vals
 *      either or both may be omitted
 * - dflt: if attribute is invalid or missing, use this default
 *      if dflt is provided as an argument to lib.coerce it takes precedence
 *      as a convenience, returns the value it finally set
 */
exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
    var opts = nestedProperty(attributes, attribute).get(),
        propIn = nestedProperty(containerIn, attribute),
        propOut = nestedProperty(containerOut, attribute),
        v = propIn.get();

    if(dflt === undefined) dflt = opts.dflt;

    /**
     * arrayOk: value MAY be an array, then we do no value checking
     * at this point, because it can be more complicated than the
     * individual form (eg. some array vals can be numbers, even if the
     * single values must be color strings)
     */
    if(opts.arrayOk && isArrayOrTypedArray(v)) {
        propOut.set(v);
        return v;
    }

    exports.valObjectMeta[opts.valType].coerceFunction(v, propOut, dflt, opts);

    return propOut.get();
};

/**
 * Variation on coerce
 *
 * Uses coerce to get attribute value if user input is valid,
 * returns attribute default if user input it not valid or
 * returns false if there is no user input.
 */
exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
    var propIn = nestedProperty(containerIn, attribute),
        propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt),
        valIn = propIn.get();

    return (valIn !== undefined && valIn !== null) ? propOut : false;
};

/*
 * Shortcut to coerce the three font attributes
 *
 * 'coerce' is a lib.coerce wrapper with implied first three arguments
 */
exports.coerceFont = function(coerce, attr, dfltObj) {
    var out = {};

    dfltObj = dfltObj || {};

    out.family = coerce(attr + '.family', dfltObj.family);
    out.size = coerce(attr + '.size', dfltObj.size);
    out.color = coerce(attr + '.color', dfltObj.color);

    return out;
};

/** Coerce shortcut for 'hoverinfo'
 * handling 1-vs-multi-trace dflt logic
 *
 * @param {object} traceIn : user trace object
 * @param {object} traceOut : full trace object (requires _module ref)
 * @param {object} layoutOut : full layout object (require _dataLength ref)
 * @return {any} : the coerced value
 */
exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
    var moduleAttrs = traceOut._module.attributes;
    var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;

    var valObj = attrs.hoverinfo;
    var dflt;

    if(layoutOut._dataLength === 1) {
        var flags = valObj.dflt === 'all' ?
            valObj.flags.slice() :
            valObj.dflt.split('+');

        flags.splice(flags.indexOf('name'), 1);
        dflt = flags.join('+');
    }

    return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
};

/** Coerce shortcut for [un]selected.marker.opacity,
 *  which has special default logic, to ensure that it corresponds to the
 *  default selection behavior while allowing to be overtaken by any other
 *  [un]selected attribute.
 *
 *  N.B. This must be called *after* coercing all the other [un]selected attrs,
 *  to give the intended result.
 *
 * @param {object} traceOut : fullData item
 * @param {function} coerce : lib.coerce wrapper with implied first three arguments
 */
exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
    if(!traceOut.marker) return;

    var mo = traceOut.marker.opacity;
    // you can still have a `marker` container with no markers if there's text
    if(mo === undefined) return;

    var smoDflt;
    var usmoDflt;

    // Don't give [un]selected.marker.opacity a default value if
    // marker.opacity is an array: handle this during style step.
    //
    // Only give [un]selected.marker.opacity a default value if you don't
    // set any other [un]selected attributes.
    if(!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
        smoDflt = mo;
        usmoDflt = DESELECTDIM * mo;
    }

    coerce('selected.marker.opacity', smoDflt);
    coerce('unselected.marker.opacity', usmoDflt);
};

exports.validate = function(value, opts) {
    var valObjectDef = exports.valObjectMeta[opts.valType];

    if(opts.arrayOk && isArrayOrTypedArray(value)) return true;

    if(valObjectDef.validateFunction) {
        return valObjectDef.validateFunction(value, opts);
    }

    var failed = {},
        out = failed,
        propMock = { set: function(v) { out = v; } };

    // 'failed' just something mutable that won't be === anything else

    valObjectDef.coerceFunction(value, propMock, failed, opts);
    return out !== failed;
};

},{"../components/colorscale/get_scale":56,"../components/colorscale/scales":62,"../constants/interactions":144,"../plots/attributes":203,"./angles":150,"./is_array":165,"./nested_property":172,"./regex":179,"fast-isnumeric":9,"tinycolor2":25}],154:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var Loggers = require('./loggers');
var mod = require('./mod');

var constants = require('../constants/numerical');
var BADNUM = constants.BADNUM;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var EPOCHJD = constants.EPOCHJD;

var Registry = require('../registry');

var utcFormat = d3.time.format.utc;

var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
// special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;

// for 2-digit years, the first year we map them onto
var YFIRST = new Date().getFullYear() - 70;

function isWorldCalendar(calendar) {
    return (
        calendar &&
        Registry.componentsRegistry.calendars &&
        typeof calendar === 'string' && calendar !== 'gregorian'
    );
}

/*
 * dateTick0: get the canonical tick for this calendar
 *
 * bool sunday is for week ticks, shift it to a Sunday.
 */
exports.dateTick0 = function(calendar, sunday) {
    if(isWorldCalendar(calendar)) {
        return sunday ?
            Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] :
            Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
    }
    else {
        return sunday ? '2000-01-02' : '2000-01-01';
    }
};

/*
 * dfltRange: for each calendar, give a valid default range
 */
exports.dfltRange = function(calendar) {
    if(isWorldCalendar(calendar)) {
        return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
    }
    else {
        return ['2000-01-01', '2001-01-01'];
    }
};

// is an object a javascript date?
exports.isJSDate = function(v) {
    return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
};

// The absolute limits of our date-time system
// This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
// but we use dateTime2ms to calculate them (after defining it!)
var MIN_MS, MAX_MS;

/**
 * dateTime2ms - turn a date object or string s into milliseconds
 * (relative to 1970-01-01, per javascript standard)
 * optional calendar (string) to use a non-gregorian calendar
 *
 * Returns BADNUM if it doesn't find a date
 *
 * strings should have the form:
 *
 *    -?YYYY-mm-dd<sep>HH:MM:SS.sss<tzInfo>?
 *
 * <sep>: space (our normal standard) or T or t (ISO-8601)
 * <tzInfo>: Z, z, or [+\-]HH:?MM and we THROW IT AWAY
 * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
 * but we allow it even with a space as the separator
 *
 * May truncate after any full field, and sss can be any length
 * even >3 digits, though javascript dates truncate to milliseconds,
 * we keep as much as javascript numeric precision can hold, but we only
 * report back up to 100 microsecond precision, because most dates support
 * this precision (close to 1970 support more, very far away support less)
 *
 * Expanded to support negative years to -9999 but you must always
 * give 4 digits, except for 2-digit positive years which we assume are
 * near the present time.
 * Note that we follow ISO 8601:2004: there *is* a year 0, which
 * is 1BC/BCE, and -1===2BC etc.
 *
 * World calendars: not all of these *have* agreed extensions to this full range,
 * if you have another calendar system but want a date range outside its validity,
 * you can use a gregorian date string prefixed with 'G' or 'g'.
 *
 * Where to cut off 2-digit years between 1900s and 2000s?
 * from http://support.microsoft.com/kb/244664:
 *   1930-2029 (the most retro of all...)
 * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
 *   1950-2049
 * by Java, from http://stackoverflow.com/questions/2024273/:
 *   now-80 - now+19
 * or FileMaker Pro, from
 *      http://www.filemaker.com/12help/html/add_view_data.4.21.html:
 *   now-70 - now+29
 * but python strptime etc, via
 *      http://docs.python.org/py3k/library/time.html:
 *   1969-2068 (super forward-looking, but static, not sliding!)
 *
 * lets go with now-70 to now+29, and if anyone runs into this problem
 * they can learn the hard way not to use 2-digit years, as no choice we
 * make now will cover all possibilities. mostly this will all be taken
 * care of in initial parsing, should only be an issue for hand-entered data
 * currently (2016) this range is:
 *   1946-2045
 */
exports.dateTime2ms = function(s, calendar) {
    // first check if s is a date object
    if(exports.isJSDate(s)) {
        // Convert to the UTC milliseconds that give the same
        // hours as this date has in the local timezone
        s = Number(s) - s.getTimezoneOffset() * ONEMIN;
        if(s >= MIN_MS && s <= MAX_MS) return s;
        return BADNUM;
    }
    // otherwise only accept strings and numbers
    if(typeof s !== 'string' && typeof s !== 'number') return BADNUM;

    s = String(s);

    var isWorld = isWorldCalendar(calendar);

    // to handle out-of-range dates in international calendars, accept
    // 'G' as a prefix to force the built-in gregorian calendar.
    var s0 = s.charAt(0);
    if(isWorld && (s0 === 'G' || s0 === 'g')) {
        s = s.substr(1);
        calendar = '';
    }

    var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';

    var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
    if(!match) return BADNUM;
    var y = match[1],
        m = match[3] || '1',
        d = Number(match[5] || 1),
        H = Number(match[7] || 0),
        M = Number(match[9] || 0),
        S = Number(match[11] || 0);

    if(isWorld) {
        // disallow 2-digit years for world calendars
        if(y.length === 2) return BADNUM;
        y = Number(y);

        var cDate;
        try {
            var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
            if(isChinese) {
                var isIntercalary = m.charAt(m.length - 1) === 'i';
                m = parseInt(m, 10);
                cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
            }
            else {
                cDate = calInstance.newDate(y, Number(m), d);
            }
        }
        catch(e) { return BADNUM; } // Invalid ... date

        if(!cDate) return BADNUM;

        return ((cDate.toJD() - EPOCHJD) * ONEDAY) +
            (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC);
    }

    if(y.length === 2) {
        y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
    }
    else y = Number(y);

    // new Date uses months from 0; subtract 1 here just so we
    // don't have to do it again during the validity test below
    m -= 1;

    // javascript takes new Date(0..99,m,d) to mean 1900-1999, so
    // to support years 0-99 we need to use setFullYear explicitly
    // Note that 2000 is a leap year.
    var date = new Date(Date.UTC(2000, m, d, H, M));
    date.setUTCFullYear(y);

    if(date.getUTCMonth() !== m) return BADNUM;
    if(date.getUTCDate() !== d) return BADNUM;

    return date.getTime() + S * ONESEC;
};

MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');

// is string s a date? (see above)
exports.isDateTime = function(s, calendar) {
    return (exports.dateTime2ms(s, calendar) !== BADNUM);
};

// pad a number with zeroes, to given # of digits before the decimal point
function lpad(val, digits) {
    return String(val + Math.pow(10, digits)).substr(1);
}

/**
 * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
 * Crop any trailing zeros in time, except never stop right after hours
 * (we could choose to crop '-01' from date too but for now we always
 * show the whole date)
 * Optional range r is the data range that applies, also in ms.
 * If rng is big, the later parts of time will be omitted
 */
var NINETYDAYS = 90 * ONEDAY;
var THREEHOURS = 3 * ONEHOUR;
var FIVEMIN = 5 * ONEMIN;
exports.ms2DateTime = function(ms, r, calendar) {
    if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;

    if(!r) r = 0;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10),
        msRounded = Math.round(ms - msecTenths / 10),
        dateStr, h, m, s, msec10, d;

    if(isWorldCalendar(calendar)) {
        var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD,
            timeMs = Math.floor(mod(ms, ONEDAY));
        try {
            dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar)
                .fromJD(dateJD).formatDate('yyyy-mm-dd');
        }
        catch(e) {
            // invalid date in this calendar - fall back to Gyyyy-mm-dd
            dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
        }

        // yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
        // other things for a few calendars, so we can't trust it. Just pad
        // it manually (after the '-' if there is one)
        if(dateStr.charAt(0) === '-') {
            while(dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
        }
        else {
            while(dateStr.length < 10) dateStr = '0' + dateStr;
        }

        // TODO: if this is faster, we could use this block for extracting
        // the time components of regular gregorian too
        h = (r < NINETYDAYS) ? Math.floor(timeMs / ONEHOUR) : 0;
        m = (r < NINETYDAYS) ? Math.floor((timeMs % ONEHOUR) / ONEMIN) : 0;
        s = (r < THREEHOURS) ? Math.floor((timeMs % ONEMIN) / ONESEC) : 0;
        msec10 = (r < FIVEMIN) ? (timeMs % ONESEC) * 10 + msecTenths : 0;
    }
    else {
        d = new Date(msRounded);

        dateStr = utcFormat('%Y-%m-%d')(d);

        // <90 days: add hours and minutes - never *only* add hours
        h = (r < NINETYDAYS) ? d.getUTCHours() : 0;
        m = (r < NINETYDAYS) ? d.getUTCMinutes() : 0;
        // <3 hours: add seconds
        s = (r < THREEHOURS) ? d.getUTCSeconds() : 0;
        // <5 minutes: add ms (plus one extra digit, this is msec*10)
        msec10 = (r < FIVEMIN) ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
    }

    return includeTime(dateStr, h, m, s, msec10);
};

// For converting old-style milliseconds to date strings,
// we use the local timezone rather than UTC like we use
// everywhere else, both for backward compatibility and
// because that's how people mostly use javasript date objects.
// Clip one extra day off our date range though so we can't get
// thrown beyond the range by the timezone shift.
exports.ms2DateTimeLocal = function(ms) {
    if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;

    var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10),
        d = new Date(Math.round(ms - msecTenths / 10)),
        dateStr = d3.time.format('%Y-%m-%d')(d),
        h = d.getHours(),
        m = d.getMinutes(),
        s = d.getSeconds(),
        msec10 = d.getUTCMilliseconds() * 10 + msecTenths;

    return includeTime(dateStr, h, m, s, msec10);
};

function includeTime(dateStr, h, m, s, msec10) {
    // include each part that has nonzero data in or after it
    if(h || m || s || msec10) {
        dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
        if(s || msec10) {
            dateStr += ':' + lpad(s, 2);
            if(msec10) {
                var digits = 4;
                while(msec10 % 10 === 0) {
                    digits -= 1;
                    msec10 /= 10;
                }
                dateStr += '.' + lpad(msec10, digits);
            }
        }
    }
    return dateStr;
}

// normalize date format to date string, in case it starts as
// a Date object or milliseconds
// optional dflt is the return value if cleaning fails
exports.cleanDate = function(v, dflt, calendar) {
    if(exports.isJSDate(v) || typeof v === 'number') {
        // do not allow milliseconds (old) or jsdate objects (inherently
        // described as gregorian dates) with world calendars
        if(isWorldCalendar(calendar)) {
            Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
            return dflt;
        }

        // NOTE: if someone puts in a year as a number rather than a string,
        // this will mistakenly convert it thinking it's milliseconds from 1970
        // that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
        v = exports.ms2DateTimeLocal(+v);
        if(!v && dflt !== undefined) return dflt;
    }
    else if(!exports.isDateTime(v, calendar)) {
        Loggers.error('unrecognized date', v);
        return dflt;
    }
    return v;
};

/*
 *  Date formatting for ticks and hovertext
 */

/*
 * modDateFormat: Support world calendars, and add one item to
 * d3's vocabulary:
 * %{n}f where n is the max number of digits of fractional seconds
 */
var fracMatch = /%\d?f/g;
function modDateFormat(fmt, x, formatter, calendar) {

    fmt = fmt.replace(fracMatch, function(match) {
        var digits = Math.min(+(match.charAt(1)) || 6, 6),
            fracSecs = ((x / 1000 % 1) + 2)
                .toFixed(digits)
                .substr(2).replace(/0+$/, '') || '0';
        return fracSecs;
    });

    var d = new Date(Math.floor(x + 0.05));

    if(isWorldCalendar(calendar)) {
        try {
            fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
        }
        catch(e) {
            return 'Invalid';
        }
    }
    return formatter(fmt)(d);
}

/*
 * formatTime: create a time string from:
 *   x: milliseconds
 *   tr: tickround ('M', 'S', or # digits)
 * only supports UTC times (where every day is 24 hours and 0 is at midnight)
 */
var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
function formatTime(x, tr) {
    var timePart = mod(x + 0.05, ONEDAY);

    var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' +
        lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);

    if(tr !== 'M') {
        if(!isNumeric(tr)) tr = 0; // should only be 'S'

        /*
         * this is a weird one - and shouldn't come up unless people
         * monkey with tick0 in weird ways, but we need to do something!
         * IN PARTICULAR we had better not display garbage (see below)
         * for numbers we always round to the nearest increment of the
         * precision we're showing, and this seems like the right way to
         * handle seconds and milliseconds, as they have a decimal point
         * and people will interpret that to mean rounding like numbers.
         * but for larger increments we floor the value: it's always
         * 2013 until the ball drops on the new year. We could argue about
         * which field it is where we start rounding (should 12:08:59
         * round to 12:09 if we're stopping at minutes?) but for now I'll
         * say we round seconds but floor everything else. BUT that means
         * we need to never round up to 60 seconds, ie 23:59:60
         */
        var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);

        var secStr = (100 + sec).toFixed(tr).substr(1);
        if(tr > 0) {
            secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
        }

        timeStr += ':' + secStr;
    }
    return timeStr;
}

/*
 * formatDate: turn a date into tick or hover label text.
 *
 *   x: milliseconds, the value to convert
 *   fmt: optional, an explicit format string (d3 format, even for world calendars)
 *   tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
 *      used if no explicit fmt is provided
 *   formatter: locale-aware d3 date formatter for standard gregorian calendars
 *      should be the result of exports.getD3DateFormat(gd)
 *   calendar: optional string, the world calendar system to use
 *
 * returns the date/time as a string, potentially with the leading portion
 * on a separate line (after '\n')
 * Note that this means if you provide an explicit format which includes '\n'
 * the axis may choose to strip things after it when they don't change from
 * one tick to the next (as it does with automatic formatting)
 */
exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
    calendar = isWorldCalendar(calendar) && calendar;

    if(!fmt) {
        if(tr === 'y') fmt = extraFormat.year;
        else if(tr === 'm') fmt = extraFormat.month;
        else if(tr === 'd') {
            fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
        }
        else {
            return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
        }
    }

    return modDateFormat(fmt, x, formatter, calendar);
};

/*
 * incrementMonth: make a new milliseconds value from the given one,
 * having changed the month
 *
 * special case for world calendars: multiples of 12 are treated as years,
 * even for calendar systems that don't have (always or ever) 12 months/year
 * TODO: perhaps we need a different code for year increments to support this?
 *
 * ms (number): the initial millisecond value
 * dMonth (int): the (signed) number of months to shift
 * calendar (string): the calendar system to use
 *
 * changing month does not (and CANNOT) always preserve day, since
 * months have different lengths. The worst example of this is:
 *   d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
 *
 * But we want to be able to iterate over the last day of each month,
 * regardless of what its number is.
 * So shift 3 days forward, THEN set the new month, then unshift:
 *   1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
 *
 * Note that odd behavior still exists if you start from the 26th-28th:
 *   1/28 -> 2/28 -> 3/31
 * but at least you can't shift any dates into the wrong month,
 * and ticks on these days incrementing by month would be very unusual
 */
var THREEDAYS = 3 * ONEDAY;
exports.incrementMonth = function(ms, dMonth, calendar) {
    calendar = isWorldCalendar(calendar) && calendar;

    // pull time out and operate on pure dates, then add time back at the end
    // this gives maximum precision - not that we *normally* care if we're
    // incrementing by month, but better to be safe!
    var timeMs = mod(ms, ONEDAY);
    ms = Math.round(ms - timeMs);

    if(calendar) {
        try {
            var dateJD = Math.round(ms / ONEDAY) + EPOCHJD,
                calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar),
                cDate = calInstance.fromJD(dateJD);

            if(dMonth % 12) calInstance.add(cDate, dMonth, 'm');
            else calInstance.add(cDate, dMonth / 12, 'y');

            return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
        }
        catch(e) {
            Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
            // then keep going in gregorian even though the result will be 'Invalid'
        }
    }

    var y = new Date(ms + THREEDAYS);
    return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
};

/*
 * findExactDates: what fraction of data is exact days, months, or years?
 *
 * data: array of millisecond values
 * calendar (string) the calendar to test against
 */
exports.findExactDates = function(data, calendar) {
    var exactYears = 0,
        exactMonths = 0,
        exactDays = 0,
        blankCount = 0,
        d,
        di;

    var calInstance = (
        isWorldCalendar(calendar) &&
        Registry.getComponentMethod('calendars', 'getCal')(calendar)
    );

    for(var i = 0; i < data.length; i++) {
        di = data[i];

        // not date data at all
        if(!isNumeric(di)) {
            blankCount ++;
            continue;
        }

        // not an exact date
        if(di % ONEDAY) continue;

        if(calInstance) {
            try {
                d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
                if(d.day() === 1) {
                    if(d.month() === 1) exactYears++;
                    else exactMonths++;
                }
                else exactDays++;
            }
            catch(e) {
                // invalid date in this calendar - ignore it here.
            }
        }
        else {
            d = new Date(di);
            if(d.getUTCDate() === 1) {
                if(d.getUTCMonth() === 0) exactYears++;
                else exactMonths++;
            }
            else exactDays++;
        }
    }
    exactMonths += exactYears;
    exactDays += exactMonths;

    var dataCount = data.length - blankCount;

    return {
        exactYears: exactYears / dataCount,
        exactMonths: exactMonths / dataCount,
        exactDays: exactDays / dataCount
    };
};

},{"../constants/numerical":145,"../registry":254,"./loggers":169,"./mod":171,"d3":6,"fast-isnumeric":9}],155:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * Ensures an array has the right amount of storage space. If it doesn't
 * exist, it creates an array. If it does exist, it returns it if too
 * short or truncates it in-place.
 *
 * The goal is to just reuse memory to avoid a bit of excessive garbage
 * collection.
 */
module.exports = function ensureArray(out, n) {
    if(!Array.isArray(out)) out = [];

    // If too long, truncate. (If too short, it will grow
    // automatically so we don't care about that case)
    out.length = n;

    return out;
};

},{}],156:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/* global jQuery:false */

var EventEmitter = require('events').EventEmitter;

var Events = {

    init: function(plotObj) {

        /*
         * If we have already instantiated an emitter for this plot
         * return early.
         */
        if(plotObj._ev instanceof EventEmitter) return plotObj;

        var ev = new EventEmitter();
        var internalEv = new EventEmitter();

        /*
         * Assign to plot._ev while we still live in a land
         * where plot is a DOM element with stuff attached to it.
         * In the future we can make plot the event emitter itself.
         */
        plotObj._ev = ev;

        /*
         * Create a second event handler that will manage events *internally*.
         * This allows parts of plotly to respond to thing like relayout without
         * having to use the user-facing event handler. They cannot peacefully
         * coexist on the same handler because a user invoking
         * plotObj.removeAllListeners() would detach internal events, breaking
         * plotly.
         */
        plotObj._internalEv = internalEv;

        /*
         * Assign bound methods from the ev to the plot object. These methods
         * will reference the 'this' of plot._ev even though they are methods
         * of plot. This will keep the event machinery away from the plot object
         * which currently is often a DOM element but presents an API that will
         * continue to function when plot becomes an emitter. Not all EventEmitter
         * methods have been bound to `plot` as some do not currently add value to
         * the Plotly event API.
         */
        plotObj.on = ev.on.bind(ev);
        plotObj.once = ev.once.bind(ev);
        plotObj.removeListener = ev.removeListener.bind(ev);
        plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);

        /*
         * Create functions for managing internal events. These are *only* triggered
         * by the mirroring of external events via the emit function.
         */
        plotObj._internalOn = internalEv.on.bind(internalEv);
        plotObj._internalOnce = internalEv.once.bind(internalEv);
        plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv);
        plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv);

        /*
         * We must wrap emit to continue to support JQuery events. The idea
         * is to check to see if the user is using JQuery events, if they are
         * we emit JQuery events to trigger user handlers as well as the EventEmitter
         * events.
         */
        plotObj.emit = function(event, data) {
            if(typeof jQuery !== 'undefined') {
                jQuery(plotObj).trigger(event, data);
            }

            ev.emit(event, data);
            internalEv.emit(event, data);
        };

        return plotObj;
    },

    /*
     * This function behaves like jQuery's triggerHandler. It calls
     * all handlers for a particular event and returns the return value
     * of the LAST handler. This function also triggers jQuery's
     * triggerHandler for backwards compatibility.
     */
    triggerHandler: function(plotObj, event, data) {
        var jQueryHandlerValue;
        var nodeEventHandlerValue;

        /*
         * If jQuery exists run all its handlers for this event and
         * collect the return value of the LAST handler function
         */
        if(typeof jQuery !== 'undefined') {
            jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data);
        }

        /*
         * Now run all the node style event handlers
         */
        var ev = plotObj._ev;
        if(!ev) return jQueryHandlerValue;

        var handlers = ev._events[event];
        if(!handlers) return jQueryHandlerValue;

        // making sure 'this' is the EventEmitter instance
        function apply(handler) {
            // The 'once' case, we can't just call handler() as we need
            // the return value here. So,
            // - remove handler
            // - call listener and grab return value!
            // - stash 'fired' key to not call handler twice
            if(handler.listener) {
                ev.removeListener(event, handler.listener);
                if(!handler.fired) {
                    handler.fired = true;
                    return handler.listener.apply(ev, [data]);
                }
            } else {
                return handler.apply(ev, [data]);
            }
        }

        // handlers can be function or an array of functions
        handlers = Array.isArray(handlers) ? handlers : [handlers];

        var i;
        for(i = 0; i < handlers.length - 1; i++) {
            apply(handlers[i]);
        }
        // now call the final handler and collect its value
        nodeEventHandlerValue = apply(handlers[i]);

        /*
         * Return either the jQuery handler value if it exists or the
         * nodeEventHandler value. jQuery event value supersedes nodejs
         * events for backwards compatibility reasons.
         */
        return jQueryHandlerValue !== undefined ?
            jQueryHandlerValue :
            nodeEventHandlerValue;
    },

    purge: function(plotObj) {
        delete plotObj._ev;
        delete plotObj.on;
        delete plotObj.once;
        delete plotObj.removeListener;
        delete plotObj.removeAllListeners;
        delete plotObj.emit;

        delete plotObj._ev;
        delete plotObj._internalEv;
        delete plotObj._internalOn;
        delete plotObj._internalOnce;
        delete plotObj._removeInternalListener;
        delete plotObj._removeAllInternalListeners;

        return plotObj;
    }

};

module.exports = Events;

},{"events":8}],157:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isPlainObject = require('./is_plain_object.js');
var isArray = Array.isArray;

function primitivesLoopSplice(source, target) {
    var i, value;
    for(i = 0; i < source.length; i++) {
        value = source[i];
        if(value !== null && typeof(value) === 'object') {
            return false;
        }
        if(value !== void(0)) {
            target[i] = value;
        }
    }
    return true;
}

exports.extendFlat = function() {
    return _extend(arguments, false, false, false);
};

exports.extendDeep = function() {
    return _extend(arguments, true, false, false);
};

exports.extendDeepAll = function() {
    return _extend(arguments, true, true, false);
};

exports.extendDeepNoArrays = function() {
    return _extend(arguments, true, false, true);
};

/*
 * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
 * All credit to the jQuery authors for perfecting this amazing utility.
 *
 * API difference with jQuery version:
 * - No optional boolean (true -> deep extend) first argument,
 *   use `extendFlat` for first-level only extend and
 *   use `extendDeep` for a deep extend.
 *
 * Other differences with jQuery version:
 * - Uses a modern (and faster) isPlainObject routine.
 * - Expected to work with object {} and array [] arguments only.
 * - Does not check for circular structure.
 *   FYI: jQuery only does a check across one level.
 *   Warning: this might result in infinite loops.
 *
 */
function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
    var target = inputs[0],
        length = inputs.length;

    var input, key, src, copy, copyIsArray, clone, allPrimitives;

    // TODO does this do the right thing for typed arrays?

    if(length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {

        allPrimitives = primitivesLoopSplice(inputs[1], target);

        if(allPrimitives) {
            return target;
        } else {
            target.splice(0, target.length); // reset target and continue to next block
        }
    }

    for(var i = 1; i < length; i++) {
        input = inputs[i];

        for(key in input) {
            src = target[key];
            copy = input[key];

            // Stop early and just transfer the array if array copies are disallowed:
            if(noArrayCopies && isArray(copy)) {
                target[key] = copy;
            }

            // recurse if we're merging plain objects or arrays
            else if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
                if(copyIsArray) {
                    copyIsArray = false;
                    clone = src && isArray(src) ? src : [];
                } else {
                    clone = src && isPlainObject(src) ? src : {};
                }

                // never move original objects, clone them
                target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
            }

            // don't bring in undefined values, except for extendDeepAll
            else if(typeof copy !== 'undefined' || keepAllKeys) {
                target[key] = copy;
            }
        }
    }

    return target;
}

},{"./is_plain_object.js":166}],158:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


/**
 * Return news array containing only the unique items
 * found in input array.
 *
 * IMPORTANT: Note that items are considered unique
 * if `String({})` is unique. For example;
 *
 *  Lib.filterUnique([ { a: 1 }, { b: 2 } ])
 *
 *  returns [{ a: 1 }]
 *
 * and
 *
 *  Lib.filterUnique([ '1', 1 ])
 *
 *  returns ['1']
 *
 *
 * @param {array} array base array
 * @return {array} new filtered array
 */
module.exports = function filterUnique(array) {
    var seen = {},
        out = [],
        j = 0;

    for(var i = 0; i < array.length; i++) {
        var item = array[i];

        if(seen[item] !== 1) {
            seen[item] = 1;
            out[j++] = item;
        }
    }

    return out;
};

},{}],159:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/** Filter out object items with visible !== true
 *  insider array container.
 *
 *  @param {array of objects} container
 *  @return {array of objects} of length <= container
 *
 */
module.exports = function filterVisible(container) {
    var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
    var out = [];

    for(var i = 0; i < container.length; i++) {
        var item = container[i];
        if(filterFn(item)) out.push(item);
    }

    return out;
};

function baseFilter(item) {
    return item.visible === true;
}

function calcDataFilter(item) {
    return item[0].trace.visible === true;
}

function isCalcData(cont) {
    return (
        Array.isArray(cont) &&
        Array.isArray(cont[0]) &&
        cont[0][0] &&
        cont[0][0].trace
    );
}

},{}],160:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var BADNUM = require('../constants/numerical').BADNUM;

/**
 * Convert calcTrace to GeoJSON 'MultiLineString' coordinate arrays
 *
 * @param {object} calcTrace
 *  gd.calcdata item.
 *  Note that calcTrace[i].lonlat is assumed to be defined
 *
 * @return {array}
 *  return line coords array (or array of arrays)
 *
 */
exports.calcTraceToLineCoords = function(calcTrace) {
    var trace = calcTrace[0].trace;
    var connectgaps = trace.connectgaps;

    var coords = [];
    var lineString = [];

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var lonlat = calcPt.lonlat;

        if(lonlat[0] !== BADNUM) {
            lineString.push(lonlat);
        } else if(!connectgaps && lineString.length > 0) {
            coords.push(lineString);
            lineString = [];
        }
    }

    if(lineString.length > 0) {
        coords.push(lineString);
    }

    return coords;
};


/**
 * Make line ('LineString' or 'MultiLineString') GeoJSON
 *
 * @param {array} coords
 *  results form calcTraceToLineCoords
 * @return {object} out
 *  GeoJSON object
 *
 */
exports.makeLine = function(coords) {
    if(coords.length === 1) {
        return {
            type: 'LineString',
            coordinates: coords[0]
        };
    } else {
        return {
            type: 'MultiLineString',
            coordinates: coords
        };
    }
};

/**
 * Make polygon ('Polygon' or 'MultiPolygon') GeoJSON
 *
 * @param {array} coords
 *  results form calcTraceToLineCoords
 * @return {object} out
 *  GeoJSON object
 */
exports.makePolygon = function(coords) {
    if(coords.length === 1) {
        return {
            type: 'Polygon',
            coordinates: coords
        };
    } else {
        var _coords = new Array(coords.length);

        for(var i = 0; i < coords.length; i++) {
            _coords[i] = [coords[i]];
        }

        return {
            type: 'MultiPolygon',
            coordinates: _coords
        };
    }
};

/**
 * Make blank GeoJSON
 *
 * @return {object}
 *  Blank GeoJSON object
 *
 */
exports.makeBlank = function() {
    return {
        type: 'Point',
        coordinates: []
    };
};

},{"../constants/numerical":145}],161:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var mod = require('./mod');

/*
 * look for intersection of two line segments
 *   (1->2 and 3->4) - returns array [x,y] if they do, null if not
 */
exports.segmentsIntersect = segmentsIntersect;
function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
    var a = x2 - x1,
        b = x3 - x1,
        c = x4 - x3,
        d = y2 - y1,
        e = y3 - y1,
        f = y4 - y3,
        det = a * f - c * d;
    // parallel lines? intersection is undefined
    // ignore the case where they are colinear
    if(det === 0) return null;
    var t = (b * f - c * e) / det,
        u = (b * d - a * e) / det;
    // segments do not intersect?
    if(u < 0 || u > 1 || t < 0 || t > 1) return null;

    return {x: x1 + a * t, y: y1 + d * t};
}

/*
 * find the minimum distance between two line segments (1->2 and 3->4)
 */
exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
    if(segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;

    // the two segments and their lengths squared
    var x12 = x2 - x1;
    var y12 = y2 - y1;
    var x34 = x4 - x3;
    var y34 = y4 - y3;
    var l2_12 = x12 * x12 + y12 * y12;
    var l2_34 = x34 * x34 + y34 * y34;

    // calculate distance squared, then take the sqrt at the very end
    var dist2 = Math.min(
        perpDistance2(x12, y12, l2_12, x3 - x1, y3 - y1),
        perpDistance2(x12, y12, l2_12, x4 - x1, y4 - y1),
        perpDistance2(x34, y34, l2_34, x1 - x3, y1 - y3),
        perpDistance2(x34, y34, l2_34, x2 - x3, y2 - y3)
    );

    return Math.sqrt(dist2);
};

/*
 * distance squared from segment ab to point c
 * [xab, yab] is the vector b-a
 * [xac, yac] is the vector c-a
 * l2_ab is the length squared of (b-a), just to simplify calculation
 */
function perpDistance2(xab, yab, l2_ab, xac, yac) {
    var fc_ab = (xac * xab + yac * yab);
    if(fc_ab < 0) {
        // point c is closer to point a
        return xac * xac + yac * yac;
    }
    else if(fc_ab > l2_ab) {
        // point c is closer to point b
        var xbc = xac - xab;
        var ybc = yac - yab;
        return xbc * xbc + ybc * ybc;
    }
    else {
        // perpendicular distance is the shortest
        var crossProduct = xac * yab - yac * xab;
        return crossProduct * crossProduct / l2_ab;
    }
}

// a very short-term cache for getTextLocation, just because
// we're often looping over the same locations multiple times
// invalidated as soon as we look at a different path
var locationCache, workingPath, workingTextWidth;

// turn a path and position along it into x, y, and angle for the given text
exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
    if(path !== workingPath || textWidth !== workingTextWidth) {
        locationCache = {};
        workingPath = path;
        workingTextWidth = textWidth;
    }
    if(locationCache[positionOnPath]) {
        return locationCache[positionOnPath];
    }

    // for the angle, use points on the path separated by the text width
    // even though due to curvature, the text will cover a bit more than that
    var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
    var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
    // note: atan handles 1/0 nicely
    var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
    // center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
    // that's the average position of this segment, assuming it's roughly quadratic
    var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
    var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
    var y = (pCenter.y * 4 + p0.y + p1.y) / 6;

    var out = {x: x, y: y, theta: theta};
    locationCache[positionOnPath] = out;
    return out;
};

exports.clearLocationCache = function() {
    workingPath = null;
};

/*
 * Find the segment of `path` that's within the visible area
 * given by `bounds` {left, right, top, bottom}, to within a
 * precision of `buffer` px
 *
 * returns: undefined if nothing is visible, else object:
 * {
 *   min: position where the path first enters bounds, or 0 if it
 *        starts within bounds
 *   max: position where the path last exits bounds, or the path length
 *        if it finishes within bounds
 *   len: max - min, ie the length of visible path
 *   total: the total path length - just included so the caller doesn't
 *        need to call path.getTotalLength() again
 *   isClosed: true iff the start and end points of the path are both visible
 *        and are at the same point
 * }
 *
 * Works by starting from either end and repeatedly finding the distance from
 * that point to the plot area, and if it's outside the plot, moving along the
 * path by that distance (because the plot must be at least that far away on
 * the path). Note that if a path enters, exits, and re-enters the plot, we
 * will not capture this behavior.
 */
exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
    var left = bounds.left;
    var right = bounds.right;
    var top = bounds.top;
    var bottom = bounds.bottom;

    var pMin = 0;
    var pTotal = path.getTotalLength();
    var pMax = pTotal;

    var pt0, ptTotal;

    function getDistToPlot(len) {
        var pt = path.getPointAtLength(len);

        // hold on to the start and end points for `closed`
        if(len === 0) pt0 = pt;
        else if(len === pTotal) ptTotal = pt;

        var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
        var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
        return Math.sqrt(dx * dx + dy * dy);
    }

    var distToPlot = getDistToPlot(pMin);
    while(distToPlot) {
        pMin += distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMin);
    }

    distToPlot = getDistToPlot(pMax);
    while(distToPlot) {
        pMax -= distToPlot + buffer;
        if(pMin > pMax) return;
        distToPlot = getDistToPlot(pMax);
    }

    return {
        min: pMin,
        max: pMax,
        len: pMax - pMin,
        total: pTotal,
        isClosed: pMin === 0 && pMax === pTotal &&
            Math.abs(pt0.x - ptTotal.x) < 0.1 &&
            Math.abs(pt0.y - ptTotal.y) < 0.1
    };
};

/**
 * Find point on SVG path corresponding to a given constraint coordinate
 *
 * @param {SVGPathElement} path
 * @param {Number} val : constraint coordinate value
 * @param {String} coord : 'x' or 'y' the constraint coordinate
 * @param {Object} opts :
 *  - {Number} pathLength : supply total path length before hand
 *  - {Number} tolerance
 *  - {Number} iterationLimit
 * @return {SVGPoint}
 */
exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
    opts = opts || {};

    var pathLength = opts.pathLength || path.getTotalLength();
    var tolerance = opts.tolerance || 1e-3;
    var iterationLimit = opts.iterationLimit || 30;

    // if path starts at a val greater than the path tail (like on vertical violins),
    // we must flip the sign of the computed diff.
    var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;

    var i = 0;
    var b0 = 0;
    var b1 = pathLength;
    var mid;
    var pt;
    var diff;

    while(i < iterationLimit) {
        mid = (b0 + b1) / 2;
        pt = path.getPointAtLength(mid);
        diff = pt[coord] - val;

        if(Math.abs(diff) < tolerance) {
            return pt;
        } else {
            if(mul * diff > 0) {
                b1 = mid;
            } else {
                b0 = mid;
            }
            i++;
        }
    }
    return pt;
};

},{"./mod":171}],162:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Allow referencing a graph DOM element either directly
 * or by its id string
 *
 * @param {HTMLDivElement|string} gd: a graph element or its id
 *
 * @returns {HTMLDivElement} the DOM element of the graph
 */
module.exports = function(gd) {
    var gdElement;

    if(typeof gd === 'string') {
        gdElement = document.getElementById(gd);

        if(gdElement === null) {
            throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
        }

        return gdElement;
    }
    else if(gd === null || gd === undefined) {
        throw new Error('DOM element provided is null or undefined');
    }

    return gd;  // otherwise assume that gd is a DOM element
};

},{}],163:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Simple helper functions
// none of these need any external deps

module.exports = function identity(d) { return d; };

},{}],164:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var numConstants = require('../constants/numerical');
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;

var lib = module.exports = {};

lib.nestedProperty = require('./nested_property');
lib.keyedContainer = require('./keyed_container');
lib.relativeAttr = require('./relative_attr');
lib.isPlainObject = require('./is_plain_object');
lib.mod = require('./mod');
lib.toLogRange = require('./to_log_range');
lib.relinkPrivateKeys = require('./relink_private');
lib.ensureArray = require('./ensure_array');

var isArrayModule = require('./is_array');
lib.isTypedArray = isArrayModule.isTypedArray;
lib.isArrayOrTypedArray = isArrayModule.isArrayOrTypedArray;
lib.isArray1D = isArrayModule.isArray1D;

var coerceModule = require('./coerce');
lib.valObjectMeta = coerceModule.valObjectMeta;
lib.coerce = coerceModule.coerce;
lib.coerce2 = coerceModule.coerce2;
lib.coerceFont = coerceModule.coerceFont;
lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
lib.validate = coerceModule.validate;

var datesModule = require('./dates');
lib.dateTime2ms = datesModule.dateTime2ms;
lib.isDateTime = datesModule.isDateTime;
lib.ms2DateTime = datesModule.ms2DateTime;
lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
lib.cleanDate = datesModule.cleanDate;
lib.isJSDate = datesModule.isJSDate;
lib.formatDate = datesModule.formatDate;
lib.incrementMonth = datesModule.incrementMonth;
lib.dateTick0 = datesModule.dateTick0;
lib.dfltRange = datesModule.dfltRange;
lib.findExactDates = datesModule.findExactDates;
lib.MIN_MS = datesModule.MIN_MS;
lib.MAX_MS = datesModule.MAX_MS;

var searchModule = require('./search');
lib.findBin = searchModule.findBin;
lib.sorterAsc = searchModule.sorterAsc;
lib.sorterDes = searchModule.sorterDes;
lib.distinctVals = searchModule.distinctVals;
lib.roundUp = searchModule.roundUp;

var statsModule = require('./stats');
lib.aggNums = statsModule.aggNums;
lib.len = statsModule.len;
lib.mean = statsModule.mean;
lib.variance = statsModule.variance;
lib.stdev = statsModule.stdev;
lib.interp = statsModule.interp;

var matrixModule = require('./matrix');
lib.init2dArray = matrixModule.init2dArray;
lib.transposeRagged = matrixModule.transposeRagged;
lib.dot = matrixModule.dot;
lib.translationMatrix = matrixModule.translationMatrix;
lib.rotationMatrix = matrixModule.rotationMatrix;
lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
lib.apply2DTransform = matrixModule.apply2DTransform;
lib.apply2DTransform2 = matrixModule.apply2DTransform2;

var anglesModule = require('./angles');
lib.deg2rad = anglesModule.deg2rad;
lib.rad2deg = anglesModule.rad2deg;
lib.wrap360 = anglesModule.wrap360;
lib.wrap180 = anglesModule.wrap180;

var geom2dModule = require('./geometry2d');
lib.segmentsIntersect = geom2dModule.segmentsIntersect;
lib.segmentDistance = geom2dModule.segmentDistance;
lib.getTextLocation = geom2dModule.getTextLocation;
lib.clearLocationCache = geom2dModule.clearLocationCache;
lib.getVisibleSegment = geom2dModule.getVisibleSegment;
lib.findPointOnPath = geom2dModule.findPointOnPath;

var extendModule = require('./extend');
lib.extendFlat = extendModule.extendFlat;
lib.extendDeep = extendModule.extendDeep;
lib.extendDeepAll = extendModule.extendDeepAll;
lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;

var loggersModule = require('./loggers');
lib.log = loggersModule.log;
lib.warn = loggersModule.warn;
lib.error = loggersModule.error;

var regexModule = require('./regex');
lib.counterRegex = regexModule.counter;

var throttleModule = require('./throttle');
lib.throttle = throttleModule.throttle;
lib.throttleDone = throttleModule.done;
lib.clearThrottle = throttleModule.clear;

lib.getGraphDiv = require('./get_graph_div');

lib._ = require('./localize');

lib.notifier = require('./notifier');

lib.filterUnique = require('./filter_unique');
lib.filterVisible = require('./filter_visible');
lib.pushUnique = require('./push_unique');

lib.cleanNumber = require('./clean_number');

lib.ensureNumber = function num(v) {
    if(!isNumeric(v)) return BADNUM;
    v = Number(v);
    if(v < -FP_SAFE || v > FP_SAFE) return BADNUM;
    return isNumeric(v) ? Number(v) : BADNUM;
};

lib.noop = require('./noop');
lib.identity = require('./identity');

/**
 * swap x and y of the same attribute in container cont
 * specify attr with a ? in place of x/y
 * you can also swap other things than x/y by providing part1 and part2
 */
lib.swapAttrs = function(cont, attrList, part1, part2) {
    if(!part1) part1 = 'x';
    if(!part2) part2 = 'y';
    for(var i = 0; i < attrList.length; i++) {
        var attr = attrList[i],
            xp = lib.nestedProperty(cont, attr.replace('?', part1)),
            yp = lib.nestedProperty(cont, attr.replace('?', part2)),
            temp = xp.get();
        xp.set(yp.get());
        yp.set(temp);
    }
};

/**
 * SVG painter's algo worked around with reinsertion
 */
lib.raiseToTop = function raiseToTop(elem) {
    elem.parentNode.appendChild(elem);
};

/**
 * cancel a possibly pending transition; returned selection may be used by caller
 */
lib.cancelTransition = function(selection) {
    return selection.transition().duration(0);
};

// constrain - restrict a number v to be between v0 and v1
lib.constrain = function(v, v0, v1) {
    if(v0 > v1) return Math.max(v1, Math.min(v0, v));
    return Math.max(v0, Math.min(v1, v));
};

/**
 * do two bounding boxes from getBoundingClientRect,
 * ie {left,right,top,bottom,width,height}, overlap?
 * takes optional padding pixels
 */
lib.bBoxIntersect = function(a, b, pad) {
    pad = pad || 0;
    return (a.left <= b.right + pad &&
            b.left <= a.right + pad &&
            a.top <= b.bottom + pad &&
            b.top <= a.bottom + pad);
};

/*
 * simpleMap: alternative to Array.map that only
 * passes on the element and up to 2 extra args you
 * provide (but not the array index or the whole array)
 *
 * array: the array to map it to
 * func: the function to apply
 * x1, x2: optional extra args
 */
lib.simpleMap = function(array, func, x1, x2) {
    var len = array.length,
        out = new Array(len);
    for(var i = 0; i < len; i++) out[i] = func(array[i], x1, x2);
    return out;
};

// random string generator
lib.randstr = function randstr(existing, bits, base) {
    /*
     * Include number of bits, the base of the string you want
     * and an optional array of existing strings to avoid.
     */
    if(!base) base = 16;
    if(bits === undefined) bits = 24;
    if(bits <= 0) return '0';

    var digits = Math.log(Math.pow(2, bits)) / Math.log(base),
        res = '',
        i,
        b,
        x;

    for(i = 2; digits === Infinity; i *= 2) {
        digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
    }

    var rem = digits - Math.floor(digits);

    for(i = 0; i < Math.floor(digits); i++) {
        x = Math.floor(Math.random() * base).toString(base);
        res = x + res;
    }

    if(rem) {
        b = Math.pow(base, rem);
        x = Math.floor(Math.random() * b).toString(base);
        res = x + res;
    }

    var parsed = parseInt(res, base);
    if((existing && (existing.indexOf(res) > -1)) ||
         (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
        return randstr(existing, bits, base);
    }
    else return res;
};

lib.OptionControl = function(opt, optname) {
    /*
     * An environment to contain all option setters and
     * getters that collectively modify opts.
     *
     * You can call up opts from any function in new object
     * as this.optname || this.opt
     *
     * See FitOpts for example of usage
     */
    if(!opt) opt = {};
    if(!optname) optname = 'opt';

    var self = {};
    self.optionList = [];

    self._newoption = function(optObj) {
        optObj[optname] = opt;
        self[optObj.name] = optObj;
        self.optionList.push(optObj);
    };

    self['_' + optname] = opt;
    return self;
};

/**
 * lib.smooth: smooth arrayIn by convolving with
 * a hann window with given full width at half max
 * bounce the ends in, so the output has the same length as the input
 */
lib.smooth = function(arrayIn, FWHM) {
    FWHM = Math.round(FWHM) || 0; // only makes sense for integers
    if(FWHM < 2) return arrayIn;

    var alen = arrayIn.length,
        alen2 = 2 * alen,
        wlen = 2 * FWHM - 1,
        w = new Array(wlen),
        arrayOut = new Array(alen),
        i,
        j,
        k,
        v;

    // first make the window array
    for(i = 0; i < wlen; i++) {
        w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
    }

    // now do the convolution
    for(i = 0; i < alen; i++) {
        v = 0;
        for(j = 0; j < wlen; j++) {
            k = i + j + 1 - FWHM;

            // multibounce
            if(k < -alen) k -= alen2 * Math.round(k / alen2);
            else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);

            // single bounce
            if(k < 0) k = - 1 - k;
            else if(k >= alen) k = alen2 - 1 - k;

            v += arrayIn[k] * w[j];
        }
        arrayOut[i] = v;
    }

    return arrayOut;
};

/**
 * syncOrAsync: run a sequence of functions synchronously
 * as long as its returns are not promises (ie have no .then)
 * includes one argument arg to send to all functions...
 * this is mainly just to prevent us having to make wrapper functions
 * when the only purpose of the wrapper is to reference gd
 * and a final step to be executed at the end
 * TODO: if there's an error and everything is sync,
 * this doesn't happen yet because we want to make sure
 * that it gets reported
 */
lib.syncOrAsync = function(sequence, arg, finalStep) {
    var ret, fni;

    function continueAsync() {
        return lib.syncOrAsync(sequence, arg, finalStep);
    }

    while(sequence.length) {
        fni = sequence.splice(0, 1)[0];
        ret = fni(arg);

        if(ret && ret.then) {
            return ret.then(continueAsync)
                .then(undefined, lib.promiseError);
        }
    }

    return finalStep && finalStep(arg);
};


/**
 * Helper to strip trailing slash, from
 * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
 */
lib.stripTrailingSlash = function(str) {
    if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
    return str;
};

lib.noneOrAll = function(containerIn, containerOut, attrList) {
    /**
     * some attributes come together, so if you have one of them
     * in the input, you should copy the default values of the others
     * to the input as well.
     */
    if(!containerIn) return;

    var hasAny = false,
        hasAll = true,
        i,
        val;

    for(i = 0; i < attrList.length; i++) {
        val = containerIn[attrList[i]];
        if(val !== undefined && val !== null) hasAny = true;
        else hasAll = false;
    }

    if(hasAny && !hasAll) {
        for(i = 0; i < attrList.length; i++) {
            containerIn[attrList[i]] = containerOut[attrList[i]];
        }
    }
};

/** merges calcdata field (given by cdAttr) with traceAttr values
 *
 * N.B. Loop over minimum of cd.length and traceAttr.length
 * i.e. it does not try to fill in beyond traceAttr.length-1
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 */
lib.mergeArray = function(traceAttr, cd, cdAttr) {
    if(lib.isArrayOrTypedArray(traceAttr)) {
        var imax = Math.min(traceAttr.length, cd.length);
        for(var i = 0; i < imax; i++) cd[i][cdAttr] = traceAttr[i];
    }
};

/** fills calcdata field (given by cdAttr) with traceAttr values
 *  or function of traceAttr values (e.g. some fallback)
 *
 * N.B. Loops over all cd items.
 *
 * @param {array} traceAttr : trace attribute
 * @param {object} cd : calcdata trace
 * @param {string} cdAttr : calcdata key
 * @param {function} [fn] : optional function to apply to each array item
 */
lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
    fn = fn || lib.identity;

    if(lib.isArrayOrTypedArray(traceAttr)) {
        for(var i = 0; i < cd.length; i++) {
            cd[i][cdAttr] = fn(traceAttr[i]);
        }
    }
};

/** Handler for trace-wide vs per-point options
 *
 * @param {object} trace : (full) trace object
 * @param {number} ptNumber : index of the point in question
 * @param {string} astr : attribute string
 * @param {function} [fn] : optional function to apply to each array item
 *
 * @return {any}
 */
lib.castOption = function(trace, ptNumber, astr, fn) {
    fn = fn || lib.identity;

    var val = lib.nestedProperty(trace, astr).get();

    if(lib.isArrayOrTypedArray(val)) {
        if(Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
            return fn(val[ptNumber[0]][ptNumber[1]]);
        } else {
            return fn(val[ptNumber]);
        }
    } else {
        return val;
    }
};

/** Extract option from calcdata item, correctly falling back to
 *  trace value if not found.
 *
 *  @param {object} calcPt : calcdata[i][j] item
 *  @param {object} trace : (full) trace object
 *  @param {string} calcKey : calcdata key
 *  @param {string} traceKey : aka trace attribute string
 *  @return {any}
 */
lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
    if(calcKey in calcPt) return calcPt[calcKey];

    // fallback to trace value,
    //   must check if value isn't itself an array
    //   which means the trace attribute has a corresponding
    //   calcdata key, but its value is falsy
    var traceVal = lib.nestedProperty(trace, traceKey).get();
    if(!Array.isArray(traceVal)) return traceVal;
};

/** Tag selected calcdata items
 *
 * N.B. note that point 'index' corresponds to input data array index
 *  whereas 'number' is its post-transform version.
 *
 * @param {array} calcTrace
 * @param {object} trace
 *  - selectedpoints {array}
 *  - _indexToPoints {object}
 * @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
 *  optional map object for trace types that do not have 1-to-1 point number to
 *  calcdata item index correspondence (e.g. histogram)
 */
lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
    var selectedpoints = trace.selectedpoints;
    var indexToPoints = trace._indexToPoints;
    var ptIndex2ptNumber;

    // make pt index-to-number map object, which takes care of transformed traces
    if(indexToPoints) {
        ptIndex2ptNumber = {};
        for(var k in indexToPoints) {
            var pts = indexToPoints[k];
            for(var j = 0; j < pts.length; j++) {
                ptIndex2ptNumber[pts[j]] = k;
            }
        }
    }

    function isPtIndexValid(v) {
        return isNumeric(v) && v >= 0 && v % 1 === 0;
    }

    function isCdIndexValid(v) {
        return v !== undefined && v < calcTrace.length;
    }

    for(var i = 0; i < selectedpoints.length; i++) {
        var ptIndex = selectedpoints[i];

        if(isPtIndexValid(ptIndex)) {
            var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
            var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;

            if(isCdIndexValid(cdIndex)) {
                calcTrace[cdIndex].selected = 1;
            }
        }
    }
};

/** Returns target as set by 'target' transform attribute
 *
 * @param {object} trace : full trace object
 * @param {object} transformOpts : transform option object
 *  - target (string} :
 *      either an attribute string referencing an array in the trace object, or
 *      a set array.
 *
 * @return {array or false} : the target array (NOT a copy!!) or false if invalid
 */
lib.getTargetArray = function(trace, transformOpts) {
    var target = transformOpts.target;

    if(typeof target === 'string' && target) {
        var array = lib.nestedProperty(trace, target).get();
        return Array.isArray(array) ? array : false;
    } else if(Array.isArray(target)) {
        return target;
    }

    return false;
};

/**
 * modified version of jQuery's extend to strip out private objs and functions,
 * and cut arrays down to first <arraylen> or 1 elements
 * because extend-like algorithms are hella slow
 * obj2 is assumed to already be clean of these things (including no arrays)
 */
lib.minExtend = function(obj1, obj2) {
    var objOut = {};
    if(typeof obj2 !== 'object') obj2 = {};
    var arrayLen = 3,
        keys = Object.keys(obj1),
        i,
        k,
        v;
    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj1[k];
        if(k.charAt(0) === '_' || typeof v === 'function') continue;
        else if(k === 'module') objOut[k] = v;
        else if(Array.isArray(v)) objOut[k] = v.slice(0, arrayLen);
        else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
        else objOut[k] = v;
    }

    keys = Object.keys(obj2);
    for(i = 0; i < keys.length; i++) {
        k = keys[i];
        v = obj2[k];
        if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
            objOut[k] = v;
        }
    }

    return objOut;
};

lib.titleCase = function(s) {
    return s.charAt(0).toUpperCase() + s.substr(1);
};

lib.containsAny = function(s, fragments) {
    for(var i = 0; i < fragments.length; i++) {
        if(s.indexOf(fragments[i]) !== -1) return true;
    }
    return false;
};

lib.isPlotDiv = function(el) {
    var el3 = d3.select(el);
    return el3.node() instanceof HTMLElement &&
        el3.size() &&
        el3.classed('js-plotly-plot');
};

lib.removeElement = function(el) {
    var elParent = el && el.parentNode;
    if(elParent) elParent.removeChild(el);
};

/**
 * for dynamically adding style rules
 * makes one stylesheet that contains all rules added
 * by all calls to this function
 */
lib.addStyleRule = function(selector, styleString) {
    if(!lib.styleSheet) {
        var style = document.createElement('style');
        // WebKit hack :(
        style.appendChild(document.createTextNode(''));
        document.head.appendChild(style);
        lib.styleSheet = style.sheet;
    }
    var styleSheet = lib.styleSheet;

    if(styleSheet.insertRule) {
        styleSheet.insertRule(selector + '{' + styleString + '}', 0);
    }
    else if(styleSheet.addRule) {
        styleSheet.addRule(selector, styleString, 0);
    }
    else lib.warn('addStyleRule failed');
};

lib.isIE = function() {
    return typeof window.navigator.msSaveBlob !== 'undefined';
};

/**
 * Duck typing to recognize a d3 selection, mostly for IE9's benefit
 * because it doesn't handle instanceof like modern browsers
 */
lib.isD3Selection = function(obj) {
    return obj && (typeof obj.classed === 'function');
};

/**
 * Append element to DOM only if not present.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} className : class name of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 *
 * Previously, we were using the following pattern:
 *
 * ```
 * var sel = parent.selectAll('.' + className)
 *     .data([0]);
 *
 * sel.enter().append(nodeType)
 *     .classed(className, true);
 *
 * return sel;
 * ```
 *
 * in numerous places in our codebase to achieve the same behavior.
 *
 * The logic below performs much better, mostly as we are using
 * `.select` instead `.selectAll` that is `querySelector` instead of
 * `querySelectorAll`.
 *
 */
lib.ensureSingle = function(parent, nodeType, className, enterFn) {
    var sel = parent.select(nodeType + (className ? '.' + className : ''));
    if(sel.size()) return sel;

    var layer = parent.append(nodeType).classed(className, true);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Same as Lib.ensureSingle, but using id as selector.
 * This version is mostly used for clipPath nodes.
 *
 * @param {d3 selection} parent : parent selection of the element in question
 * @param {string} nodeType : node type of element to append
 * @param {string} id : id of element in question
 * @param {fn} enterFn (optional) : optional fn applied to entering elements only
 * @return {d3 selection} selection of new layer
 */
lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
    var sel = parent.select(nodeType + '#' + id);
    if(sel.size()) return sel;

    var layer = parent.append(nodeType).attr('id', id);
    if(enterFn) layer.call(enterFn);

    return layer;
};

/**
 * Converts a string path to an object.
 *
 * When given a string containing an array element, it will create a `null`
 * filled array of the given size.
 *
 * @example
 * lib.objectFromPath('nested.test[2].path', 'value');
 * // returns { nested: { test: [null, null, { path: 'value' }]}
 *
 * @param   {string}    path to nested value
 * @param   {*}         any value to be set
 *
 * @return {Object} the constructed object with a full nested path
 */
lib.objectFromPath = function(path, value) {
    var keys = path.split('.'),
        tmpObj,
        obj = tmpObj = {};

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        var el = null;

        var parts = keys[i].match(/(.*)\[([0-9]+)\]/);

        if(parts) {
            key = parts[1];
            el = parts[2];

            tmpObj = tmpObj[key] = [];

            if(i === keys.length - 1) {
                tmpObj[el] = value;
            } else {
                tmpObj[el] = {};
            }

            tmpObj = tmpObj[el];
        } else {

            if(i === keys.length - 1) {
                tmpObj[key] = value;
            } else {
                tmpObj[key] = {};
            }

            tmpObj = tmpObj[key];
        }
    }

    return obj;
};

/**
 * Iterate through an object in-place, converting dotted properties to objects.
 *
 * Examples:
 *
 *   lib.expandObjectPaths({'nested.test.path': 'value'});
 *     => { nested: { test: {path: 'value'}}}
 *
 * It also handles array notation, e.g.:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 'value'});
 *     => { foo: [null, {bar: value}] }
 *
 * It handles merges the results when two properties are specified in parallel:
 *
 *   lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
 *     => { foo: [{bar: 10}, {bar: 20}] }
 *
 * It does NOT, however, merge mulitple mutliply-nested arrays::
 *
 *   lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
 *     => { marker: [null, {range: 4}] }
 */

// Store this to avoid recompiling regex on *every* prop since this may happen many
// many times for animations. Could maybe be inside the function. Not sure about
// scoping vs. recompilation tradeoff, but at least it's not just inlining it into
// the inner loop.
var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;

lib.expandObjectPaths = function(data) {
    var match, key, prop, datum, idx, dest, trailingPath;
    if(typeof data === 'object' && !Array.isArray(data)) {
        for(key in data) {
            if(data.hasOwnProperty(key)) {
                if((match = key.match(dottedPropertyRegex))) {
                    datum = data[key];
                    prop = match[1];

                    delete data[key];

                    data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
                } else if((match = key.match(indexedPropertyRegex))) {
                    datum = data[key];

                    prop = match[1];
                    idx = parseInt(match[2]);

                    delete data[key];

                    data[prop] = data[prop] || [];

                    if(match[3] === '.') {
                        // This is the case where theere are subsequent properties into which
                        // we must recurse, e.g. transforms[0].value
                        trailingPath = match[4];
                        dest = data[prop][idx] = data[prop][idx] || {};

                        // NB: Extend deep no arrays prevents this from working on multiple
                        // nested properties in the same object, e.g.
                        //
                        // {
                        //   foo[0].bar[1].range
                        //   foo[0].bar[0].range
                        // }
                        //
                        // In this case, the extendDeepNoArrays will overwrite one array with
                        // the other, so that both properties *will not* be present in the
                        // result. Fixing this would require a more intelligent tracking
                        // of changes and merging than extendDeepNoArrays currently accomplishes.
                        lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
                    } else {
                        // This is the case where this property is the end of the line,
                        // e.g. xaxis.range[0]
                        data[prop][idx] = lib.expandObjectPaths(datum);
                    }
                } else {
                    data[key] = lib.expandObjectPaths(data[key]);
                }
            }
        }
    }

    return data;
};

/**
 * Converts value to string separated by the provided separators.
 *
 * @example
 * lib.numSeparate(2016, '.,');
 * // returns '2016'
 *
 * @example
 * lib.numSeparate(3000, '.,', true);
 * // returns '3,000'
 *
 * @example
 * lib.numSeparate(1234.56, '|,')
 * // returns '1,234|56'
 *
 * @param   {string|number} value       the value to be converted
 * @param   {string}    separators  string of decimal, then thousands separators
 * @param   {boolean}    separatethousands  boolean, 4-digit integers are separated if true
 *
 * @return  {string}    the value that has been separated
 */
lib.numSeparate = function(value, separators, separatethousands) {
    if(!separatethousands) separatethousands = false;

    if(typeof separators !== 'string' || separators.length === 0) {
        throw new Error('Separator string required for formatting!');
    }

    if(typeof value === 'number') {
        value = String(value);
    }

    var thousandsRe = /(\d+)(\d{3})/,
        decimalSep = separators.charAt(0),
        thouSep = separators.charAt(1);

    var x = value.split('.'),
        x1 = x[0],
        x2 = x.length > 1 ? decimalSep + x[1] : '';

    // Years are ignored for thousands separators
    if(thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
        while(thousandsRe.test(x1)) {
            x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
        }
    }

    return x1 + x2;
};

var TEMPLATE_STRING_REGEX = /%{([^\s%{}]*)}/g;
var SIMPLE_PROPERTY_REGEX = /^\w*$/;

/*
 * Substitute values from an object into a string
 *
 * Examples:
 *  Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
 *  Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
 *
 * @param {string}  input string containing %{...} template strings
 * @param {obj}     data object containing substitution values
 *
 * @return {string} templated string
 */

lib.templateString = function(string, obj) {
    // Not all that useful, but cache nestedProperty instantiation
    // just in case it speeds things up *slightly*:
    var getterCache = {};

    return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) {
        if(SIMPLE_PROPERTY_REGEX.test(key)) {
            return obj[key] || '';
        }
        getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
        return getterCache[key]() || '';
    });
};

/*
 * alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
 */
var char0 = 48;
var char9 = 57;
lib.subplotSort = function(a, b) {
    var l = Math.min(a.length, b.length) + 1;
    var numA = 0;
    var numB = 0;
    for(var i = 0; i < l; i++) {
        var charA = a.charCodeAt(i) || 0;
        var charB = b.charCodeAt(i) || 0;
        var isNumA = charA >= char0 && charA <= char9;
        var isNumB = charB >= char0 && charB <= char9;

        if(isNumA) numA = 10 * numA + charA - char0;
        if(isNumB) numB = 10 * numB + charB - char0;

        if(!isNumA || !isNumB) {
            if(numA !== numB) return numA - numB;
            if(charA !== charB) return charA - charB;
        }
    }
    return numB - numA;
};

// repeatable pseudorandom generator
var randSeed = 2000000000;

lib.seedPseudoRandom = function() {
    randSeed = 2000000000;
};

lib.pseudoRandom = function() {
    var lastVal = randSeed;
    randSeed = (69069 * randSeed + 1) % 4294967296;
    // don't let consecutive vals be too close together
    // gets away from really trying to be random, in favor of better local uniformity
    if(Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
    return randSeed / 4294967296;
};

},{"../constants/numerical":145,"./angles":150,"./clean_number":151,"./coerce":153,"./dates":154,"./ensure_array":155,"./extend":157,"./filter_unique":158,"./filter_visible":159,"./geometry2d":161,"./get_graph_div":162,"./identity":163,"./is_array":165,"./is_plain_object":166,"./keyed_container":167,"./localize":168,"./loggers":169,"./matrix":170,"./mod":171,"./nested_property":172,"./noop":173,"./notifier":174,"./push_unique":177,"./regex":179,"./relative_attr":180,"./relink_private":181,"./search":182,"./stats":184,"./throttle":186,"./to_log_range":187,"d3":6,"fast-isnumeric":9}],165:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// IE9 fallbacks

var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ?
    {isView: function() { return false; }} :
    ArrayBuffer;

var dv = (typeof DataView === 'undefined') ?
    function() {} :
    DataView;

function isTypedArray(a) {
    return ab.isView(a) && !(a instanceof dv);
}

function isArrayOrTypedArray(a) {
    return Array.isArray(a) || isTypedArray(a);
}

/*
 * Test whether an input object is 1D.
 *
 * Assumes we already know the object is an array.
 *
 * Looks only at the first element, if the dimensionality is
 * not consistent we won't figure that out here.
 */
function isArray1D(a) {
    return !isArrayOrTypedArray(a[0]);
}

module.exports = {
    isTypedArray: isTypedArray,
    isArrayOrTypedArray: isArrayOrTypedArray,
    isArray1D: isArray1D
};

},{}],166:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {

    // We need to be a little less strict in the `imagetest` container because
    // of how async image requests are handled.
    //
    // N.B. isPlainObject(new Constructor()) will return true in `imagetest`
    if(window && window.process && window.process.versions) {
        return Object.prototype.toString.call(obj) === '[object Object]';
    }

    return (
        Object.prototype.toString.call(obj) === '[object Object]' &&
        Object.getPrototypeOf(obj) === Object.prototype
    );
};

},{}],167:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var nestedProperty = require('./nested_property');

var SIMPLE_PROPERTY_REGEX = /^\w*$/;

// bitmask for deciding what's updated. Sometimes the name needs to be updated,
// sometimes the value needs to be updated, and sometimes both do. This is just
// a simple way to track what's updated such that it's a simple OR operation to
// assimilate new updates.
//
// The only exception is the UNSET bit that tracks when we need to explicitly
// unset and remove the property. This concrn arises because of the special
// way in which nestedProperty handles null/undefined. When you specify `null`,
// it prunes any unused items in the tree. I ran into some issues with it getting
// null vs undefined confused, so UNSET is just a bit that forces the property
// update to send `null`, removing the property explicitly rather than setting
// it to undefined.
var NONE = 0;
var NAME = 1;
var VALUE = 2;
var BOTH = 3;
var UNSET = 4;

module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
    keyName = keyName || 'name';
    valueName = valueName || 'value';
    var i, arr, baseProp;
    var changeTypes = {};

    if(path && path.length) {
        baseProp = nestedProperty(baseObj, path);
        arr = baseProp.get();
    } else {
        arr = baseObj;
    }

    path = path || '';

    // Construct an index:
    var indexLookup = {};
    if(arr) {
        for(i = 0; i < arr.length; i++) {
            indexLookup[arr[i][keyName]] = i;
        }
    }

    var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);

    var obj = {
        set: function(name, value) {
            var changeType = value === null ? UNSET : NONE;

            // create the base array if necessary
            if(!arr) {
                if(!baseProp || changeType === UNSET) return;

                arr = [];
                baseProp.set(arr);
            }

            var idx = indexLookup[name];
            if(idx === undefined) {
                if(changeType === UNSET) return;

                changeType = changeType | BOTH;
                idx = arr.length;
                indexLookup[name] = idx;
            } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
                changeType = changeType | VALUE;
            }

            var newValue = arr[idx] = arr[idx] || {};
            newValue[keyName] = name;

            if(isSimpleValueProp) {
                newValue[valueName] = value;
            } else {
                nestedProperty(newValue, valueName).set(value);
            }

            // If it's not an unset, force that bit to be unset. This is all related to the fact
            // that undefined and null are a bit specially implemented in nestedProperties.
            if(value !== null) {
                changeType = changeType & ~UNSET;
            }

            changeTypes[idx] = changeTypes[idx] | changeType;

            return obj;
        },
        get: function(name) {
            if(!arr) return;

            var idx = indexLookup[name];

            if(idx === undefined) {
                return undefined;
            } else if(isSimpleValueProp) {
                return arr[idx][valueName];
            } else {
                return nestedProperty(arr[idx], valueName).get();
            }
        },
        rename: function(name, newName) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;
            changeTypes[idx] = changeTypes[idx] | NAME;

            indexLookup[newName] = idx;
            delete indexLookup[name];

            arr[idx][keyName] = newName;

            return obj;
        },
        remove: function(name) {
            var idx = indexLookup[name];

            if(idx === undefined) return obj;

            var object = arr[idx];
            if(Object.keys(object).length > 2) {
                // This object contains more than just the key/value, so unset
                // the value without modifying the entry otherwise:
                changeTypes[idx] = changeTypes[idx] | VALUE;
                return obj.set(name, null);
            }

            if(isSimpleValueProp) {
                for(i = idx; i < arr.length; i++) {
                    changeTypes[i] = changeTypes[i] | BOTH;
                }
                for(i = idx; i < arr.length; i++) {
                    indexLookup[arr[i][keyName]]--;
                }
                arr.splice(idx, 1);
                delete(indexLookup[name]);
            } else {
                // Perform this update *strictly* so we can check whether the result's
                // been pruned. If so, it's a removal. If not, it's a value unset only.
                nestedProperty(object, valueName).set(null);

                // Now check if the top level nested property has any keys left. If so,
                // the object still has values so we only want to unset the key. If not,
                // the entire object can be removed since there's no other data.
                // var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);

                changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
            }

            return obj;
        },
        constructUpdate: function() {
            var astr, idx;
            var update = {};
            var changed = Object.keys(changeTypes);
            for(var i = 0; i < changed.length; i++) {
                idx = changed[i];
                astr = path + '[' + idx + ']';
                if(arr[idx]) {
                    if(changeTypes[idx] & NAME) {
                        update[astr + '.' + keyName] = arr[idx][keyName];
                    }
                    if(changeTypes[idx] & VALUE) {
                        if(isSimpleValueProp) {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName];
                        } else {
                            update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : nestedProperty(arr[idx], valueName).get();
                        }
                    }
                } else {
                    update[astr] = null;
                }
            }

            return update;
        }
    };

    return obj;
};

},{"./nested_property":172}],168:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../registry');

/**
 * localize: translate a string for the current locale
 *
 * @param {object} gd: the graphDiv for context
 *  gd._context.locale determines the language (& optional region/country)
 *  the dictionary for each locale may either be supplied in
 *  gd._context.locales or globally via Plotly.register
 * @param {string} s: the string to translate
 */
module.exports = function localize(gd, s) {
    var locale = gd._context.locale;

    /*
     * Priority of lookup:
     *     contextDicts[locale],
     *     registeredDicts[locale],
     *     contextDicts[baseLocale], (if baseLocale is distinct)
     *     registeredDicts[baseLocale]
     * Return the first translation we find.
     * This way if you have a regionalization you are allowed to specify
     * only what's different from the base locale, everything else will
     * fall back on the base.
     */
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var dict = (locales[locale] || {}).dictionary;
            if(dict) {
                var out = dict[s];
                if(out) return out;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(baseLocale === locale) break;
        locale = baseLocale;
    }

    return s;
};

},{"../registry":254}],169:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/* eslint-disable no-console */

var config = require('../plot_api/plot_config');

var loggers = module.exports = {};

/**
 * ------------------------------------------
 * debugging tools
 * ------------------------------------------
 */

loggers.log = function() {
    if(config.logging > 1) {
        var messages = ['LOG:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.warn = function() {
    if(config.logging > 0) {
        var messages = ['WARN:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.trace || console.log, messages);
    }
};

loggers.error = function() {
    if(config.logging > 0) {
        var messages = ['ERROR:'];

        for(var i = 0; i < arguments.length; i++) {
            messages.push(arguments[i]);
        }

        apply(console.error, messages);
    }
};

/*
 * Robust apply, for IE9 where console.log doesn't support
 * apply like other functions do
 */
function apply(f, args) {
    if(f.apply) {
        f.apply(f, args);
    }
    else {
        for(var i = 0; i < args.length; i++) {
            f(args[i]);
        }
    }
}

},{"../plot_api/plot_config":196}],170:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


exports.init2dArray = function(rowLength, colLength) {
    var array = new Array(rowLength);
    for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
    return array;
};

/**
 * transpose a (possibly ragged) 2d array z. inspired by
 * http://stackoverflow.com/questions/17428587/
 * transposing-a-2d-array-in-javascript
 */
exports.transposeRagged = function(z) {
    var maxlen = 0,
        zlen = z.length,
        i,
        j;
    // Maximum row length:
    for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);

    var t = new Array(maxlen);
    for(i = 0; i < maxlen; i++) {
        t[i] = new Array(zlen);
        for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
    }

    return t;
};

// our own dot function so that we don't need to include numeric
exports.dot = function(x, y) {
    if(!(x.length && y.length) || x.length !== y.length) return null;

    var len = x.length,
        out,
        i;

    if(x[0].length) {
        // mat-vec or mat-mat
        out = new Array(len);
        for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
    }
    else if(y[0].length) {
        // vec-mat
        var yTranspose = exports.transposeRagged(y);
        out = new Array(yTranspose.length);
        for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
    }
    else {
        // vec-vec
        out = 0;
        for(i = 0; i < len; i++) out += x[i] * y[i];
    }

    return out;
};

// translate by (x,y)
exports.translationMatrix = function(x, y) {
    return [[1, 0, x], [0, 1, y], [0, 0, 1]];
};

// rotate by alpha around (0,0)
exports.rotationMatrix = function(alpha) {
    var a = alpha * Math.PI / 180;
    return [[Math.cos(a), -Math.sin(a), 0],
            [Math.sin(a), Math.cos(a), 0],
            [0, 0, 1]];
};

// rotate by alpha around (x,y)
exports.rotationXYMatrix = function(a, x, y) {
    return exports.dot(
        exports.dot(exports.translationMatrix(x, y),
                    exports.rotationMatrix(a)),
        exports.translationMatrix(-x, -y));
};

// applies a 2D transformation matrix to either x and y params or an [x,y] array
exports.apply2DTransform = function(transform) {
    return function() {
        var args = arguments;
        if(args.length === 3) {
            args = args[0];
        }// from map
        var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
        return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
    };
};

// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
exports.apply2DTransform2 = function(transform) {
    var at = exports.apply2DTransform(transform);
    return function(xys) {
        return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
    };
};

},{}],171:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * sanitized modulus function that always returns in the range [0, d)
 * rather than (-d, 0] if v is negative
 */
module.exports = function mod(v, d) {
    var out = v % d;
    return out < 0 ? out + d : out;
};

},{}],172:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var isArrayOrTypedArray = require('./is_array').isArrayOrTypedArray;

/**
 * convert a string s (such as 'xaxis.range[0]')
 * representing a property of nested object into set and get methods
 * also return the string and object so we don't have to keep track of them
 * allows [-1] for an array index, to set a property inside all elements
 * of an array
 * eg if obj = {arr: [{a: 1}, {a: 2}]}
 * you can do p = nestedProperty(obj, 'arr[-1].a')
 * but you cannot set the array itself this way, to do that
 * just set the whole array.
 * eg if obj = {arr: [1, 2, 3]}
 * you can't do nestedProperty(obj, 'arr[-1]').set(5)
 * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
 */
module.exports = function nestedProperty(container, propStr) {
    if(isNumeric(propStr)) propStr = String(propStr);
    else if(typeof propStr !== 'string' ||
            propStr.substr(propStr.length - 4) === '[-1]') {
        throw 'bad property string';
    }

    var j = 0,
        propParts = propStr.split('.'),
        indexed,
        indices,
        i;

    // check for parts of the nesting hierarchy that are numbers (ie array elements)
    while(j < propParts.length) {
        // look for non-bracket chars, then any number of [##] blocks
        indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
        if(indexed) {
            if(indexed[1]) propParts[j] = indexed[1];
            // allow propStr to start with bracketed array indices
            else if(j === 0) propParts.splice(0, 1);
            else throw 'bad property string';

            indices = indexed[2]
                .substr(1, indexed[2].length - 2)
                .split('][');

            for(i = 0; i < indices.length; i++) {
                j++;
                propParts.splice(j, 0, Number(indices[i]));
            }
        }
        j++;
    }

    if(typeof container !== 'object') {
        return badContainer(container, propStr, propParts);
    }

    return {
        set: npSet(container, propParts, propStr),
        get: npGet(container, propParts),
        astr: propStr,
        parts: propParts,
        obj: container
    };
};

function npGet(cont, parts) {
    return function() {
        var curCont = cont,
            curPart,
            allSame,
            out,
            i,
            j;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];
            if(curPart === -1) {
                allSame = true;
                out = [];
                for(j = 0; j < curCont.length; j++) {
                    out[j] = npGet(curCont[j], parts.slice(i + 1))();
                    if(out[j] !== out[0]) allSame = false;
                }
                return allSame ? out[0] : out;
            }
            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                return undefined;
            }
            curCont = curCont[curPart];
            if(typeof curCont !== 'object' || curCont === null) {
                return undefined;
            }
        }

        // only hit this if parts.length === 1
        if(typeof curCont !== 'object' || curCont === null) return undefined;

        out = curCont[parts[i]];
        if(out === null) return undefined;
        return out;
    };
}

/*
 * Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
 * *args* array.
 *
 * Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
 * a net noop; but this causes far more complication than it's worth, and still had
 * lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
 *
 * *args* arrays get passed directly to API methods and we should respect null if
 * the user put it there, but otherwise null is deleted as we use it as code
 * in restyle/relayout/update for "delete this value" whereas undefined means
 * "ignore this edit"
 */
var ARGS_PATTERN = /(^|\.)args\[/;
function isDeletable(val, propStr) {
    return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
}

function npSet(cont, parts, propStr) {
    return function(val) {
        var curCont = cont,
            propPart = '',
            containerLevels = [[cont, propPart]],
            toDelete = isDeletable(val, propStr),
            curPart,
            i;

        for(i = 0; i < parts.length - 1; i++) {
            curPart = parts[i];

            if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
                throw 'array index but container is not an array';
            }

            // handle special -1 array index
            if(curPart === -1) {
                toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
                if(toDelete) break;
                else return;
            }

            if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
                break;
            }

            curCont = curCont[curPart];

            if(typeof curCont !== 'object' || curCont === null) {
                throw 'container is not an object';
            }

            propPart = joinPropStr(propPart, curPart);

            containerLevels.push([curCont, propPart]);
        }

        if(toDelete) {
            if(i === parts.length - 1) {
                delete curCont[parts[i]];

                // The one bit of pruning we still do: drop `undefined` from the end of arrays.
                // In case someone has already unset previous items, continue until we hit a
                // non-undefined value.
                if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
                    while(curCont.length && curCont[curCont.length - 1] === undefined) {
                        curCont.pop();
                    }
                }
            }
        }
        else curCont[parts[i]] = val;
    };
}

function joinPropStr(propStr, newPart) {
    var toAdd = newPart;
    if(isNumeric(newPart)) toAdd = '[' + newPart + ']';
    else if(propStr) toAdd = '.' + newPart;

    return propStr + toAdd;
}

// handle special -1 array index
function setArrayAll(containerArray, innerParts, val, propStr) {
    var arrayVal = isArrayOrTypedArray(val),
        allSet = true,
        thisVal = val,
        thisPropStr = propStr.replace('-1', 0),
        deleteThis = arrayVal ? false : isDeletable(val, thisPropStr),
        firstPart = innerParts[0],
        i;

    for(i = 0; i < containerArray.length; i++) {
        thisPropStr = propStr.replace('-1', i);
        if(arrayVal) {
            thisVal = val[i % val.length];
            deleteThis = isDeletable(thisVal, thisPropStr);
        }
        if(deleteThis) allSet = false;
        if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
            continue;
        }
        npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
    }
    return allSet;
}

/**
 * make new sub-container as needed.
 * returns false if there's no container and none is needed
 * because we're only deleting an attribute
 */
function checkNewContainer(container, part, nextPart, toDelete) {
    if(container[part] === undefined) {
        if(toDelete) return false;

        if(typeof nextPart === 'number') container[part] = [];
        else container[part] = {};
    }
    return true;
}

function badContainer(container, propStr, propParts) {
    return {
        set: function() { throw 'bad container'; },
        get: function() {},
        astr: propStr,
        parts: propParts,
        obj: container
    };
}

},{"./is_array":165,"fast-isnumeric":9}],173:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Simple helper functions
// none of these need any external deps

module.exports = function noop() {};

},{}],174:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var NOTEDATA = [];

/**
 * notifier
 * @param {String} text The person's user name
 * @param {Number} [delay=1000] The delay time in milliseconds
 *          or 'long' which provides 2000 ms delay time.
 * @return {undefined} this function does not return a value
 */
module.exports = function(text, displayLength) {
    if(NOTEDATA.indexOf(text) !== -1) return;

    NOTEDATA.push(text);

    var ts = 1000;
    if(isNumeric(displayLength)) ts = displayLength;
    else if(displayLength === 'long') ts = 3000;

    var notifierContainer = d3.select('body')
        .selectAll('.plotly-notifier')
        .data([0]);
    notifierContainer.enter()
        .append('div')
        .classed('plotly-notifier', true);

    var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);

    function killNote(transition) {
        transition
            .duration(700)
            .style('opacity', 0)
            .each('end', function(thisText) {
                var thisIndex = NOTEDATA.indexOf(thisText);
                if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
                d3.select(this).remove();
            });
    }

    notes.enter().append('div')
        .classed('notifier-note', true)
        .style('opacity', 0)
        .each(function(thisText) {
            var note = d3.select(this);

            note.append('button')
                .classed('notifier-close', true)
                .html('&times;')
                .on('click', function() {
                    note.transition().call(killNote);
                });

            var p = note.append('p');
            var lines = thisText.split(/<br\s*\/?>/g);
            for(var i = 0; i < lines.length; i++) {
                if(i) p.append('br');
                p.append('span').text(lines[i]);
            }

            note.transition()
                    .duration(700)
                    .style('opacity', 1)
                .transition()
                    .delay(ts)
                    .call(killNote);
        });
};

},{"d3":6,"fast-isnumeric":9}],175:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var setCursor = require('./setcursor');

var STASHATTR = 'data-savedcursor';
var NO_CURSOR = '!!';

/*
 * works with our CSS cursor classes (see css/_cursor.scss)
 * to override a previous cursor set on d3 single-element selections,
 * by moving the name of the original cursor to the data-savedcursor attr.
 * omit cursor to revert to the previously set value.
 */
module.exports = function overrideCursor(el3, csr) {
    var savedCursor = el3.attr(STASHATTR);
    if(csr) {
        if(!savedCursor) {
            var classes = (el3.attr('class') || '').split(' ');
            for(var i = 0; i < classes.length; i++) {
                var cls = classes[i];
                if(cls.indexOf('cursor-') === 0) {
                    el3.attr(STASHATTR, cls.substr(7))
                        .classed(cls, false);
                }
            }
            if(!el3.attr(STASHATTR)) {
                el3.attr(STASHATTR, NO_CURSOR);
            }
        }
        setCursor(el3, csr);
    }
    else if(savedCursor) {
        el3.attr(STASHATTR, null);

        if(savedCursor === NO_CURSOR) setCursor(el3);
        else setCursor(el3, savedCursor);
    }
};

},{"./setcursor":183}],176:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var dot = require('./matrix').dot;
var BADNUM = require('../constants/numerical').BADNUM;

var polygon = module.exports = {};

/**
 * Turn an array of [x, y] pairs into a polygon object
 * that can test if points are inside it
 *
 * @param ptsIn Array of [x, y] pairs
 *
 * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
 *      (x|y)(min|max) are the bounding rect of the polygon
 *      pts is the original array, with the first pair repeated at the end
 *      contains is a function: (pt, omitFirstEdge)
 *          pt is the [x, y] pair to test
 *          omitFirstEdge truthy means points exactly on the first edge don't
 *              count. This is for use adding one polygon to another so we
 *              don't double-count the edge where they meet.
 *          returns boolean: is pt inside the polygon (including on its edges)
 */
polygon.tester = function tester(ptsIn) {
    if(Array.isArray(ptsIn[0][0])) return polygon.multitester(ptsIn);

    var pts = ptsIn.slice(),
        xmin = pts[0][0],
        xmax = xmin,
        ymin = pts[0][1],
        ymax = ymin,
        i;

    pts.push(pts[0]);
    for(i = 1; i < pts.length; i++) {
        xmin = Math.min(xmin, pts[i][0]);
        xmax = Math.max(xmax, pts[i][0]);
        ymin = Math.min(ymin, pts[i][1]);
        ymax = Math.max(ymax, pts[i][1]);
    }

    // do we have a rectangle? Handle this here, so we can use the same
    // tester for the rectangular case without sacrificing speed

    var isRect = false,
        rectFirstEdgeTest;

    if(pts.length === 5) {
        if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz
            if(pts[2][0] === pts[3][0] &&
                    pts[0][1] === pts[3][1] &&
                    pts[1][1] === pts[2][1]) {
                isRect = true;
                rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; };
            }
        }
        else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert
            if(pts[2][1] === pts[3][1] &&
                    pts[0][0] === pts[3][0] &&
                    pts[1][0] === pts[2][0]) {
                isRect = true;
                rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; };
            }
        }
    }

    function rectContains(pt, omitFirstEdge) {
        var x = pt[0],
            y = pt[1];

        if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            // pt is outside the bounding box of polygon
            return false;
        }
        if(omitFirstEdge && rectFirstEdgeTest(pt)) return false;

        return true;
    }

    function contains(pt, omitFirstEdge) {
        var x = pt[0],
            y = pt[1];

        if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
            // pt is outside the bounding box of polygon
            return false;
        }

        var imax = pts.length,
            x1 = pts[0][0],
            y1 = pts[0][1],
            crossings = 0,
            i,
            x0,
            y0,
            xmini,
            ycross;

        for(i = 1; i < imax; i++) {
            // find all crossings of a vertical line upward from pt with
            // polygon segments
            // crossings exactly at xmax don't count, unless the point is
            // exactly on the segment, then it counts as inside.
            x0 = x1;
            y0 = y1;
            x1 = pts[i][0];
            y1 = pts[i][1];
            xmini = Math.min(x0, x1);

            // outside the bounding box of this segment, it's only a crossing
            // if it's below the box.
            if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
                continue;
            }
            else if(y < Math.min(y0, y1)) {
                // don't count the left-most point of the segment as a crossing
                // because we don't want to double-count adjacent crossings
                // UNLESS the polygon turns past vertical at exactly this x
                // Note that this is repeated below, but we can't factor it out
                // because
                if(x !== xmini) crossings++;
            }
            // inside the bounding box, check the actual line intercept
            else {
                // vertical segment - we know already that the point is exactly
                // on the segment, so mark the crossing as exactly at the point.
                if(x1 === x0) ycross = y;
                // any other angle
                else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);

                // exactly on the edge: counts as inside the polygon, unless it's the
                // first edge and we're omitting it.
                if(y === ycross) {
                    if(i === 1 && omitFirstEdge) return false;
                    return true;
                }

                if(y <= ycross && x !== xmini) crossings++;
            }
        }

        // if we've gotten this far, odd crossings means inside, even is outside
        return crossings % 2 === 1;
    }

    // detect if poly is degenerate
    var degenerate = true;
    var lastPt = pts[0];
    for(i = 1; i < pts.length; i++) {
        if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) {
            degenerate = false;
            break;
        }
    }

    return {
        xmin: xmin,
        xmax: xmax,
        ymin: ymin,
        ymax: ymax,
        pts: pts,
        contains: isRect ? rectContains : contains,
        isRect: isRect,
        degenerate: degenerate
    };
};

/**
 * Test multiple polygons
 */
polygon.multitester = function multitester(list) {
    var testers = [],
        xmin = list[0][0][0],
        xmax = xmin,
        ymin = list[0][0][1],
        ymax = ymin;

    for(var i = 0; i < list.length; i++) {
        var tester = polygon.tester(list[i]);
        tester.subtract = list[i].subtract;
        testers.push(tester);
        xmin = Math.min(xmin, tester.xmin);
        xmax = Math.max(xmax, tester.xmax);
        ymin = Math.min(ymin, tester.ymin);
        ymax = Math.max(ymax, tester.ymax);
    }

    function contains(pt, arg) {
        var yes = false;
        for(var i = 0; i < testers.length; i++) {
            if(testers[i].contains(pt, arg)) {
                // if contained by subtract polygon - exclude the point
                yes = testers[i].subtract === false;
            }
        }

        return yes;
    }

    return {
        xmin: xmin,
        xmax: xmax,
        ymin: ymin,
        ymax: ymax,
        pts: [],
        contains: contains,
        isRect: false,
        degenerate: false
    };
};

/**
 * Test if a segment of a points array is bent or straight
 *
 * @param pts Array of [x, y] pairs
 * @param start the index of the proposed start of the straight section
 * @param end the index of the proposed end point
 * @param tolerance the max distance off the line connecting start and end
 *      before the line counts as bent
 * @returns boolean: true means this segment is bent, false means straight
 */
var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) {
    var startPt = pts[start],
        segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]],
        segmentSquared = dot(segment, segment),
        segmentLen = Math.sqrt(segmentSquared),
        unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen],
        i,
        part,
        partParallel;

    for(i = start + 1; i < end; i++) {
        part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
        partParallel = dot(part, segment);

        if(partParallel < 0 || partParallel > segmentSquared ||
            Math.abs(dot(part, unitPerp)) > tolerance) return true;
    }
    return false;
};

/**
 * Make a filtering polygon, to minimize the number of segments
 *
 * @param pts Array of [x, y] pairs (must start with at least 1 pair)
 * @param tolerance the maximum deviation from straight allowed for
 *      removing points to simplify the polygon
 *
 * @returns Object {addPt, raw, filtered}
 *      addPt is a function(pt: [x, y] pair) to add a raw point and
 *          continue filtering
 *      raw is all the input points
 *      filtered is the resulting filtered Array of [x, y] pairs
 */
polygon.filter = function filter(pts, tolerance) {
    var ptsFiltered = [pts[0]],
        doneRawIndex = 0,
        doneFilteredIndex = 0;

    function addPt(pt) {
        pts.push(pt);
        var prevFilterLen = ptsFiltered.length,
            iLast = doneRawIndex;
        ptsFiltered.splice(doneFilteredIndex + 1);

        for(var i = iLast + 1; i < pts.length; i++) {
            if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) {
                ptsFiltered.push(pts[i]);
                if(ptsFiltered.length < prevFilterLen - 2) {
                    doneRawIndex = i;
                    doneFilteredIndex = ptsFiltered.length - 1;
                }
                iLast = i;
            }
        }
    }

    if(pts.length > 1) {
        var lastPt = pts.pop();
        addPt(lastPt);
    }

    return {
        addPt: addPt,
        raw: pts,
        filtered: ptsFiltered
    };
};

},{"../constants/numerical":145,"./matrix":170}],177:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * Push array with unique items
 *
 * Ignores falsy items, except 0 so we can use it to construct arrays of indices.
 *
 * @param {array} array
 *  array to be filled
 * @param {any} item
 *  item to be or not to be inserted
 * @return {array}
 *  ref to array (now possibly containing one more item)
 *
 */
module.exports = function pushUnique(array, item) {
    if(item instanceof RegExp) {
        var itemStr = item.toString(),
            i;
        for(i = 0; i < array.length; i++) {
            if(array[i] instanceof RegExp && array[i].toString() === itemStr) {
                return array;
            }
        }
        array.push(item);
    }
    else if((item || item === 0) && array.indexOf(item) === -1) array.push(item);

    return array;
};

},{}],178:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../lib');
var config = require('../plot_api/plot_config');


/**
 * Copy arg array *without* removing `undefined` values from objects.
 *
 * @param gd
 * @param args
 * @returns {Array}
 */
function copyArgArray(gd, args) {
    var copy = [];
    var arg;

    for(var i = 0; i < args.length; i++) {
        arg = args[i];

        if(arg === gd) copy[i] = arg;
        else if(typeof arg === 'object') {
            copy[i] = Array.isArray(arg) ?
                Lib.extendDeep([], arg) :
                Lib.extendDeepAll({}, arg);
        }
        else copy[i] = arg;
    }

    return copy;
}


// -----------------------------------------------------
// Undo/Redo queue for plots
// -----------------------------------------------------


var queue = {};

// TODO: disable/enable undo and redo buttons appropriately

/**
 * Add an item to the undoQueue for a graphDiv
 *
 * @param gd
 * @param undoFunc Function undo this operation
 * @param undoArgs Args to supply undoFunc with
 * @param redoFunc Function to redo this operation
 * @param redoArgs Args to supply redoFunc with
 */
queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) {
    var queueObj,
        queueIndex;

    // make sure we have the queue and our position in it
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    queueIndex = gd.undoQueue.index;

    // if we're already playing an undo or redo, or if this is an auto operation
    // (like pane resize... any others?) then we don't save this to the undo queue
    if(gd.autoplay) {
        if(!gd.undoQueue.inSequence) gd.autoplay = false;
        return;
    }

    // if we're not in a sequence or are just starting, we need a new queue item
    if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
        queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}};
        gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
        gd.undoQueue.index += 1;
    } else {
        queueObj = gd.undoQueue.queue[queueIndex - 1];
    }
    gd.undoQueue.beginSequence = false;

    // we unshift to handle calls for undo in a forward for loop later
    if(queueObj) {
        queueObj.undo.calls.unshift(undoFunc);
        queueObj.undo.args.unshift(undoArgs);
        queueObj.redo.calls.push(redoFunc);
        queueObj.redo.args.push(redoArgs);
    }

    if(gd.undoQueue.queue.length > config.queueLength) {
        gd.undoQueue.queue.shift();
        gd.undoQueue.index--;
    }
};

/**
 * Begin a sequence of undoQueue changes
 *
 * @param gd
 */
queue.startSequence = function(gd) {
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    gd.undoQueue.sequence = true;
    gd.undoQueue.beginSequence = true;
};

/**
 * Stop a sequence of undoQueue changes
 *
 * Call this *after* you're sure your undo chain has ended
 *
 * @param gd
 */
queue.stopSequence = function(gd) {
    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
    gd.undoQueue.sequence = false;
    gd.undoQueue.beginSequence = false;
};

/**
 * Move one step back in the undo queue, and undo the object there.
 *
 * @param gd
 */
queue.undo = function undo(gd) {
    var queueObj, i;

    if(gd.framework && gd.framework.isPolar) {
        gd.framework.undo();
        return;
    }
    if(gd.undoQueue === undefined ||
            isNaN(gd.undoQueue.index) ||
            gd.undoQueue.index <= 0) {
        return;
    }

    // index is pointing to next *forward* queueObj, point to the one we're undoing
    gd.undoQueue.index--;

    // get the queueObj for instructions on how to undo
    queueObj = gd.undoQueue.queue[gd.undoQueue.index];

    // this sequence keeps things from adding to the queue during undo/redo
    gd.undoQueue.inSequence = true;
    for(i = 0; i < queueObj.undo.calls.length; i++) {
        queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
    }
    gd.undoQueue.inSequence = false;
    gd.autoplay = false;
};

/**
 * Redo the current object in the undo, then move forward in the queue.
 *
 * @param gd
 */
queue.redo = function redo(gd) {
    var queueObj, i;

    if(gd.framework && gd.framework.isPolar) {
        gd.framework.redo();
        return;
    }
    if(gd.undoQueue === undefined ||
            isNaN(gd.undoQueue.index) ||
            gd.undoQueue.index >= gd.undoQueue.queue.length) {
        return;
    }

    // get the queueObj for instructions on how to undo
    queueObj = gd.undoQueue.queue[gd.undoQueue.index];

    // this sequence keeps things from adding to the queue during undo/redo
    gd.undoQueue.inSequence = true;
    for(i = 0; i < queueObj.redo.calls.length; i++) {
        queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
    }
    gd.undoQueue.inSequence = false;
    gd.autoplay = false;

    // index is pointing to the thing we just redid, move it
    gd.undoQueue.index++;
};

/**
 * Called by undo/redo to make the actual changes.
 *
 * Not meant to be called publically, but included for mocking out in tests.
 *
 * @param gd
 * @param func
 * @param args
 */
queue.plotDo = function(gd, func, args) {
    gd.autoplay = true;

    // this *won't* copy gd and it preserves `undefined` properties!
    args = copyArgArray(gd, args);

    // call the supplied function
    func.apply(null, args);
};

module.exports = queue;

},{"../lib":164,"../plot_api/plot_config":196}],179:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
 *
 * @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
 *      'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
 * @param {Optional(string)} tail: a fixed piece after the id
 *      eg counterRegex('scene', '.annotations') for scene2.annotations etc.
 * @param {boolean} openEnded: if true, the string may continue past the match.
 */
exports.counter = function(head, tail, openEnded) {
    var fullTail = (tail || '') + (openEnded ? '' : '$');
    if(head === 'xy') {
        return new RegExp('^x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
    }
    return new RegExp('^' + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
};

},{}],180:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// ASCEND: chop off the last nesting level - either [<n>] or .<key> - to ascend
// the attribute tree. the remaining attrString is in match[1]
var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;

// SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
var SIMPLEATTR = /^[^\.\[\]]+$/;

/*
 * calculate a relative attribute string, similar to a relative path
 *
 * @param {string} baseAttr:
 *   an attribute string, such as 'annotations[3].x'. The "current location"
 *   is the attribute string minus the last component ('annotations[3]')
 * @param {string} relativeAttr:
 *   a route to the desired attribute string, using '^' to ascend
 *
 * @return {string} attrString:
 *   for example:
 *     relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
 *     relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
 *     relativeAttr('annotations[3].x', '^^margin') = 'margin'
 *     relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
 */
module.exports = function(baseAttr, relativeAttr) {
    while(relativeAttr) {
        var match = baseAttr.match(ASCEND);

        if(match) baseAttr = match[1];
        else if(baseAttr.match(SIMPLEATTR)) baseAttr = '';
        else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);

        if(relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);
        else break;
    }

    if(baseAttr && relativeAttr.charAt(0) !== '[') {
        return baseAttr + '.' + relativeAttr;
    }
    return baseAttr + relativeAttr;
};

},{}],181:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isArrayOrTypedArray = require('./is_array').isArrayOrTypedArray;
var isPlainObject = require('./is_plain_object');

/**
 * Relink private _keys and keys with a function value from one container
 * to the new container.
 * Relink means copying if object is pass-by-value and adding a reference
 * if object is pass-by-ref.
 * This prevents deepCopying massive structures like a webgl context.
 */
module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
    for(var k in fromContainer) {
        var fromVal = fromContainer[k];
        var toVal = toContainer[k];

        if(toVal === fromVal) {
            continue;
        }
        if(k.charAt(0) === '_' || typeof fromVal === 'function') {

            // if it already exists at this point, it's something
            // that we recreate each time around, so ignore it
            if(k in toContainer) continue;

            toContainer[k] = fromVal;
        }
        else if(isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {

            // filter out data_array items that can contain user objects
            // most of the time the toVal === fromVal check will catch these early
            // but if the user makes new ones we also don't want to recurse in.
            if(k === 'customdata' || k === 'ids') continue;

            // recurse into arrays containers
            var minLen = Math.min(fromVal.length, toVal.length);
            for(var j = 0; j < minLen; j++) {
                if((toVal[j] !== fromVal[j]) && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
                    relinkPrivateKeys(toVal[j], fromVal[j]);
                }
            }
        }
        else if(isPlainObject(fromVal) && isPlainObject(toVal)) {

            // recurse into objects, but only if they still exist
            relinkPrivateKeys(toVal, fromVal);

            if(!Object.keys(toVal).length) delete toContainer[k];
        }
    }
};

},{"./is_array":165,"./is_plain_object":166}],182:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var loggers = require('./loggers');

// don't trust floating point equality - fraction of bin size to call
// "on the line" and ensure that they go the right way specified by
// linelow
var roundingError = 1e-9;


/**
 * findBin - find the bin for val - note that it can return outside the
 * bin range any pos. or neg. integer for linear bins, or -1 or
 * bins.length-1 for explicit.
 * bins is either an object {start,size,end} or an array length #bins+1
 * bins can be either increasing or decreasing but must be monotonic
 * for linear bins, we can just calculate. For listed bins, run a binary
 * search linelow (truthy) says the bin boundary should be attributed to
 * the lower bin rather than the default upper bin
 */
exports.findBin = function(val, bins, linelow) {
    if(isNumeric(bins.start)) {
        return linelow ?
            Math.ceil((val - bins.start) / bins.size - roundingError) - 1 :
            Math.floor((val - bins.start) / bins.size + roundingError);
    }
    else {
        var n1 = 0;
        var n2 = bins.length;
        var c = 0;
        var binSize = (n2 > 1) ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
        var n, test;
        if(binSize >= 0) {
            test = linelow ? lessThan : lessOrEqual;
        } else {
            test = linelow ? greaterOrEqual : greaterThan;
        }
        val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
        // c is just to avoid infinite loops if there's an error
        while(n1 < n2 && c++ < 100) {
            n = Math.floor((n1 + n2) / 2);
            if(test(bins[n], val)) n1 = n + 1;
            else n2 = n;
        }
        if(c > 90) loggers.log('Long binary search...');
        return n1 - 1;
    }
};

function lessThan(a, b) { return a < b; }
function lessOrEqual(a, b) { return a <= b; }
function greaterThan(a, b) { return a > b; }
function greaterOrEqual(a, b) { return a >= b; }

exports.sorterAsc = function(a, b) { return a - b; };
exports.sorterDes = function(a, b) { return b - a; };

/**
 * find distinct values in an array, lumping together ones that appear to
 * just be off by a rounding error
 * return the distinct values and the minimum difference between any two
 */
exports.distinctVals = function(valsIn) {
    var vals = valsIn.slice();  // otherwise we sort the original array...
    vals.sort(exports.sorterAsc);

    var l = vals.length - 1,
        minDiff = (vals[l] - vals[0]) || 1,
        errDiff = minDiff / (l || 1) / 10000,
        v2 = [vals[0]];

    for(var i = 0; i < l; i++) {
        // make sure values aren't just off by a rounding error
        if(vals[i + 1] > vals[i] + errDiff) {
            minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
            v2.push(vals[i + 1]);
        }
    }

    return {vals: v2, minDiff: minDiff};
};

/**
 * return the smallest element from (sorted) array arrayIn that's bigger than val,
 * or (reverse) the largest element smaller than val
 * used to find the best tick given the minimum (non-rounded) tick
 * particularly useful for date/time where things are not powers of 10
 * binary search is probably overkill here...
 */
exports.roundUp = function(val, arrayIn, reverse) {
    var low = 0,
        high = arrayIn.length - 1,
        mid,
        c = 0,
        dlow = reverse ? 0 : 1,
        dhigh = reverse ? 1 : 0,
        rounded = reverse ? Math.ceil : Math.floor;
    // c is just to avoid infinite loops if there's an error
    while(low < high && c++ < 100) {
        mid = rounded((low + high) / 2);
        if(arrayIn[mid] <= val) low = mid + dlow;
        else high = mid - dhigh;
    }
    return arrayIn[low];
};

},{"./loggers":169,"fast-isnumeric":9}],183:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

// works with our CSS cursor classes (see css/_cursor.scss)
// to apply cursors to d3 single-element selections.
// omit cursor to revert to the default.
module.exports = function setCursor(el3, csr) {
    (el3.attr('class') || '').split(' ').forEach(function(cls) {
        if(cls.indexOf('cursor-') === 0) el3.classed(cls, false);
    });

    if(csr) el3.classed('cursor-' + csr, true);
};

},{}],184:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var isArrayOrTypedArray = require('./is_array').isArrayOrTypedArray;

/**
 * aggNums() returns the result of an aggregate function applied to an array of
 * values, where non-numerical values have been tossed out.
 *
 * @param {function} f - aggregation function (e.g., Math.min)
 * @param {Number} v - initial value (continuing from previous calls)
 *      if there's no continuing value, use null for selector-type
 *      functions (max,min), or 0 for summations
 * @param {Array} a - array to aggregate (may be nested, we will recurse,
 *                    but all elements must have the same dimension)
 * @param {Number} len - maximum length of a to aggregate
 * @return {Number} - result of f applied to a starting from v
 */
exports.aggNums = function(f, v, a, len) {
    var i,
        b;
    if(!len || len > a.length) len = a.length;
    if(!isNumeric(v)) v = false;
    if(isArrayOrTypedArray(a[0])) {
        b = new Array(len);
        for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
        a = b;
    }

    for(i = 0; i < len; i++) {
        if(!isNumeric(v)) v = a[i];
        else if(isNumeric(a[i])) v = f(+v, +a[i]);
    }
    return v;
};

/**
 * mean & std dev functions using aggNums, so it handles non-numerics nicely
 * even need to use aggNums instead of .length, to toss out non-numerics
 */
exports.len = function(data) {
    return exports.aggNums(function(a) { return a + 1; }, 0, data);
};

exports.mean = function(data, len) {
    if(!len) len = exports.len(data);
    return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
};

exports.variance = function(data, len, mean) {
    if(!len) len = exports.len(data);
    if(!isNumeric(mean)) mean = exports.mean(data, len);

    return exports.aggNums(function(a, b) {
        return a + Math.pow(b - mean, 2);
    }, 0, data) / len;
};

exports.stdev = function(data, len, mean) {
    return Math.sqrt(exports.variance(data, len, mean));
};

/**
 * interp() computes a percentile (quantile) for a given distribution.
 * We interpolate the distribution (to compute quantiles, we follow method #10 here:
 * http://www.amstat.org/publications/jse/v14n3/langford.html).
 * Typically the index or rank (n * arr.length) may be non-integer.
 * For reference: ends are clipped to the extreme values in the array;
 * For box plots: index you get is half a point too high (see
 * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
 * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
 *
 * @param {Array} arr - This array contains the values that make up the distribution.
 * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
 * For example, the 50th percentile (or median) corresponds to n = 0.5
 * @return {Number} - percentile
 */
exports.interp = function(arr, n) {
    if(!isNumeric(n)) throw 'n should be a finite number';
    n = n * arr.length - 0.5;
    if(n < 0) return arr[0];
    if(n > arr.length - 1) return arr[arr.length - 1];
    var frac = n % 1;
    return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
};

},{"./is_array":165,"fast-isnumeric":9}],185:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

/* global MathJax:false */

var d3 = require('d3');

var Lib = require('../lib');
var xmlnsNamespaces = require('../constants/xmlns_namespaces');
var stringMappings = require('../constants/string_mappings');
var LINE_SPACING = require('../constants/alignment').LINE_SPACING;

// text converter

function getSize(_selection, _dimension) {
    return _selection.node().getBoundingClientRect()[_dimension];
}

var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/;

exports.convertToTspans = function(_context, gd, _callback) {
    var str = _context.text();

    // Until we get tex integrated more fully (so it can be used along with non-tex)
    // allow some elements to prohibit it by attaching 'data-notex' to the original
    var tex = (!_context.attr('data-notex')) &&
        (typeof MathJax !== 'undefined') &&
        str.match(FIND_TEX);

    var parent = d3.select(_context.node().parentNode);
    if(parent.empty()) return;
    var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text';
    svgClass += '-math';
    parent.selectAll('svg.' + svgClass).remove();
    parent.selectAll('g.' + svgClass + '-group').remove();
    _context.style('display', null)
        .attr({
            // some callers use data-unformatted *from the <text> element* in 'cancel'
            // so we need it here even if we're going to turn it into math
            // these two (plus style and text-anchor attributes) form the key we're
            // going to use for Drawing.bBox
            'data-unformatted': str,
            'data-math': 'N'
        });

    function showText() {
        if(!parent.empty()) {
            svgClass = _context.attr('class') + '-math';
            parent.select('svg.' + svgClass).remove();
        }
        _context.text('')
            .style('white-space', 'pre');

        var hasLink = buildSVGText(_context.node(), str);

        if(hasLink) {
            // at least in Chrome, pointer-events does not seem
            // to be honored in children of <text> elements
            // so if we have an anchor, we have to make the
            // whole element respond
            _context.style('pointer-events', 'all');
        }

        exports.positionText(_context);

        if(_callback) _callback.call(_context);
    }

    if(tex) {
        ((gd && gd._promises) || []).push(new Promise(function(resolve) {
            _context.style('display', 'none');
            var fontSize = parseInt(_context.node().style.fontSize, 10);
            var config = {fontSize: fontSize};

            texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) {
                parent.selectAll('svg.' + svgClass).remove();
                parent.selectAll('g.' + svgClass + '-group').remove();

                var newSvg = _svgEl && _svgEl.select('svg');
                if(!newSvg || !newSvg.node()) {
                    showText();
                    resolve();
                    return;
                }

                var mathjaxGroup = parent.append('g')
                    .classed(svgClass + '-group', true)
                    .attr({
                        'pointer-events': 'none',
                        'data-unformatted': str,
                        'data-math': 'Y'
                    });

                mathjaxGroup.node().appendChild(newSvg.node());

                // stitch the glyph defs
                if(_glyphDefs && _glyphDefs.node()) {
                    newSvg.node().insertBefore(_glyphDefs.node().cloneNode(true),
                                               newSvg.node().firstChild);
                }

                newSvg.attr({
                    'class': svgClass,
                    height: _svgBBox.height,
                    preserveAspectRatio: 'xMinYMin meet'
                })
                .style({overflow: 'visible', 'pointer-events': 'none'});

                var fill = _context.node().style.fill || 'black';
                newSvg.select('g').attr({fill: fill, stroke: fill});

                var newSvgW = getSize(newSvg, 'width'),
                    newSvgH = getSize(newSvg, 'height'),
                    newX = +_context.attr('x') - newSvgW *
                        {start: 0, middle: 0.5, end: 1}[_context.attr('text-anchor') || 'start'],
                    // font baseline is about 1/4 fontSize below centerline
                    textHeight = fontSize || getSize(_context, 'height'),
                    dy = -textHeight / 4;

                if(svgClass[0] === 'y') {
                    mathjaxGroup.attr({
                        transform: 'rotate(' + [-90, +_context.attr('x'), +_context.attr('y')] +
                        ') translate(' + [-newSvgW / 2, dy - newSvgH / 2] + ')'
                    });
                    newSvg.attr({x: +_context.attr('x'), y: +_context.attr('y')});
                }
                else if(svgClass[0] === 'l') {
                    newSvg.attr({x: _context.attr('x'), y: dy - (newSvgH / 2)});
                }
                else if(svgClass[0] === 'a') {
                    newSvg.attr({x: 0, y: dy});
                }
                else {
                    newSvg.attr({x: newX, y: (+_context.attr('y') + dy - newSvgH / 2)});
                }

                if(_callback) _callback.call(_context, mathjaxGroup);
                resolve(mathjaxGroup);
            });
        }));
    }
    else showText();

    return _context;
};


// MathJax

var LT_MATCH = /(<|&lt;|&#60;)/g;
var GT_MATCH = /(>|&gt;|&#62;)/g;

function cleanEscapesForTex(s) {
    return s.replace(LT_MATCH, '\\lt ')
        .replace(GT_MATCH, '\\gt ');
}

function texToSVG(_texString, _config, _callback) {
    var randomID = 'math-output-' + Lib.randstr([], 64);
    var tmpDiv = d3.select('body').append('div')
        .attr({id: randomID})
        .style({visibility: 'hidden', position: 'absolute'})
        .style({'font-size': _config.fontSize + 'px'})
        .text(cleanEscapesForTex(_texString));

    MathJax.Hub.Queue(['Typeset', MathJax.Hub, tmpDiv.node()], function() {
        var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs');

        if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) {
            Lib.log('There was an error in the tex syntax.', _texString);
            _callback();
        }
        else {
            var svgBBox = tmpDiv.select('svg').node().getBoundingClientRect();
            _callback(tmpDiv.select('.MathJax_SVG'), glyphDefs, svgBBox);
        }

        tmpDiv.remove();
    });
}

var TAG_STYLES = {
    // would like to use baseline-shift for sub/sup but FF doesn't support it
    // so we need to use dy along with the uber hacky shift-back-to
    // baseline below
    sup: 'font-size:70%',
    sub: 'font-size:70%',
    b: 'font-weight:bold',
    i: 'font-style:italic',
    a: 'cursor:pointer',
    span: '',
    em: 'font-style:italic;font-weight:bold'
};

// baseline shifts for sub and sup
var SHIFT_DY = {
    sub: '0.3em',
    sup: '-0.6em'
};
// reset baseline by adding a tspan (empty except for a zero-width space)
// with dy of -70% * SHIFT_DY (because font-size=70%)
var RESET_DY = {
    sub: '-0.21em',
    sup: '0.42em'
};
var ZERO_WIDTH_SPACE = '\u200b';

/*
 * Whitelist of protocols in user-supplied urls. Mostly we want to avoid javascript
 * and related attack vectors. The empty items are there for IE, that in various
 * versions treats relative paths as having different flavors of no protocol, while
 * other browsers have these explicitly inherit the protocol of the page they're in.
 */
var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':'];

var STRIP_TAGS = new RegExp('</?(' + Object.keys(TAG_STYLES).join('|') + ')( [^>]*)?/?>', 'g');

var ENTITY_TO_UNICODE = Object.keys(stringMappings.entityToUnicode).map(function(k) {
    return {
        regExp: new RegExp('&' + k + ';', 'g'),
        sub: stringMappings.entityToUnicode[k]
    };
});

var NEWLINES = /(\r\n?|\n)/g;

var SPLIT_TAGS = /(<[^<>]*>)/;

var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i;

var BR_TAG = /<br(\s+.*)?>/i;

/*
 * style and href: pull them out of either single or double quotes. Also
 * - target: (_blank|_self|_parent|_top|framename)
 *     note that you can't use target to get a popup but if you use popup,
 *     a `framename` will be passed along as the name of the popup window.
 *     per the spec, cannot contain whitespace.
 *     for backward compatibility we default to '_blank'
 * - popup: a custom one for us to enable popup (new window) links. String
 *     for window.open -> strWindowFeatures, like 'menubar=yes,width=500,height=550'
 *     note that at least in Chrome, you need to give at least one property
 *     in this string or the page will open in a new tab anyway. We follow this
 *     convention and will not make a popup if this string is empty.
 *     per the spec, cannot contain whitespace.
 *
 * Because we hack in other attributes with style (sub & sup), drop any trailing
 * semicolon in user-supplied styles so we can consistently append the tag-dependent style
 */
var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i;
var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i;
var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i;
var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;

// dedicated matcher for these quoted regexes, that can return their results
// in two different places
function getQuotedMatch(_str, re) {
    if(!_str) return null;
    var match = _str.match(re);
    return match && (match[3] || match[4]);
}

var COLORMATCH = /(^|;)\s*color:/;

exports.plainText = function(_str) {
    // strip out our pseudo-html so we have a readable
    // version to put into text fields
    return (_str || '').replace(STRIP_TAGS, ' ');
};

function replaceFromMapObject(_str, list) {
    if(!_str) return '';

    for(var i = 0; i < list.length; i++) {
        var item = list[i];
        _str = _str.replace(item.regExp, item.sub);
    }

    return _str;
}

function convertEntities(_str) {
    return replaceFromMapObject(_str, ENTITY_TO_UNICODE);
}

/*
 * buildSVGText: convert our pseudo-html into SVG tspan elements, and attach these
 * to containerNode
 *
 * @param {svg text element} containerNode: the <text> node to insert this text into
 * @param {string} str: the pseudo-html string to convert to svg
 *
 * @returns {bool}: does the result contain any links? We need to handle the text element
 *   somewhat differently if it does, so just keep track of this when it happens.
 */
function buildSVGText(containerNode, str) {
    str = convertEntities(str)
        /*
         * Normalize behavior between IE and others wrt newlines and whitespace:pre
         * this combination makes IE barf https://github.com/plotly/plotly.js/issues/746
         * Chrome and FF display \n, \r, or \r\n as a space in this mode.
         * I feel like at some point we turned these into <br> but currently we don't so
         * I'm just going to cement what we do now in Chrome and FF
         */
        .replace(NEWLINES, ' ');

    var hasLink = false;

    // as we're building the text, keep track of what elements we're nested inside
    // nodeStack will be an array of {node, type, style, href, target, popup}
    // where only type: 'a' gets the last 3 and node is only added when it's created
    var nodeStack = [];
    var currentNode;
    var currentLine = -1;

    function newLine() {
        currentLine++;

        var lineNode = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
        d3.select(lineNode).attr({
            class: 'line',
            dy: (currentLine * LINE_SPACING) + 'em'
        });
        containerNode.appendChild(lineNode);

        currentNode = lineNode;

        var oldNodeStack = nodeStack;
        nodeStack = [{node: lineNode}];

        if(oldNodeStack.length > 1) {
            for(var i = 1; i < oldNodeStack.length; i++) {
                enterNode(oldNodeStack[i]);
            }
        }
    }

    function enterNode(nodeSpec) {
        var type = nodeSpec.type;
        var nodeAttrs = {};
        var nodeType;

        if(type === 'a') {
            nodeType = 'a';
            var target = nodeSpec.target;
            var href = nodeSpec.href;
            var popup = nodeSpec.popup;
            if(href) {
                nodeAttrs = {
                    'xlink:xlink:show': (target === '_blank' || target.charAt(0) !== '_') ? 'new' : 'replace',
                    target: target,
                    'xlink:xlink:href': href
                };
                if(popup) {
                    // security: href and target are not inserted as code but
                    // as attributes. popup is, but limited to /[A-Za-z0-9_=,]/
                    nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' +
                        popup + '");return false;';
                }
            }
        }
        else nodeType = 'tspan';

        if(nodeSpec.style) nodeAttrs.style = nodeSpec.style;

        var newNode = document.createElementNS(xmlnsNamespaces.svg, nodeType);

        if(type === 'sup' || type === 'sub') {
            addTextNode(currentNode, ZERO_WIDTH_SPACE);
            currentNode.appendChild(newNode);

            var resetter = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
            addTextNode(resetter, ZERO_WIDTH_SPACE);
            d3.select(resetter).attr('dy', RESET_DY[type]);
            nodeAttrs.dy = SHIFT_DY[type];

            currentNode.appendChild(newNode);
            currentNode.appendChild(resetter);
        }
        else {
            currentNode.appendChild(newNode);
        }

        d3.select(newNode).attr(nodeAttrs);

        currentNode = nodeSpec.node = newNode;
        nodeStack.push(nodeSpec);
    }

    function addTextNode(node, text) {
        node.appendChild(document.createTextNode(text));
    }

    function exitNode(type) {
        // A bare closing tag can't close the root node. If we encounter this it
        // means there's an extra closing tag that can just be ignored:
        if(nodeStack.length === 1) {
            Lib.log('Ignoring unexpected end tag </' + type + '>.', str);
            return;
        }

        var innerNode = nodeStack.pop();

        if(type !== innerNode.type) {
            Lib.log('Start tag <' + innerNode.type + '> doesnt match end tag <' +
                type + '>. Pretending it did match.', str);
        }
        currentNode = nodeStack[nodeStack.length - 1].node;
    }

    var hasLines = BR_TAG.test(str);

    if(hasLines) newLine();
    else {
        currentNode = containerNode;
        nodeStack = [{node: containerNode}];
    }

    var parts = str.split(SPLIT_TAGS);
    for(var i = 0; i < parts.length; i++) {
        var parti = parts[i];
        var match = parti.match(ONE_TAG);
        var tagType = match && match[2].toLowerCase();
        var tagStyle = TAG_STYLES[tagType];

        if(tagType === 'br') {
            newLine();
        }
        else if(tagStyle === undefined) {
            addTextNode(currentNode, parti);
        }
        else {
            // tag - open or close
            if(match[1]) {
                exitNode(tagType);
            }
            else {
                var extra = match[4];

                var nodeSpec = {type: tagType};

                // now add style, from both the tag name and any extra css
                // Most of the svg css that users will care about is just like html,
                // but font color is different (uses fill). Let our users ignore this.
                var css = getQuotedMatch(extra, STYLEMATCH);
                if(css) {
                    css = css.replace(COLORMATCH, '$1 fill:');
                    if(tagStyle) css += ';' + tagStyle;
                }
                else if(tagStyle) css = tagStyle;

                if(css) nodeSpec.style = css;

                if(tagType === 'a') {
                    hasLink = true;

                    var href = getQuotedMatch(extra, HREFMATCH);

                    if(href) {
                        // check safe protocols
                        var dummyAnchor = document.createElement('a');
                        dummyAnchor.href = href;
                        if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) {
                            // Decode href to allow both already encoded and not encoded
                            // URIs. Without decoding prior encoding, an already encoded
                            // URI would be encoded twice producing a semantically different URI.
                            nodeSpec.href = encodeURI(decodeURI(href));
                            nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || '_blank';
                            nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH);
                        }
                    }
                }

                enterNode(nodeSpec);
            }
        }
    }

    return hasLink;
}

exports.lineCount = function lineCount(s) {
    return s.selectAll('tspan.line').size() || 1;
};

exports.positionText = function positionText(s, x, y) {
    return s.each(function() {
        var text = d3.select(this);

        function setOrGet(attr, val) {
            if(val === undefined) {
                val = text.attr(attr);
                if(val === null) {
                    text.attr(attr, 0);
                    val = 0;
                }
            }
            else text.attr(attr, val);
            return val;
        }

        var thisX = setOrGet('x', x);
        var thisY = setOrGet('y', y);

        if(this.nodeName === 'text') {
            text.selectAll('tspan.line').attr({x: thisX, y: thisY});
        }
    });
};

function alignHTMLWith(_base, container, options) {
    var alignH = options.horizontalAlign,
        alignV = options.verticalAlign || 'top',
        bRect = _base.node().getBoundingClientRect(),
        cRect = container.node().getBoundingClientRect(),
        thisRect,
        getTop,
        getLeft;

    if(alignV === 'bottom') {
        getTop = function() { return bRect.bottom - thisRect.height; };
    } else if(alignV === 'middle') {
        getTop = function() { return bRect.top + (bRect.height - thisRect.height) / 2; };
    } else { // default: top
        getTop = function() { return bRect.top; };
    }

    if(alignH === 'right') {
        getLeft = function() { return bRect.right - thisRect.width; };
    } else if(alignH === 'center') {
        getLeft = function() { return bRect.left + (bRect.width - thisRect.width) / 2; };
    } else { // default: left
        getLeft = function() { return bRect.left; };
    }

    return function() {
        thisRect = this.node().getBoundingClientRect();
        this.style({
            top: (getTop() - cRect.top) + 'px',
            left: (getLeft() - cRect.left) + 'px',
            'z-index': 1000
        });
        return this;
    };
}

/*
 * Editable title
 * @param {d3.selection} context: the element being edited. Normally text,
 *   but if it isn't, you should provide the styling options
 * @param {object} options:
 *   @param {div} options.gd: graphDiv
 *   @param {d3.selection} options.delegate: item to bind events to if not this
 *   @param {boolean} options.immediate: start editing now (true) or on click (false, default)
 *   @param {string} options.fill: font color if not as shown
 *   @param {string} options.background: background color if not as shown
 *   @param {string} options.text: initial text, if not as shown
 *   @param {string} options.horizontalAlign: alignment of the edit box wrt. the bound element
 *   @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element
 */

exports.makeEditable = function(context, options) {
    var gd = options.gd;
    var _delegate = options.delegate;
    var dispatch = d3.dispatch('edit', 'input', 'cancel');
    var handlerElement = _delegate || context;

    context.style({'pointer-events': _delegate ? 'none' : 'all'});

    if(context.size() !== 1) throw new Error('boo');

    function handleClick() {
        appendEditable();
        context.style({opacity: 0});
        // also hide any mathjax svg
        var svgClass = handlerElement.attr('class'),
            mathjaxClass;
        if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
        else mathjaxClass = '[class*=-math-group]';
        if(mathjaxClass) {
            d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
        }
    }

    function selectElementContents(_el) {
        var el = _el.node();
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        el.focus();
    }

    function appendEditable() {
        var plotDiv = d3.select(gd);
        var container = plotDiv.select('.svg-container');
        var div = container.append('div');
        var cStyle = context.node().style;
        var fontSize = parseFloat(cStyle.fontSize || 12);

        var initialText = options.text;
        if(initialText === undefined) initialText = context.attr('data-unformatted');

        div.classed('plugin-editable editable', true)
            .style({
                position: 'absolute',
                'font-family': cStyle.fontFamily || 'Arial',
                'font-size': fontSize,
                color: options.fill || cStyle.fill || 'black',
                opacity: 1,
                'background-color': options.background || 'transparent',
                outline: '#ffffff33 1px solid',
                margin: [-fontSize / 8 + 1, 0, 0, -1].join('px ') + 'px',
                padding: '0',
                'box-sizing': 'border-box'
            })
            .attr({contenteditable: true})
            .text(initialText)
            .call(alignHTMLWith(context, container, options))
            .on('blur', function() {
                gd._editing = false;
                context.text(this.textContent)
                    .style({opacity: 1});
                var svgClass = d3.select(this).attr('class'),
                    mathjaxClass;
                if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
                else mathjaxClass = '[class*=-math-group]';
                if(mathjaxClass) {
                    d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
                }
                var text = this.textContent;
                d3.select(this).transition().duration(0).remove();
                d3.select(document).on('mouseup', null);
                dispatch.edit.call(context, text);
            })
            .on('focus', function() {
                var editDiv = this;
                gd._editing = true;
                d3.select(document).on('mouseup', function() {
                    if(d3.event.target === editDiv) return false;
                    if(document.activeElement === div.node()) div.node().blur();
                });
            })
            .on('keyup', function() {
                if(d3.event.which === 27) {
                    gd._editing = false;
                    context.style({opacity: 1});
                    d3.select(this)
                        .style({opacity: 0})
                        .on('blur', function() { return false; })
                        .transition().remove();
                    dispatch.cancel.call(context, this.textContent);
                }
                else {
                    dispatch.input.call(context, this.textContent);
                    d3.select(this).call(alignHTMLWith(context, container, options));
                }
            })
            .on('keydown', function() {
                if(d3.event.which === 13) this.blur();
            })
            .call(selectElementContents);
    }

    if(options.immediate) handleClick();
    else handlerElement.on('click', handleClick);

    return d3.rebind(context, dispatch, 'on');
};

},{"../constants/alignment":143,"../constants/string_mappings":146,"../constants/xmlns_namespaces":147,"../lib":164,"d3":6}],186:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var timerCache = {};

/**
 * Throttle a callback. `callback` executes synchronously only if
 * more than `minInterval` milliseconds have already elapsed since the latest
 * call (if any). Otherwise we wait until `minInterval` is over and execute the
 * last callback received while waiting.
 * So the first and last events in a train are always executed (eventually)
 * but some of the events in the middle can be dropped.
 *
 * @param {string} id: an identifier to mark events to throttle together
 * @param {number} minInterval: minimum time, in milliseconds, between
 *   invocations of `callback`
 * @param {function} callback: the function to throttle. `callback` itself
 *   should be a purely synchronous function.
 */
exports.throttle = function throttle(id, minInterval, callback) {
    var cache = timerCache[id];
    var now = Date.now();

    if(!cache) {
        /*
         * Throw out old items before making a new one, to prevent the cache
         * getting overgrown, for example from old plots that have been replaced.
         * 1 minute age is arbitrary.
         */
        for(var idi in timerCache) {
            if(timerCache[idi].ts < now - 60000) {
                delete timerCache[idi];
            }
        }
        cache = timerCache[id] = {ts: 0, timer: null};
    }

    _clearTimeout(cache);

    function exec() {
        callback();
        cache.ts = Date.now();
        if(cache.onDone) {
            cache.onDone();
            cache.onDone = null;
        }
    }

    if(now > cache.ts + minInterval) {
        exec();
        return;
    }

    cache.timer = setTimeout(function() {
        exec();
        cache.timer = null;
    }, minInterval);
};

exports.done = function(id) {
    var cache = timerCache[id];
    if(!cache || !cache.timer) return Promise.resolve();

    return new Promise(function(resolve) {
        var previousOnDone = cache.onDone;
        cache.onDone = function onDone() {
            if(previousOnDone) previousOnDone();
            resolve();
            cache.onDone = null;
        };
    });
};

/**
 * Clear the throttle cache for one or all timers
 * @param {optional string} id:
 *   if provided, clear just this timer
 *   if omitted, clear all timers (mainly useful for testing)
 */
exports.clear = function(id) {
    if(id) {
        _clearTimeout(timerCache[id]);
        delete timerCache[id];
    }
    else {
        for(var idi in timerCache) exports.clear(idi);
    }
};

function _clearTimeout(cache) {
    if(cache && cache.timer !== null) {
        clearTimeout(cache.timer);
        cache.timer = null;
    }
}

},{}],187:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');

/**
 * convert a linear value into a logged value, folding negative numbers into
 * the given range
 */
module.exports = function toLogRange(val, range) {
    if(val > 0) return Math.log(val) / Math.LN10;

    // move a negative value reference to a log axis - just put the
    // result at the lowest range value on the plot (or if the range also went negative,
    // one millionth of the top of the range)
    var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
    if(!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
    return newVal;
};

},{"fast-isnumeric":9}],188:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'en-US',
    dictionary: {
        'Click to enter Colorscale title': 'Click to enter Colorscale title'
    },
    format: {
        date: '%m/%d/%Y'
    }
};

},{}],189:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'en',
    dictionary: {
        'Click to enter Colorscale title': 'Click to enter Colourscale title'
    },
    format: {
        days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        months: [
            'January', 'February', 'March', 'April', 'May', 'June',
            'July', 'August', 'September', 'October', 'November', 'December'
        ],
        shortMonths: [
            'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
            'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
        ],
        periods: ['AM', 'PM'],
        dateTime: '%a %b %e %X %Y',
        date: '%d/%m/%Y',
        time: '%H:%M:%S',
        decimal: '.',
        thousands: ',',
        grouping: [3],
        currency: ['$', ''],
        year: '%Y',
        month: '%b %Y',
        dayMonth: '%b %-d',
        dayMonthYear: '%b %-d, %Y'
    }
};

},{}],190:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../registry');

/*
 * containerArrayMatch: does this attribute string point into a
 * layout container array?
 *
 * @param {String} astr: an attribute string, like *annotations[2].text*
 *
 * @returns {Object | false} Returns false if `astr` doesn't match a container
 *  array. If it does, returns:
 *     {array: {String}, index: {Number}, property: {String}}
 *  ie the attribute string for the array, the index within the array (or ''
 *  if the whole array) and the property within that (or '' if the whole array
 *  or the whole object)
 */
module.exports = function containerArrayMatch(astr) {
    var rootContainers = Registry.layoutArrayContainers,
        regexpContainers = Registry.layoutArrayRegexes,
        rootPart = astr.split('[')[0],
        arrayStr,
        match;

    // look for regexp matches first, because they may be nested inside root matches
    // eg updatemenus[i].buttons is nested inside updatemenus
    for(var i = 0; i < regexpContainers.length; i++) {
        match = astr.match(regexpContainers[i]);
        if(match && match.index === 0) {
            arrayStr = match[0];
            break;
        }
    }

    // now look for root matches
    if(!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)];

    if(!arrayStr) return false;

    var tail = astr.substr(arrayStr.length);
    if(!tail) return {array: arrayStr, index: '', property: ''};

    match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/);
    if(!match) return false;

    return {array: arrayStr, index: Number(match[1]), property: match[3] || ''};
};

},{"../registry":254}],191:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../lib');
var extendFlat = Lib.extendFlat;
var isPlainObject = Lib.isPlainObject;

var traceOpts = {
    valType: 'flaglist',
    extras: ['none'],
    flags: ['calc', 'calcIfAutorange', 'clearAxisTypes', 'plot', 'style', 'colorbars'],
    
};

var layoutOpts = {
    valType: 'flaglist',
    extras: ['none'],
    flags: [
        'calc', 'calcIfAutorange', 'plot', 'legend', 'ticks', 'axrange', 'margins',
        'layoutstyle', 'modebar', 'camera', 'arraydraw'
    ],
    
};

// flags for inside restyle/relayout include a few extras
// that shouldn't be used in attributes, to deal with certain
// combinations and conditionals efficiently
var traceEditTypeFlags = traceOpts.flags.slice()
    .concat(['clearCalc', 'fullReplot']);

var layoutEditTypeFlags = layoutOpts.flags.slice()
    .concat('layoutReplot');

module.exports = {
    traces: traceOpts,
    layout: layoutOpts,
    /*
     * default (all false) edit flags for restyle (traces)
     * creates a new object each call, so the caller can mutate freely
     */
    traceFlags: function() { return falseObj(traceEditTypeFlags); },

    /*
     * default (all false) edit flags for relayout
     * creates a new object each call, so the caller can mutate freely
     */
    layoutFlags: function() { return falseObj(layoutEditTypeFlags); },

    /*
     * update `flags` with the `editType` values found in `attr`
     */
    update: function(flags, attr) {
        var editType = attr.editType;
        if(editType && editType !== 'none') {
            var editTypeParts = editType.split('+');
            for(var i = 0; i < editTypeParts.length; i++) {
                flags[editTypeParts[i]] = true;
            }
        }
    },

    overrideAll: overrideAll
};

function falseObj(keys) {
    var out = {};
    for(var i = 0; i < keys.length; i++) out[keys[i]] = false;
    return out;
}

/**
 * For attributes that are largely copied from elsewhere into a plot type that doesn't
 * support partial redraws - overrides the editType field of all attributes in the object
 *
 * @param {object} attrs: the attributes to override. Will not be mutated.
 * @param {string} editTypeOverride: the new editType to use
 * @param {'nested'|'from-root'} overrideContainers:
 *   - 'nested' will override editType for nested containers but not the root.
 *   - 'from-root' will also override editType of the root container.
 *   Containers below the absolute top level (trace or layout root) DO need an
 *   editType even if they are not `valObject`s themselves (eg `scatter.marker`)
 *   to handle the case where you edit the whole container.
 *
 * @return {object} a new attributes object with `editType` modified as directed
 */
function overrideAll(attrs, editTypeOverride, overrideContainers) {
    var out = extendFlat({}, attrs);
    for(var key in out) {
        var attr = out[key];
        if(isPlainObject(attr)) {
            out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key);
        }
    }
    if(overrideContainers === 'from-root') out.editType = editTypeOverride;

    return out;
}

function overrideOne(attr, editTypeOverride, overrideContainers, key) {
    if(attr.valType) {
        var out = extendFlat({}, attr);
        out.editType = editTypeOverride;

        if(Array.isArray(attr.items)) {
            out.items = new Array(attr.items.length);
            for(var i = 0; i < attr.items.length; i++) {
                out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root');
            }
        }
        return out;
    }
    else {
        // don't provide an editType for the _deprecated container
        return overrideAll(attr, editTypeOverride,
            (key.charAt(0) === '_') ? 'nested' : 'from-root');
    }
}

},{"../lib":164}],192:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var m4FromQuat = require('gl-mat4/fromQuat');

var Registry = require('../registry');
var Lib = require('../lib');
var Plots = require('../plots/plots');
var AxisIds = require('../plots/cartesian/axis_ids');
var cleanId = AxisIds.cleanId;
var getFromTrace = AxisIds.getFromTrace;
var Color = require('../components/color');


// clear the promise queue if one of them got rejected
exports.clearPromiseQueue = function(gd) {
    if(Array.isArray(gd._promises) && gd._promises.length > 0) {
        Lib.log('Clearing previous rejected promises from queue.');
    }

    gd._promises = [];
};

// make a few changes to the layout right away
// before it gets used for anything
// backward compatibility and cleanup of nonstandard options
exports.cleanLayout = function(layout) {
    var i, j;

    if(!layout) layout = {};

    // cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
    if(layout.xaxis1) {
        if(!layout.xaxis) layout.xaxis = layout.xaxis1;
        delete layout.xaxis1;
    }
    if(layout.yaxis1) {
        if(!layout.yaxis) layout.yaxis = layout.yaxis1;
        delete layout.yaxis1;
    }
    if(layout.scene1) {
        if(!layout.scene) layout.scene = layout.scene1;
        delete layout.scene1;
    }

    var axisAttrRegex = (Plots.subplotsRegistry.cartesian || {}).attrRegex;
    var sceneAttrRegex = (Plots.subplotsRegistry.gl3d || {}).attrRegex;

    var keys = Object.keys(layout);
    for(i = 0; i < keys.length; i++) {
        var key = keys[i];

        // modifications to cartesian axes
        if(axisAttrRegex && axisAttrRegex.test(key)) {
            var ax = layout[key];
            if(ax.anchor && ax.anchor !== 'free') {
                ax.anchor = cleanId(ax.anchor);
            }
            if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying);

            // old method of axis type - isdate and islog (before category existed)
            if(!ax.type) {
                if(ax.isdate) ax.type = 'date';
                else if(ax.islog) ax.type = 'log';
                else if(ax.isdate === false && ax.islog === false) ax.type = 'linear';
            }
            if(ax.autorange === 'withzero' || ax.autorange === 'tozero') {
                ax.autorange = true;
                ax.rangemode = 'tozero';
            }
            delete ax.islog;
            delete ax.isdate;
            delete ax.categories; // replaced by _categories

            // prune empty domain arrays made before the new nestedProperty
            if(emptyContainer(ax, 'domain')) delete ax.domain;

            // autotick -> tickmode
            if(ax.autotick !== undefined) {
                if(ax.tickmode === undefined) {
                    ax.tickmode = ax.autotick ? 'auto' : 'linear';
                }
                delete ax.autotick;
            }
        }

        // modifications for 3D scenes
        else if(sceneAttrRegex && sceneAttrRegex.test(key)) {
            var scene = layout[key];

            // clean old Camera coords
            var cameraposition = scene.cameraposition;

            if(Array.isArray(cameraposition) && cameraposition[0].length === 4) {
                var rotation = cameraposition[0],
                    center = cameraposition[1],
                    radius = cameraposition[2],
                    mat = m4FromQuat([], rotation),
                    eye = [];

                for(j = 0; j < 3; ++j) {
                    eye[j] = center[j] + radius * mat[2 + 4 * j];
                }

                scene.camera = {
                    eye: {x: eye[0], y: eye[1], z: eye[2]},
                    center: {x: center[0], y: center[1], z: center[2]},
                    up: {x: mat[1], y: mat[5], z: mat[9]}
                };

                delete scene.cameraposition;
            }
        }
    }

    var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0;
    for(i = 0; i < annotationsLen; i++) {
        var ann = layout.annotations[i];

        if(!Lib.isPlainObject(ann)) continue;

        if(ann.ref) {
            if(ann.ref === 'paper') {
                ann.xref = 'paper';
                ann.yref = 'paper';
            }
            else if(ann.ref === 'data') {
                ann.xref = 'x';
                ann.yref = 'y';
            }
            delete ann.ref;
        }

        cleanAxRef(ann, 'xref');
        cleanAxRef(ann, 'yref');
    }

    var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0;
    for(i = 0; i < shapesLen; i++) {
        var shape = layout.shapes[i];

        if(!Lib.isPlainObject(shape)) continue;

        cleanAxRef(shape, 'xref');
        cleanAxRef(shape, 'yref');
    }

    var legend = layout.legend;
    if(legend) {
        // check for old-style legend positioning (x or y is +/- 100)
        if(legend.x > 3) {
            legend.x = 1.02;
            legend.xanchor = 'left';
        }
        else if(legend.x < -2) {
            legend.x = -0.02;
            legend.xanchor = 'right';
        }

        if(legend.y > 3) {
            legend.y = 1.02;
            legend.yanchor = 'bottom';
        }
        else if(legend.y < -2) {
            legend.y = -0.02;
            legend.yanchor = 'top';
        }
    }

    /*
     * Moved from rotate -> orbit for dragmode
     */
    if(layout.dragmode === 'rotate') layout.dragmode = 'orbit';

    // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
    // supported, but new tinycolor does not because they're not valid css
    Color.clean(layout);

    return layout;
};

function cleanAxRef(container, attr) {
    var valIn = container[attr],
        axLetter = attr.charAt(0);
    if(valIn && valIn !== 'paper') {
        container[attr] = cleanId(valIn, axLetter);
    }
}

/*
 * cleanData: Make a few changes to the data right away
 * before it gets used for anything
 * Mostly for backward compatibility, modifies the data traces users provide.
 *
 * Important: if you're going to add something here that modifies a data array,
 * update it in place so the new array === the old one.
 */
exports.cleanData = function(data, existingData) {
    // Enforce unique IDs
    var suids = [], // seen uids --- so we can weed out incoming repeats
        uids = data.concat(Array.isArray(existingData) ? existingData : [])
               .filter(function(trace) { return 'uid' in trace; })
               .map(function(trace) { return trace.uid; });

    for(var tracei = 0; tracei < data.length; tracei++) {
        var trace = data[tracei];
        var i;

        // assign uids to each trace and detect collisions.
        if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) {
            var newUid;

            for(i = 0; i < 100; i++) {
                newUid = Lib.randstr(uids);
                if(suids.indexOf(newUid) === -1) break;
            }
            trace.uid = Lib.randstr(uids);
            uids.push(trace.uid);
        }
        // keep track of already seen uids, so that if there are
        // doubles we force the trace with a repeat uid to
        // acquire a new one
        suids.push(trace.uid);

        // BACKWARD COMPATIBILITY FIXES

        // use xbins to bin data in x, and ybins to bin data in y
        if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) {
            trace.ybins = trace.xbins;
            delete trace.xbins;
        }

        // error_y.opacity is obsolete - merge into color
        if(trace.error_y && 'opacity' in trace.error_y) {
            var dc = Color.defaults,
                yeColor = trace.error_y.color ||
                (Registry.traceIs(trace, 'bar') ? Color.defaultLine : dc[tracei % dc.length]);
            trace.error_y.color = Color.addOpacity(
                Color.rgb(yeColor),
                Color.opacity(yeColor) * trace.error_y.opacity);
            delete trace.error_y.opacity;
        }

        // convert bardir to orientation, and put the data into
        // the axes it's eventually going to be used with
        if('bardir' in trace) {
            if(trace.bardir === 'h' && (Registry.traceIs(trace, 'bar') ||
                     trace.type.substr(0, 9) === 'histogram')) {
                trace.orientation = 'h';
                exports.swapXYData(trace);
            }
            delete trace.bardir;
        }

        // now we have only one 1D histogram type, and whether
        // it uses x or y data depends on trace.orientation
        if(trace.type === 'histogramy') exports.swapXYData(trace);
        if(trace.type === 'histogramx' || trace.type === 'histogramy') {
            trace.type = 'histogram';
        }

        // scl->scale, reversescl->reversescale
        if('scl' in trace) {
            trace.colorscale = trace.scl;
            delete trace.scl;
        }
        if('reversescl' in trace) {
            trace.reversescale = trace.reversescl;
            delete trace.reversescl;
        }

        // axis ids x1 -> x, y1-> y
        if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x');
        if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y');

        // scene ids scene1 -> scene
        if(Registry.traceIs(trace, 'gl3d') && trace.scene) {
            trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
        }

        if(!Registry.traceIs(trace, 'pie') && !Registry.traceIs(trace, 'bar')) {
            if(Array.isArray(trace.textposition)) {
                for(i = 0; i < trace.textposition.length; i++) {
                    trace.textposition[i] = cleanTextPosition(trace.textposition[i]);
                }
            }
            else if(trace.textposition) {
                trace.textposition = cleanTextPosition(trace.textposition);
            }
        }

        // fix typo in colorscale definition
        if(Registry.traceIs(trace, '2dMap')) {
            if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu';
            if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd';
        }
        if(Registry.traceIs(trace, 'markerColorscale') && trace.marker) {
            var cont = trace.marker;
            if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu';
            if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd';
        }

        // fix typo in surface 'highlight*' definitions
        if(trace.type === 'surface' && Lib.isPlainObject(trace.contours)) {
            var dims = ['x', 'y', 'z'];

            for(i = 0; i < dims.length; i++) {
                var opts = trace.contours[dims[i]];

                if(!Lib.isPlainObject(opts)) continue;

                if(opts.highlightColor) {
                    opts.highlightcolor = opts.highlightColor;
                    delete opts.highlightColor;
                }

                if(opts.highlightWidth) {
                    opts.highlightwidth = opts.highlightWidth;
                    delete opts.highlightWidth;
                }
            }
        }

        // fixes from converting finance from transforms to real trace types
        if(trace.type === 'candlestick' || trace.type === 'ohlc') {
            var increasingShowlegend = (trace.increasing || {}).showlegend !== false;
            var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false;
            var increasingName = cleanFinanceDir(trace.increasing);
            var decreasingName = cleanFinanceDir(trace.decreasing);

            // now figure out something smart to do with the separate direction
            // names we removed
            if((increasingName !== false) && (decreasingName !== false)) {
                // both sub-names existed: base name previously had no effect
                // so ignore it and try to find a shared part of the sub-names

                var newName = commonPrefix(
                    increasingName, decreasingName,
                    increasingShowlegend, decreasingShowlegend
                );
                // if no common part, leave whatever name was (or wasn't) there
                if(newName) trace.name = newName;
            }
            else if((increasingName || decreasingName) && !trace.name) {
                // one sub-name existed but not the base name - just use the sub-name
                trace.name = increasingName || decreasingName;
            }
        }

        // transforms backward compatibility fixes
        if(Array.isArray(trace.transforms)) {
            var transforms = trace.transforms;

            for(i = 0; i < transforms.length; i++) {
                var transform = transforms[i];

                if(!Lib.isPlainObject(transform)) continue;

                switch(transform.type) {
                    case 'filter':
                        if(transform.filtersrc) {
                            transform.target = transform.filtersrc;
                            delete transform.filtersrc;
                        }

                        if(transform.calendar) {
                            if(!transform.valuecalendar) {
                                transform.valuecalendar = transform.calendar;
                            }
                            delete transform.calendar;
                        }
                        break;

                    case 'groupby':
                        // Name has changed from `style` to `styles`, so use `style` but prefer `styles`:
                        transform.styles = transform.styles || transform.style;

                        if(transform.styles && !Array.isArray(transform.styles)) {
                            var prevStyles = transform.styles;
                            var styleKeys = Object.keys(prevStyles);

                            transform.styles = [];
                            for(var j = 0; j < styleKeys.length; j++) {
                                transform.styles.push({
                                    target: styleKeys[j],
                                    value: prevStyles[styleKeys[j]]
                                });
                            }
                        }
                        break;
                }
            }
        }

        // prune empty containers made before the new nestedProperty
        if(emptyContainer(trace, 'line')) delete trace.line;
        if('marker' in trace) {
            if(emptyContainer(trace.marker, 'line')) delete trace.marker.line;
            if(emptyContainer(trace, 'marker')) delete trace.marker;
        }

        // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
        // supported, but new tinycolor does not because they're not valid css
        Color.clean(trace);
    }
};

function cleanFinanceDir(dirContainer) {
    if(!Lib.isPlainObject(dirContainer)) return false;

    var dirName = dirContainer.name;

    delete dirContainer.name;
    delete dirContainer.showlegend;

    return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName);
}

function commonPrefix(name1, name2, show1, show2) {
    // if only one is shown in the legend, use that
    if(show1 && !show2) return name1;
    if(show2 && !show1) return name2;

    // if both or neither are in the legend, check if one is blank (or whitespace)
    // and use the other one
    // note that hover labels can still use the name even if the legend doesn't
    if(!name1.trim()) return name2;
    if(!name2.trim()) return name1;

    var minLen = Math.min(name1.length, name2.length);
    var i;
    for(i = 0; i < minLen; i++) {
        if(name1.charAt(i) !== name2.charAt(i)) break;
    }

    var out = name1.substr(0, i);
    return out.trim();
}

// textposition - support partial attributes (ie just 'top')
// and incorrect use of middle / center etc.
function cleanTextPosition(textposition) {
    var posY = 'middle',
        posX = 'center';
    if(textposition.indexOf('top') !== -1) posY = 'top';
    else if(textposition.indexOf('bottom') !== -1) posY = 'bottom';

    if(textposition.indexOf('left') !== -1) posX = 'left';
    else if(textposition.indexOf('right') !== -1) posX = 'right';

    return posY + ' ' + posX;
}

function emptyContainer(outer, innerStr) {
    return (innerStr in outer) &&
        (typeof outer[innerStr] === 'object') &&
        (Object.keys(outer[innerStr]).length === 0);
}


// swap all the data and data attributes associated with x and y
exports.swapXYData = function(trace) {
    var i;
    Lib.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']);
    if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
        if(trace.transpose) delete trace.transpose;
        else trace.transpose = true;
    }
    if(trace.error_x && trace.error_y) {
        var errorY = trace.error_y,
            copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle :
                !(errorY.color || errorY.thickness || errorY.width);
        Lib.swapAttrs(trace, ['error_?.copy_ystyle']);
        if(copyYstyle) {
            Lib.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']);
        }
    }
    if(typeof trace.hoverinfo === 'string') {
        var hoverInfoParts = trace.hoverinfo.split('+');
        for(i = 0; i < hoverInfoParts.length; i++) {
            if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y';
            else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x';
        }
        trace.hoverinfo = hoverInfoParts.join('+');
    }
};

// coerce traceIndices input to array of trace indices
exports.coerceTraceIndices = function(gd, traceIndices) {
    if(isNumeric(traceIndices)) {
        return [traceIndices];
    }
    else if(!Array.isArray(traceIndices) || !traceIndices.length) {
        return gd.data.map(function(_, i) { return i; });
    }

    return traceIndices;
};

/**
 * Manages logic around array container item creation / deletion / update
 * that nested property alone can't handle.
 *
 * @param {Object} np
 *  nested property of update attribute string about trace or layout object
 * @param {*} newVal
 *  update value passed to restyle / relayout / update
 * @param {Object} undoit
 *  undo hash (N.B. undoit may be mutated here).
 *
 */
exports.manageArrayContainers = function(np, newVal, undoit) {
    var obj = np.obj,
        parts = np.parts,
        pLength = parts.length,
        pLast = parts[pLength - 1];

    var pLastIsNumber = isNumeric(pLast);

    // delete item
    if(pLastIsNumber && newVal === null) {

        // Clear item in array container when new value is null
        var contPath = parts.slice(0, pLength - 1).join('.'),
            cont = Lib.nestedProperty(obj, contPath).get();
        cont.splice(pLast, 1);

        // Note that nested property clears null / undefined at end of
        // array container, but not within them.
    }
    // create item
    else if(pLastIsNumber && np.get() === undefined) {

        // When adding a new item, make sure undo command will remove it
        if(np.get() === undefined) undoit[np.astr] = null;

        np.set(newVal);
    }
    // update item
    else {

        // If the last part of attribute string isn't a number,
        // np.set is all we need.
        np.set(newVal);
    }
};

/*
 * Match the part to strip off to turn an attribute into its parent
 * really it should be either '.some_characters' or '[number]'
 * but we're a little more permissive here and match either
 * '.not_brackets_or_dot' or '[not_brackets_or_dot]'
 */
var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;

function getParent(attr) {
    var tail = attr.search(ATTR_TAIL_RE);
    if(tail > 0) return attr.substr(0, tail);
}

/*
 * hasParent: does an attribute object contain a parent of the given attribute?
 * for example, given 'images[2].x' do we also have 'images' or 'images[2]'?
 *
 * @param {Object} aobj
 *  update object, whose keys are attribute strings and values are their new settings
 * @param {string} attr
 *  the attribute string to test against
 * @returns {Boolean}
 *  is a parent of attr present in aobj?
 */
exports.hasParent = function(aobj, attr) {
    var attrParent = getParent(attr);
    while(attrParent) {
        if(attrParent in aobj) return true;
        attrParent = getParent(attrParent);
    }
    return false;
};

/**
 * Empty out types for all axes containing these traces so we auto-set them again
 *
 * @param {object} gd
 * @param {[integer]} traces: trace indices to search for axes to clear the types of
 * @param {object} layoutUpdate: any update being done concurrently to the layout,
 *   which may supercede clearing the axis types
 */
var axLetters = ['x', 'y', 'z'];
exports.clearAxisTypes = function(gd, traces, layoutUpdate) {
    for(var i = 0; i < traces.length; i++) {
        var trace = gd._fullData[i];
        for(var j = 0; j < 3; j++) {
            var ax = getFromTrace(gd, trace, axLetters[j]);

            // do not clear log type - that's never an auto result so must have been intentional
            if(ax && ax.type !== 'log') {
                var axAttr = ax._name;
                var sceneName = ax._id.substr(1);
                if(sceneName.substr(0, 5) === 'scene') {
                    if(layoutUpdate[sceneName] !== undefined) continue;
                    axAttr = sceneName + '.' + axAttr;
                }
                var typeAttr = axAttr + '.type';

                if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) {
                    Lib.nestedProperty(gd.layout, typeAttr).set(null);
                }
            }
        }
    }
};

exports.clearAxisAutomargins = function(gd) {
    var keys = Object.keys(gd._fullLayout._pushmargin);
    for(var i = 0; i < keys.length; i++) {
        if(keys[i].indexOf('automargin') !== -1) {
            delete gd._fullLayout._pushmargin[keys[i]];
        }
    }
};

},{"../components/color":43,"../lib":164,"../plots/cartesian/axis_ids":209,"../plots/plots":245,"../registry":254,"fast-isnumeric":9,"gl-mat4/fromQuat":10}],193:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var main = require('./plot_api');

exports.plot = main.plot;
exports.newPlot = main.newPlot;
exports.restyle = main.restyle;
exports.relayout = main.relayout;
exports.redraw = main.redraw;
exports.update = main.update;
exports.react = main.react;
exports.extendTraces = main.extendTraces;
exports.prependTraces = main.prependTraces;
exports.addTraces = main.addTraces;
exports.deleteTraces = main.deleteTraces;
exports.moveTraces = main.moveTraces;
exports.purge = main.purge;
exports.addFrames = main.addFrames;
exports.deleteFrames = main.deleteFrames;
exports.animate = main.animate;
exports.setPlotConfig = main.setPlotConfig;

exports.toImage = require('./to_image');
exports.validate = require('./validate');
exports.downloadImage = require('../snapshot/download');

},{"../snapshot/download":256,"./plot_api":195,"./to_image":199,"./validate":200}],194:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var nestedProperty = require('../lib/nested_property');
var isPlainObject = require('../lib/is_plain_object');
var noop = require('../lib/noop');
var Loggers = require('../lib/loggers');
var sorterAsc = require('../lib/search').sorterAsc;
var Registry = require('../registry');


exports.containerArrayMatch = require('./container_array_match');

var isAddVal = exports.isAddVal = function isAddVal(val) {
    return val === 'add' || isPlainObject(val);
};

var isRemoveVal = exports.isRemoveVal = function isRemoveVal(val) {
    return val === null || val === 'remove';
};

/*
 * applyContainerArrayChanges: for managing arrays of layout components in relayout
 * handles them all with a consistent interface.
 *
 * Here are the supported actions -> relayout calls -> edits we get here
 * (as prepared in _relayout):
 *
 * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}}
 * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}}
 * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}}
 *               -> {'annotations[2]': null} -> {2: {'': null}}
 * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}}
 *                        -> {'annotations': null} -> {'': {'': null}}
 * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}}
 *
 * You can combine many edits to different objects. Objects are added and edited
 * in ascending order, then removed in descending order.
 * For example, starting with [a, b, c], if you want to:
 * - replace b with d:
 *   {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d)
 * - add a new item d between a and b, and edit b:
 *    {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d)
 * - delete b and edit c:
 *    {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed)
 *
 * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i`
 * You CANNOT combine replacing/deleting the whole array with anything else (for the same array).
 *
 * @param {HTMLDivElement} gd
 *  the DOM element of the graph container div
 * @param {Lib.nestedProperty} componentType: the array we are editing
 * @param {Object} edits
 *  the changes to make; keys are indices to edit, values are themselves objects:
 *  {attr: newValue} of changes to make to that index (with add/remove behavior
 *  in special values of the empty attr)
 * @param {Object} flags
 *  the flags for which actions we're going to perform to display these (and
 *  any other) changes. If we're already `recalc`ing, we don't need to redraw
 *  individual items
 *
 * @returns {bool} `true` if it managed to complete drawing of the changes
 *  `false` would mean the parent should replot.
 */
exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags) {
    var componentType = np.astr,
        supplyComponentDefaults = Registry.getComponentMethod(componentType, 'supplyLayoutDefaults'),
        draw = Registry.getComponentMethod(componentType, 'draw'),
        drawOne = Registry.getComponentMethod(componentType, 'drawOne'),
        replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === noop) ||
            (draw === noop),
        layout = gd.layout,
        fullLayout = gd._fullLayout;

    if(edits['']) {
        if(Object.keys(edits).length > 1) {
            Loggers.warn('Full array edits are incompatible with other edits',
                componentType);
        }

        var fullVal = edits[''][''];

        if(isRemoveVal(fullVal)) np.set(null);
        else if(Array.isArray(fullVal)) np.set(fullVal);
        else {
            Loggers.warn('Unrecognized full array edit value', componentType, fullVal);
            return true;
        }

        if(replotLater) return false;

        supplyComponentDefaults(layout, fullLayout);
        draw(gd);
        return true;
    }

    var componentNums = Object.keys(edits).map(Number).sort(sorterAsc),
        componentArrayIn = np.get(),
        componentArray = componentArrayIn || [],
        // componentArrayFull is used just to keep splices in line between
        // full and input arrays, so private keys can be copied over after
        // redoing supplyDefaults
        // TODO: this assumes componentArray is in gd.layout - which will not be
        // true after we extend this to restyle
        componentArrayFull = nestedProperty(fullLayout, componentType).get();

    var deletes = [],
        firstIndexChange = -1,
        maxIndex = componentArray.length,
        i,
        j,
        componentNum,
        objEdits,
        objKeys,
        objVal,
        adding;

    // first make the add and edit changes
    for(i = 0; i < componentNums.length; i++) {
        componentNum = componentNums[i];
        objEdits = edits[componentNum];
        objKeys = Object.keys(objEdits);
        objVal = objEdits[''],
        adding = isAddVal(objVal);

        if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) {
            Loggers.warn('index out of range', componentType, componentNum);
            continue;
        }

        if(objVal !== undefined) {
            if(objKeys.length > 1) {
                Loggers.warn(
                    'Insertion & removal are incompatible with edits to the same index.',
                    componentType, componentNum);
            }

            if(isRemoveVal(objVal)) {
                deletes.push(componentNum);
            }
            else if(adding) {
                if(objVal === 'add') objVal = {};
                componentArray.splice(componentNum, 0, objVal);
                if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {});
            }
            else {
                Loggers.warn('Unrecognized full object edit value',
                    componentType, componentNum, objVal);
            }

            if(firstIndexChange === -1) firstIndexChange = componentNum;
        }
        else {
            for(j = 0; j < objKeys.length; j++) {
                nestedProperty(componentArray[componentNum], objKeys[j]).set(objEdits[objKeys[j]]);
            }
        }
    }

    // now do deletes
    for(i = deletes.length - 1; i >= 0; i--) {
        componentArray.splice(deletes[i], 1);
        // TODO: this drops private keys that had been stored in componentArrayFull
        // does this have any ill effects?
        if(componentArrayFull) componentArrayFull.splice(deletes[i], 1);
    }

    if(!componentArray.length) np.set(null);
    else if(!componentArrayIn) np.set(componentArray);

    if(replotLater) return false;

    supplyComponentDefaults(layout, fullLayout);

    // finally draw all the components we need to
    // if we added or removed any, redraw all after it
    if(drawOne !== noop) {
        var indicesToDraw;
        if(firstIndexChange === -1) {
            // there's no re-indexing to do, so only redraw components that changed
            indicesToDraw = componentNums;
        }
        else {
            // in case the component array was shortened, we still need do call
            // drawOne on the latter items so they get properly removed
            maxIndex = Math.max(componentArray.length, maxIndex);
            indicesToDraw = [];
            for(i = 0; i < componentNums.length; i++) {
                componentNum = componentNums[i];
                if(componentNum >= firstIndexChange) break;
                indicesToDraw.push(componentNum);
            }
            for(i = firstIndexChange; i < maxIndex; i++) {
                indicesToDraw.push(i);
            }
        }
        for(i = 0; i < indicesToDraw.length; i++) {
            drawOne(gd, indicesToDraw[i]);
        }
    }
    else draw(gd);

    return true;
};

},{"../lib/is_plain_object":166,"../lib/loggers":169,"../lib/nested_property":172,"../lib/noop":173,"../lib/search":182,"../registry":254,"./container_array_match":190}],195:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


var d3 = require('d3');
var isNumeric = require('fast-isnumeric');
var hasHover = require('has-hover');

var Lib = require('../lib');
var Events = require('../lib/events');
var Queue = require('../lib/queue');

var Registry = require('../registry');
var PlotSchema = require('./plot_schema');
var Plots = require('../plots/plots');
var Polar = require('../plots/polar/legacy');

var Axes = require('../plots/cartesian/axes');
var Drawing = require('../components/drawing');
var Color = require('../components/color');
var initInteractions = require('../plots/cartesian/graph_interact').initInteractions;
var xmlnsNamespaces = require('../constants/xmlns_namespaces');
var svgTextUtils = require('../lib/svg_text_utils');

var defaultConfig = require('./plot_config');
var manageArrays = require('./manage_arrays');
var helpers = require('./helpers');
var subroutines = require('./subroutines');
var editTypes = require('./edit_types');

var AX_NAME_PATTERN = require('../plots/cartesian/constants').AX_NAME_PATTERN;

var numericNameWarningCount = 0;
var numericNameWarningCountLimit = 5;

/**
 * Main plot-creation function
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {array of objects} data
 *      array of traces, containing the data and display information for each trace
 * @param {object} layout
 *      object describing the overall display of the plot,
 *      all the stuff that doesn't pertain to any individual trace
 * @param {object} config
 *      configuration options (see ./plot_config.js for more info)
 *
 * OR
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {object} figure
 *      object containing `data`, `layout`, `config`, and `frames` members
 *
 */
exports.plot = function(gd, data, layout, config) {
    var frames;

    gd = Lib.getGraphDiv(gd);

    // Events.init is idempotent and bails early if gd has already been init'd
    Events.init(gd);

    if(Lib.isPlainObject(data)) {
        var obj = data;
        data = obj.data;
        layout = obj.layout;
        config = obj.config;
        frames = obj.frames;
    }

    var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
    if(okToPlot === false) return Promise.reject();

    // if there's no data or layout, and this isn't yet a plotly plot
    // container, log a warning to help plotly.js users debug
    if(!data && !layout && !Lib.isPlotDiv(gd)) {
        Lib.warn('Calling Plotly.plot as if redrawing ' +
            'but this container doesn\'t yet have a plot.', gd);
    }

    function addFrames() {
        if(frames) {
            return exports.addFrames(gd, frames);
        }
    }

    // transfer configuration options to gd until we move over to
    // a more OO like model
    setPlotContext(gd, config);

    if(!layout) layout = {};

    // hook class for plots main container (in case of plotly.js
    // this won't be #embedded-graph or .js-tab-contents)
    d3.select(gd).classed('js-plotly-plot', true);

    // off-screen getBoundingClientRect testing space,
    // in #js-plotly-tester (and stored as Drawing.tester)
    // so we can share cached text across tabs
    Drawing.makeTester();

    // clear stashed base url
    delete Drawing.baseUrl;

    // collect promises for any async actions during plotting
    // any part of the plotting code can push to gd._promises, then
    // before we move to the next step, we check that they're all
    // complete, and empty out the promise list again.
    if(!Array.isArray(gd._promises)) gd._promises = [];

    var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));

    // if there is already data on the graph, append the new data
    // if you only want to redraw, pass a non-array for data
    if(Array.isArray(data)) {
        helpers.cleanData(data, gd.data);

        if(graphWasEmpty) gd.data = data;
        else gd.data.push.apply(gd.data, data);

        // for routines outside graph_obj that want a clean tab
        // (rather than appending to an existing one) gd.empty
        // is used to determine whether to make a new tab
        gd.empty = false;
    }

    if(!gd.layout || graphWasEmpty) gd.layout = helpers.cleanLayout(layout);

    // if the user is trying to drag the axes, allow new data and layout
    // to come in but don't allow a replot.
    if(gd._dragging && !gd._transitioning) {
        // signal to drag handler that after everything else is done
        // we need to replot, because something has changed
        gd._replotPending = true;
        return Promise.reject();
    } else {
        // we're going ahead with a replot now
        gd._replotPending = false;
    }

    Plots.supplyDefaults(gd);

    var fullLayout = gd._fullLayout;

    var hasCartesian = fullLayout._has('cartesian');

    // Legacy polar plots
    if(!fullLayout._has('polar') && data && data[0] && data[0].r) {
        Lib.log('Legacy polar charts are deprecated!');
        return plotPolar(gd, data, layout);
    }

    // so we don't try to re-call Plotly.plot from inside
    // legend and colorbar, if margins changed
    fullLayout._replotting = true;

    // make or remake the framework if we need to
    if(graphWasEmpty) makePlotFramework(gd);

    // polar need a different framework
    if(gd.framework !== makePlotFramework) {
        gd.framework = makePlotFramework;
        makePlotFramework(gd);
    }

    // clear gradient defs on each .plot call, because we know we'll loop through all traces
    Drawing.initGradients(gd);

    // save initial show spikes once per graph
    if(graphWasEmpty) Axes.saveShowSpikeInitial(gd);

    // prepare the data and find the autorange

    // generate calcdata, if we need to
    // to force redoing calcdata, just delete it before calling Plotly.plot
    var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
    if(recalc) Plots.doCalcdata(gd);

    // in case it has changed, attach fullData traces to calcdata
    for(var i = 0; i < gd.calcdata.length; i++) {
        gd.calcdata[i][0].trace = gd._fullData[i];
    }

    /*
     * start async-friendly code - now we're actually drawing things
     */

    var oldmargins = JSON.stringify(fullLayout._size);

    // draw framework first so that margin-pushing
    // components can position themselves correctly
    function drawFramework() {
        var basePlotModules = fullLayout._basePlotModules;

        for(var i = 0; i < basePlotModules.length; i++) {
            if(basePlotModules[i].drawFramework) {
                basePlotModules[i].drawFramework(gd);
            }
        }

        if(!fullLayout._glcanvas && fullLayout._has('gl')) {
            fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{
                key: 'contextLayer',
                context: true,
                pick: false
            }, {
                key: 'focusLayer',
                context: false,
                pick: false
            }, {
                key: 'pickLayer',
                context: false,
                pick: true
            }], function(d) { return d.key; });

            fullLayout._glcanvas.enter().append('canvas')
                .attr('class', function(d) {
                    return 'gl-canvas gl-canvas-' + d.key.replace('Layer', '');
                })
                .style({
                    'position': 'absolute',
                    'top': 0,
                    'left': 0,
                    'width': '100%',
                    'height': '100%',
                    'overflow': 'visible',
                    'pointer-events': 'none'
                });
        }

        if(fullLayout._glcanvas) {
            fullLayout._glcanvas
                .attr('width', fullLayout.width)
                .attr('height', fullLayout.height);
        }

        return Plots.previousPromises(gd);
    }

    // draw anything that can affect margins.
    function marginPushers() {
        var calcdata = gd.calcdata;
        var i, cd, trace;

        Registry.getComponentMethod('legend', 'draw')(gd);
        Registry.getComponentMethod('rangeselector', 'draw')(gd);
        Registry.getComponentMethod('sliders', 'draw')(gd);
        Registry.getComponentMethod('updatemenus', 'draw')(gd);

        for(i = 0; i < calcdata.length; i++) {
            cd = calcdata[i];
            trace = cd[0].trace;
            if(trace.visible !== true || !trace._module.colorbar) {
                Plots.autoMargin(gd, 'cb' + trace.uid);
            }
            else trace._module.colorbar(gd, cd);
        }

        Plots.doAutoMargin(gd);
        return Plots.previousPromises(gd);
    }

    // in case the margins changed, draw margin pushers again
    function marginPushersAgain() {
        if(JSON.stringify(fullLayout._size) === oldmargins) return;

        return Lib.syncOrAsync([
            marginPushers,
            subroutines.layoutStyles
        ], gd);
    }

    function positionAndAutorange() {
        if(!recalc) {
            doAutoRangeAndConstraints();
            return;
        }

        var subplots = fullLayout._subplots.cartesian;
        var modules = fullLayout._modules;
        var setPositionsArray = [];

        // position and range calculations for traces that
        // depend on each other ie bars (stacked or grouped)
        // and boxes (grouped) push each other out of the way

        var subplotInfo, i, j;

        for(j = 0; j < modules.length; j++) {
            Lib.pushUnique(setPositionsArray, modules[j].setPositions);
        }

        if(setPositionsArray.length) {
            for(i = 0; i < subplots.length; i++) {
                subplotInfo = fullLayout._plots[subplots[i]];

                for(j = 0; j < setPositionsArray.length; j++) {
                    setPositionsArray[j](gd, subplotInfo);
                }
            }
        }

        // calc and autorange for errorbars
        Registry.getComponentMethod('errorbars', 'calc')(gd);

        // TODO: autosize extra for text markers and images
        // see https://github.com/plotly/plotly.js/issues/1111
        return Lib.syncOrAsync([
            Registry.getComponentMethod('shapes', 'calcAutorange'),
            Registry.getComponentMethod('annotations', 'calcAutorange'),
            doAutoRangeAndConstraints,
            Registry.getComponentMethod('rangeslider', 'calcAutorange')
        ], gd);
    }

    function doAutoRangeAndConstraints() {
        if(gd._transitioning) return;

        subroutines.doAutoRangeAndConstraints(gd);

        // store initial ranges *after* enforcing constraints, otherwise
        // we will never look like we're at the initial ranges
        if(graphWasEmpty) Axes.saveRangeInitial(gd);
    }

    // draw ticks, titles, and calculate axis scaling (._b, ._m)
    function drawAxes() {
        return Axes.doTicks(gd, graphWasEmpty ? '' : 'redraw');
    }

    var seq = [
        Plots.previousPromises,
        addFrames,
        drawFramework,
        marginPushers,
        marginPushersAgain
    ];
    if(hasCartesian) seq.push(positionAndAutorange);
    seq.push(subroutines.layoutStyles);
    if(hasCartesian) seq.push(drawAxes);
    seq.push(
        subroutines.drawData,
        subroutines.finalDraw,
        initInteractions,
        Plots.addLinks,
        Plots.rehover,
        Plots.previousPromises
    );

    // even if everything we did was synchronous, return a promise
    // so that the caller doesn't care which route we took
    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();

    return plotDone.then(function() {
        gd.emit('plotly_afterplot');
        return gd;
    });
};

exports.setPlotConfig = function setPlotConfig(obj) {
    return Lib.extendFlat(defaultConfig, obj);
};

function setBackground(gd, bgColor) {
    try {
        gd._fullLayout._paper.style('background', bgColor);
    } catch(e) {
        Lib.error(e);
    }
}

function opaqueSetBackground(gd, bgColor) {
    var blend = Color.combine(bgColor, 'white');
    setBackground(gd, blend);
}

function setPlotContext(gd, config) {
    if(!gd._context) gd._context = Lib.extendDeep({}, defaultConfig);
    var context = gd._context;

    var i, keys, key;

    if(config) {
        keys = Object.keys(config);
        for(i = 0; i < keys.length; i++) {
            key = keys[i];
            if(key === 'editable' || key === 'edits') continue;
            if(key in context) {
                if(key === 'setBackground' && config[key] === 'opaque') {
                    context[key] = opaqueSetBackground;
                } else {
                    context[key] = config[key];
                }
            }
        }

        // map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
        if(config.plot3dPixelRatio && !context.plotGlPixelRatio) {
            context.plotGlPixelRatio = context.plot3dPixelRatio;
        }

        // now deal with editable and edits - first editable overrides
        // everything, then edits refines
        var editable = config.editable;
        if(editable !== undefined) {
            // we're not going to *use* context.editable, we're only going to
            // use context.edits... but keep it for the record
            context.editable = editable;

            keys = Object.keys(context.edits);
            for(i = 0; i < keys.length; i++) {
                context.edits[keys[i]] = editable;
            }
        }
        if(config.edits) {
            keys = Object.keys(config.edits);
            for(i = 0; i < keys.length; i++) {
                key = keys[i];
                if(key in context.edits) {
                    context.edits[key] = config.edits[key];
                }
            }
        }
    }

    // staticPlot forces a bunch of others:
    if(context.staticPlot) {
        context.editable = false;
        context.edits = {};
        context.autosizable = false;
        context.scrollZoom = false;
        context.doubleClick = false;
        context.showTips = false;
        context.showLink = false;
        context.displayModeBar = false;
    }

    // make sure hover-only devices have mode bar visible
    if(context.displayModeBar === 'hover' && !hasHover) {
        context.displayModeBar = true;
    }

    // default and fallback for setBackground
    if(context.setBackground === 'transparent' || typeof context.setBackground !== 'function') {
        context.setBackground = setBackground;
    }
}

function plotPolar(gd, data, layout) {
    // build or reuse the container skeleton
    var plotContainer = d3.select(gd).selectAll('.plot-container')
        .data([0]);
    plotContainer.enter()
        .insert('div', ':first-child')
        .classed('plot-container plotly', true);
    var paperDiv = plotContainer.selectAll('.svg-container')
        .data([0]);
    paperDiv.enter().append('div')
        .classed('svg-container', true)
        .style('position', 'relative');

    // empty it everytime for now
    paperDiv.html('');

    // fulfill gd requirements
    if(data) gd.data = data;
    if(layout) gd.layout = layout;
    Polar.manager.fillLayout(gd);

    // resize canvas
    paperDiv.style({
        width: gd._fullLayout.width + 'px',
        height: gd._fullLayout.height + 'px'
    });

    // instantiate framework
    gd.framework = Polar.manager.framework(gd);

    // plot
    gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node());

    // set undo point
    gd.framework.setUndoPoint();

    // get the resulting svg for extending it
    var polarPlotSVG = gd.framework.svg();

    // editable title
    var opacity = 1;
    var txt = gd._fullLayout.title;
    if(txt === '' || !txt) opacity = 0;

    var titleLayout = function() {
        this.call(svgTextUtils.convertToTspans, gd);
        // TODO: html/mathjax
        // TODO: center title
    };

    var title = polarPlotSVG.select('.title-group text')
        .call(titleLayout);

    if(gd._context.edits.titleText) {
        var placeholderText = Lib._(gd, 'Click to enter Plot title');
        if(!txt || txt === placeholderText) {
            opacity = 0.2;
            // placeholder is not going through convertToTspans
            // so needs explicit data-unformatted
            title.attr({'data-unformatted': placeholderText})
                .text(placeholderText)
                .style({opacity: opacity})
                .on('mouseover.opacity', function() {
                    d3.select(this).transition().duration(100)
                        .style('opacity', 1);
                })
                .on('mouseout.opacity', function() {
                    d3.select(this).transition().duration(1000)
                        .style('opacity', 0);
                });
        }

        var setContenteditable = function() {
            this.call(svgTextUtils.makeEditable, {gd: gd})
                .on('edit', function(text) {
                    gd.framework({layout: {title: text}});
                    this.text(text)
                        .call(titleLayout);
                    this.call(setContenteditable);
                })
                .on('cancel', function() {
                    var txt = this.attr('data-unformatted');
                    this.text(txt).call(titleLayout);
                });
        };
        title.call(setContenteditable);
    }

    gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor);
    Plots.addLinks(gd);

    return Promise.resolve();
}

// convenience function to force a full redraw, mostly for use by plotly.js
exports.redraw = function(gd) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error('This element is not a Plotly plot: ' + gd);
    }

    helpers.cleanData(gd.data, gd.data);
    helpers.cleanLayout(gd.layout);

    gd.calcdata = undefined;
    return exports.plot(gd).then(function() {
        gd.emit('plotly_redraw');
        return gd;
    });
};

/**
 * Convenience function to make idempotent plot option obvious to users.
 *
 * @param gd
 * @param {Object[]} data
 * @param {Object} layout
 * @param {Object} config
 */
exports.newPlot = function(gd, data, layout, config) {
    gd = Lib.getGraphDiv(gd);

    // remove gl contexts
    Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}, gd.calcdata || []);

    Plots.purge(gd);
    return exports.plot(gd, data, layout, config);
};

/**
 * Wrap negative indicies to their positive counterparts.
 *
 * @param {Number[]} indices An array of indices
 * @param {Number} maxIndex The maximum index allowable (arr.length - 1)
 */
function positivifyIndices(indices, maxIndex) {
    var parentLength = maxIndex + 1,
        positiveIndices = [],
        i,
        index;

    for(i = 0; i < indices.length; i++) {
        index = indices[i];
        if(index < 0) {
            positiveIndices.push(parentLength + index);
        } else {
            positiveIndices.push(index);
        }
    }
    return positiveIndices;
}

/**
 * Ensures that an index array for manipulating gd.data is valid.
 *
 * Intended for use with addTraces, deleteTraces, and moveTraces.
 *
 * @param gd
 * @param indices
 * @param arrayName
 */
function assertIndexArray(gd, indices, arrayName) {
    var i,
        index;

    for(i = 0; i < indices.length; i++) {
        index = indices[i];

        // validate that indices are indeed integers
        if(index !== parseInt(index, 10)) {
            throw new Error('all values in ' + arrayName + ' must be integers');
        }

        // check that all indices are in bounds for given gd.data array length
        if(index >= gd.data.length || index < -gd.data.length) {
            throw new Error(arrayName + ' must be valid indices for gd.data.');
        }

        // check that indices aren't repeated
        if(indices.indexOf(index, i + 1) > -1 ||
                index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
                index < 0 && indices.indexOf(gd.data.length + index) > -1) {
            throw new Error('each index in ' + arrayName + ' must be unique.');
        }
    }
}

/**
 * Private function used by Plotly.moveTraces to check input args
 *
 * @param gd
 * @param currentIndices
 * @param newIndices
 */
function checkMoveTracesArgs(gd, currentIndices, newIndices) {

    // check that gd has attribute 'data' and 'data' is array
    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array.');
    }

    // validate currentIndices array
    if(typeof currentIndices === 'undefined') {
        throw new Error('currentIndices is a required argument.');
    } else if(!Array.isArray(currentIndices)) {
        currentIndices = [currentIndices];
    }
    assertIndexArray(gd, currentIndices, 'currentIndices');

    // validate newIndices array if it exists
    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }
    if(typeof newIndices !== 'undefined') {
        assertIndexArray(gd, newIndices, 'newIndices');
    }

    // check currentIndices and newIndices are the same length if newIdices exists
    if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
        throw new Error('current and new indices must be of equal length.');
    }

}
/**
 * A private function to reduce the type checking clutter in addTraces.
 *
 * @param gd
 * @param traces
 * @param newIndices
 */
function checkAddTracesArgs(gd, traces, newIndices) {
    var i, value;

    // check that gd has attribute 'data' and 'data' is array
    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array.');
    }

    // make sure traces exists
    if(typeof traces === 'undefined') {
        throw new Error('traces must be defined.');
    }

    // make sure traces is an array
    if(!Array.isArray(traces)) {
        traces = [traces];
    }

    // make sure each value in traces is an object
    for(i = 0; i < traces.length; i++) {
        value = traces[i];
        if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {
            throw new Error('all values in traces array must be non-array objects');
        }
    }

    // make sure we have an index for each trace
    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }
    if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
        throw new Error(
            'if indices is specified, traces.length must equal indices.length'
        );
    }
}

/**
 * A private function to reduce the type checking clutter in spliceTraces.
 * Get all update Properties from gd.data. Validate inputs and outputs.
 * Used by prependTrace and extendTraces
 *
 * @param gd
 * @param update
 * @param indices
 * @param maxPoints
 */
function assertExtendTracesArgs(gd, update, indices, maxPoints) {

    var maxPointsIsObject = Lib.isPlainObject(maxPoints);

    if(!Array.isArray(gd.data)) {
        throw new Error('gd.data must be an array');
    }
    if(!Lib.isPlainObject(update)) {
        throw new Error('update must be a key:value object');
    }

    if(typeof indices === 'undefined') {
        throw new Error('indices must be an integer or array of integers');
    }

    assertIndexArray(gd, indices, 'indices');

    for(var key in update) {

        /*
         * Verify that the attribute to be updated contains as many trace updates
         * as indices. Failure must result in throw and no-op
         */
        if(!Array.isArray(update[key]) || update[key].length !== indices.length) {
            throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
        }

        /*
         * if maxPoints is an object it must match keys and array lengths of 'update' 1:1
         */
        if(maxPointsIsObject &&
            (!(key in maxPoints) || !Array.isArray(maxPoints[key]) ||
            maxPoints[key].length !== update[key].length)) {
            throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' +
                            'corrispondence with the keys and number of traces in the update object');
        }
    }
}

/**
 * A private function to reduce the type checking clutter in spliceTraces.
 *
 * @param {Object|HTMLDivElement} gd
 * @param {Object} update
 * @param {Number[]} indices
 * @param {Number||Object} maxPoints
 * @return {Object[]}
 */
function getExtendProperties(gd, update, indices, maxPoints) {

    var maxPointsIsObject = Lib.isPlainObject(maxPoints),
        updateProps = [];
    var trace, target, prop, insert, maxp;

    // allow scalar index to represent a single trace position
    if(!Array.isArray(indices)) indices = [indices];

    // negative indices are wrapped around to their positive value. Equivalent to python indexing.
    indices = positivifyIndices(indices, gd.data.length - 1);

    // loop through all update keys and traces and harvest validated data.
    for(var key in update) {

        for(var j = 0; j < indices.length; j++) {

            /*
             * Choose the trace indexed by the indices map argument and get the prop setter-getter
             * instance that references the key and value for this particular trace.
             */
            trace = gd.data[indices[j]];
            prop = Lib.nestedProperty(trace, key);

            /*
             * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
             * Target must exist as an Array to allow the extend operation to be performed.
             */
            target = prop.get();
            insert = update[key][j];

            if(!Lib.isArrayOrTypedArray(insert)) {
                throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
            }
            if(!Lib.isArrayOrTypedArray(target)) {
                throw new Error('cannot extend missing or non-array attribute: ' + key);
            }
            if(target.constructor !== insert.constructor) {
                throw new Error('cannot extend array with an array of a different type: ' + key);
            }

            /*
             * maxPoints may be an object map or a scalar. If object select the key:value, else
             * Use the scalar maxPoints for all key and trace combinations.
             */
            maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;

            // could have chosen null here, -1 just tells us to not take a window
            if(!isNumeric(maxp)) maxp = -1;

            /*
             * Wrap the nestedProperty in an object containing required data
             * for lengthening and windowing this particular trace - key combination.
             * Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
             */
            updateProps.push({
                prop: prop,
                target: target,
                insert: insert,
                maxp: Math.floor(maxp)
            });
        }
    }

    // all target and insertion data now validated
    return updateProps;
}

/**
 * A private function to key Extend and Prepend traces DRY
 *
 * @param {Object|HTMLDivElement} gd
 * @param {Object} update
 * @param {Number[]} indices
 * @param {Number||Object} maxPoints
 * @param {Function} updateArray
 * @return {Object}
 */
function spliceTraces(gd, update, indices, maxPoints, updateArray) {
    assertExtendTracesArgs(gd, update, indices, maxPoints);

    var updateProps = getExtendProperties(gd, update, indices, maxPoints);
    var undoUpdate = {};
    var undoPoints = {};

    for(var i = 0; i < updateProps.length; i++) {
        var prop = updateProps[i].prop;
        var maxp = updateProps[i].maxp;

        // return new array and remainder
        var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
        prop.set(out[0]);

        // build the inverse update object for the undo operation
        if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
        undoUpdate[prop.astr].push(out[1]);

         // build the matching maxPoints undo object containing original trace lengths
        if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
        undoPoints[prop.astr].push(updateProps[i].target.length);
    }

    return {update: undoUpdate, maxPoints: undoPoints};
}

function concatTypedArray(arr0, arr1) {
    var arr2 = new arr0.constructor(arr0.length + arr1.length);
    arr2.set(arr0);
    arr2.set(arr1, arr0.length);
    return arr2;
}

/**
 * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
 *
 * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
 * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
 * from the head, whereas Extend truncates the head of the array, counting backward maxPoints
 * from the tail.
 *
 * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
 * truncation / windowing will be performed. If its zero, well the whole trace is truncated.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object} update The key:array map of target attributes to extend
 * @param {Number|Number[]} indices The locations of traces to be extended
 * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
 *
 */
exports.extendTraces = function extendTraces(gd, update, indices, maxPoints) {
    gd = Lib.getGraphDiv(gd);

    function updateArray(target, insert, maxp) {
        var newArray, remainder;

        if(Lib.isTypedArray(target)) {
            if(maxp < 0) {
                var none = new target.constructor(0);
                var both = concatTypedArray(target, insert);

                if(maxp < 0) {
                    newArray = both;
                    remainder = none;
                } else {
                    newArray = none;
                    remainder = both;
                }
            } else {
                newArray = new target.constructor(maxp);
                remainder = new target.constructor(target.length + insert.length - maxp);

                if(maxp === insert.length) {
                    newArray.set(insert);
                    remainder.set(target);
                } else if(maxp < insert.length) {
                    var numberOfItemsFromInsert = insert.length - maxp;

                    newArray.set(insert.subarray(numberOfItemsFromInsert));
                    remainder.set(target);
                    remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
                } else {
                    var numberOfItemsFromTarget = maxp - insert.length;
                    var targetBegin = target.length - numberOfItemsFromTarget;

                    newArray.set(target.subarray(targetBegin));
                    newArray.set(insert, numberOfItemsFromTarget);
                    remainder.set(target.subarray(0, targetBegin));
                }
            }
        } else {
            newArray = target.concat(insert);
            remainder = (maxp >= 0 && maxp < newArray.length) ?
                newArray.splice(0, newArray.length - maxp) :
                [];
        }

        return [newArray, remainder];
    }

    var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
    var promise = exports.redraw(gd);
    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
    Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);

    return promise;
};

exports.prependTraces = function prependTraces(gd, update, indices, maxPoints) {
    gd = Lib.getGraphDiv(gd);

    function updateArray(target, insert, maxp) {
        var newArray, remainder;

        if(Lib.isTypedArray(target)) {
            if(maxp <= 0) {
                var none = new target.constructor(0);
                var both = concatTypedArray(insert, target);

                if(maxp < 0) {
                    newArray = both;
                    remainder = none;
                } else {
                    newArray = none;
                    remainder = both;
                }
            } else {
                newArray = new target.constructor(maxp);
                remainder = new target.constructor(target.length + insert.length - maxp);

                if(maxp === insert.length) {
                    newArray.set(insert);
                    remainder.set(target);
                } else if(maxp < insert.length) {
                    var numberOfItemsFromInsert = insert.length - maxp;

                    newArray.set(insert.subarray(0, numberOfItemsFromInsert));
                    remainder.set(insert.subarray(numberOfItemsFromInsert));
                    remainder.set(target, numberOfItemsFromInsert);
                } else {
                    var numberOfItemsFromTarget = maxp - insert.length;

                    newArray.set(insert);
                    newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
                    remainder.set(target.subarray(numberOfItemsFromTarget));
                }
            }
        } else {
            newArray = insert.concat(target);
            remainder = (maxp >= 0 && maxp < newArray.length) ?
                newArray.splice(maxp, newArray.length) :
                [];
        }

        return [newArray, remainder];
    }

    var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
    var promise = exports.redraw(gd);
    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
    Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);

    return promise;
};

/**
 * Add data traces to an existing graph div.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're adding to
 * @param {Object[]|Object} traces The object or array of objects to add
 * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces
 *
 */
exports.addTraces = function addTraces(gd, traces, newIndices) {
    gd = Lib.getGraphDiv(gd);

    var currentIndices = [],
        undoFunc = exports.deleteTraces,
        redoFunc = addTraces,
        undoArgs = [gd, currentIndices],
        redoArgs = [gd, traces],  // no newIndices here
        i,
        promise;

    // all validation is done elsewhere to remove clutter here
    checkAddTracesArgs(gd, traces, newIndices);

    // make sure traces is an array
    if(!Array.isArray(traces)) {
        traces = [traces];
    }

    // make sure traces do not repeat existing ones
    traces = traces.map(function(trace) {
        return Lib.extendFlat({}, trace);
    });

    helpers.cleanData(traces, gd.data);

    // add the traces to gd.data (no redrawing yet!)
    for(i = 0; i < traces.length; i++) {
        gd.data.push(traces[i]);
    }

    // to continue, we need to call moveTraces which requires currentIndices
    for(i = 0; i < traces.length; i++) {
        currentIndices.push(-traces.length + i);
    }

    // if the user didn't define newIndices, they just want the traces appended
    // i.e., we can simply redraw and be done
    if(typeof newIndices === 'undefined') {
        promise = exports.redraw(gd);
        Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
        return promise;
    }

    // make sure indices is property defined
    if(!Array.isArray(newIndices)) {
        newIndices = [newIndices];
    }

    try {

        // this is redundant, but necessary to not catch later possible errors!
        checkMoveTracesArgs(gd, currentIndices, newIndices);
    }
    catch(error) {

        // something went wrong, reset gd to be safe and rethrow error
        gd.data.splice(gd.data.length - traces.length, traces.length);
        throw error;
    }

    // if we're here, the user has defined specific places to place the new traces
    // this requires some extra work that moveTraces will do
    Queue.startSequence(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
    promise = exports.moveTraces(gd, currentIndices, newIndices);
    Queue.stopSequence(gd);
    return promise;
};

/**
 * Delete traces at `indices` from gd.data array.
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're removing from
 * @param {Number|Number[]} indices The indices
 */
exports.deleteTraces = function deleteTraces(gd, indices) {
    gd = Lib.getGraphDiv(gd);

    var traces = [],
        undoFunc = exports.addTraces,
        redoFunc = deleteTraces,
        undoArgs = [gd, traces, indices],
        redoArgs = [gd, indices],
        i,
        deletedTrace;

    // make sure indices are defined
    if(typeof indices === 'undefined') {
        throw new Error('indices must be an integer or array of integers.');
    } else if(!Array.isArray(indices)) {
        indices = [indices];
    }
    assertIndexArray(gd, indices, 'indices');

    // convert negative indices to positive indices
    indices = positivifyIndices(indices, gd.data.length - 1);

    // we want descending here so that splicing later doesn't affect indexing
    indices.sort(Lib.sorterDes);
    for(i = 0; i < indices.length; i += 1) {
        deletedTrace = gd.data.splice(indices[i], 1)[0];
        traces.push(deletedTrace);
    }

    var promise = exports.redraw(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return promise;
};

/**
 * Move traces at currentIndices array to locations in newIndices array.
 *
 * If newIndices is omitted, currentIndices will be moved to the end. E.g.,
 * these are equivalent:
 *
 * Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1])
 * Plotly.moveTraces(gd, [1, 2, 3])
 *
 * @param {Object|HTMLDivElement} gd The graph div
 * @param {Object[]} gd.data The array of traces we're removing from
 * @param {Number|Number[]} currentIndices The locations of traces to be moved
 * @param {Number|Number[]} [newIndices] The locations to move traces to
 *
 * Example calls:
 *
 *      // move trace i to location x
 *      Plotly.moveTraces(gd, i, x)
 *
 *      // move trace i to end of array
 *      Plotly.moveTraces(gd, i)
 *
 *      // move traces i, j, k to end of array (i != j != k)
 *      Plotly.moveTraces(gd, [i, j, k])
 *
 *      // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z)
 *      Plotly.moveTraces(gd, [i, j, k], [x, y, z])
 *
 *      // reorder all traces (assume there are 5--a, b, c, d, e)
 *      Plotly.moveTraces(gd, [b, d, e, a, c])  // same as 'move to end'
 */
exports.moveTraces = function moveTraces(gd, currentIndices, newIndices) {
    gd = Lib.getGraphDiv(gd);

    var newData = [],
        movingTraceMap = [],
        undoFunc = moveTraces,
        redoFunc = moveTraces,
        undoArgs = [gd, newIndices, currentIndices],
        redoArgs = [gd, currentIndices, newIndices],
        i;

    // to reduce complexity here, check args elsewhere
    // this throws errors where appropriate
    checkMoveTracesArgs(gd, currentIndices, newIndices);

    // make sure currentIndices is an array
    currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];

    // if undefined, define newIndices to point to the end of gd.data array
    if(typeof newIndices === 'undefined') {
        newIndices = [];
        for(i = 0; i < currentIndices.length; i++) {
            newIndices.push(-currentIndices.length + i);
        }
    }

    // make sure newIndices is an array if it's user-defined
    newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];

    // convert negative indices to positive indices (they're the same length)
    currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
    newIndices = positivifyIndices(newIndices, gd.data.length - 1);

    // at this point, we've coerced the index arrays into predictable forms

    // get the traces that aren't being moved around
    for(i = 0; i < gd.data.length; i++) {

        // if index isn't in currentIndices, include it in ignored!
        if(currentIndices.indexOf(i) === -1) {
            newData.push(gd.data[i]);
        }
    }

    // get a mapping of indices to moving traces
    for(i = 0; i < currentIndices.length; i++) {
        movingTraceMap.push({newIndex: newIndices[i], trace: gd.data[currentIndices[i]]});
    }

    // reorder this mapping by newIndex, ascending
    movingTraceMap.sort(function(a, b) {
        return a.newIndex - b.newIndex;
    });

    // now, add the moving traces back in, in order!
    for(i = 0; i < movingTraceMap.length; i += 1) {
        newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
    }

    gd.data = newData;

    var promise = exports.redraw(gd);
    Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return promise;
};

/**
 * restyle: update trace attributes of an existing plot
 *
 * Can be called two ways.
 *
 * Signature 1:
 * @param {String | HTMLDivElement} gd
 *  the id or DOM element of the graph container div
 * @param {String} astr
 *  attribute string (like `'marker.symbol'`) to update
 * @param {*} val
 *  value to give this attribute
 * @param {Number[] | Number} [traces]
 *  integer or array of integers for the traces to alter (all if omitted)
 *
 * Signature 2:
 * @param {String | HTMLDivElement} gd
 *  (as in signature 1)
 * @param {Object} aobj
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  allows setting multiple attributes simultaneously
 * @param {Number[] | Number} [traces]
 *  (as in signature 1)
 *
 * `val` (or `val1`, `val2` ... in the object form) can be an array,
 * to apply different values to each trace.
 *
 * If the array is too short, it will wrap around (useful for
 * style files that want to specify cyclical default values).
 */
exports.restyle = function restyle(gd, astr, val, _traces) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    var aobj = {};
    if(typeof astr === 'string') aobj[astr] = val;
    else if(Lib.isPlainObject(astr)) {
        // the 3-arg form
        aobj = Lib.extendFlat({}, astr);
        if(_traces === undefined) _traces = val;
    }
    else {
        Lib.warn('Restyle fail.', astr, val, _traces);
        return Promise.reject();
    }

    if(Object.keys(aobj).length) gd.changed = true;

    var traces = helpers.coerceTraceIndices(gd, _traces);

    var specs = _restyle(gd, aobj, traces);
    var flags = specs.flags;

    // clear calcdata and/or axis types if required so they get regenerated
    if(flags.clearCalc) gd.calcdata = undefined;
    if(flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {});

    // fill in redraw sequence
    var seq = [];

    if(flags.fullReplot) {
        seq.push(exports.plot);
    } else {
        seq.push(Plots.previousPromises);

        Plots.supplyDefaults(gd);

        if(flags.style) seq.push(subroutines.doTraceStyle);
        if(flags.colorbars) seq.push(subroutines.doColorBars);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        restyle, [gd, specs.undoit, specs.traces],
        restyle, [gd, specs.redoit, specs.traces]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();

    return plotDone.then(function() {
        gd.emit('plotly_restyle', specs.eventData);
        return gd;
    });
};

// for undo: undefined initial vals must be turned into nulls
// so that we unset rather than ignore them
function undefinedToNull(val) {
    if(val === undefined) return null;
    return val;
}

function _restyle(gd, aobj, traces) {
    var fullLayout = gd._fullLayout,
        fullData = gd._fullData,
        data = gd.data,
        i;

    // initialize flags
    var flags = editTypes.traceFlags();

    // copies of the change (and previous values of anything affected)
    // for the undo / redo queue
    var redoit = {},
        undoit = {},
        axlist;

    // make a new empty vals array for undoit
    function a0() { return traces.map(function() { return undefined; }); }

    // for autoranging multiple axes
    function addToAxlist(axid) {
        var axName = Axes.id2name(axid);
        if(axlist.indexOf(axName) === -1) axlist.push(axName);
    }

    function autorangeAttr(axName) { return 'LAYOUT' + axName + '.autorange'; }

    function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; }

    // for attrs that interact (like scales & autoscales), save the
    // old vals before making the change
    // val=undefined will not set a value, just record what the value was.
    // val=null will delete the attribute
    // attr can be an array to set several at once (all to the same val)
    function doextra(attr, val, i) {
        if(Array.isArray(attr)) {
            attr.forEach(function(a) { doextra(a, val, i); });
            return;
        }
        // quit if explicitly setting this elsewhere
        if(attr in aobj || helpers.hasParent(aobj, attr)) return;

        var extraparam;
        if(attr.substr(0, 6) === 'LAYOUT') {
            extraparam = Lib.nestedProperty(gd.layout, attr.replace('LAYOUT', ''));
        } else {
            extraparam = Lib.nestedProperty(data[traces[i]], attr);
        }

        if(!(attr in undoit)) {
            undoit[attr] = a0();
        }
        if(undoit[attr][i] === undefined) {
            undoit[attr][i] = undefinedToNull(extraparam.get());
        }
        if(val !== undefined) {
            extraparam.set(val);
        }
    }

    // now make the changes to gd.data (and occasionally gd.layout)
    // and figure out what kind of graphics update we need to do
    for(var ai in aobj) {
        if(helpers.hasParent(aobj, ai)) {
            throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously');
        }

        var vi = aobj[ai],
            cont,
            contFull,
            param,
            oldVal,
            newVal,
            valObject;

        redoit[ai] = vi;

        if(ai.substr(0, 6) === 'LAYOUT') {
            param = Lib.nestedProperty(gd.layout, ai.replace('LAYOUT', ''));
            undoit[ai] = [undefinedToNull(param.get())];
            // since we're allowing val to be an array, allow it here too,
            // even though that's meaningless
            param.set(Array.isArray(vi) ? vi[0] : vi);
            // ironically, the layout attrs in restyle only require replot,
            // not relayout
            flags.calc = true;
            continue;
        }

        // set attribute in gd.data
        undoit[ai] = a0();
        for(i = 0; i < traces.length; i++) {
            cont = data[traces[i]];
            contFull = fullData[traces[i]];
            param = Lib.nestedProperty(cont, ai);
            oldVal = param.get();
            newVal = Array.isArray(vi) ? vi[i % vi.length] : vi;

            if(newVal === undefined) continue;

            valObject = PlotSchema.getTraceValObject(contFull, param.parts);

            if(valObject && valObject.impliedEdits && newVal !== null) {
                for(var impliedKey in valObject.impliedEdits) {
                    doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i);
                }
            }

            // changing colorbar size modes,
            // make the resulting size not change
            // note that colorbar fractional sizing is based on the
            // original plot size, before anything (like a colorbar)
            // increases the margins
            else if(ai === 'colorbar.thicknessmode' && param.get() !== newVal &&
                        ['fraction', 'pixels'].indexOf(newVal) !== -1 &&
                        contFull.colorbar) {
                var thicknorm =
                    ['top', 'bottom'].indexOf(contFull.colorbar.orient) !== -1 ?
                        (fullLayout.height - fullLayout.margin.t - fullLayout.margin.b) :
                        (fullLayout.width - fullLayout.margin.l - fullLayout.margin.r);
                doextra('colorbar.thickness', contFull.colorbar.thickness *
                    (newVal === 'fraction' ? 1 / thicknorm : thicknorm), i);
            }
            else if(ai === 'colorbar.lenmode' && param.get() !== newVal &&
                        ['fraction', 'pixels'].indexOf(newVal) !== -1 &&
                        contFull.colorbar) {
                var lennorm =
                    ['top', 'bottom'].indexOf(contFull.colorbar.orient) !== -1 ?
                        (fullLayout.width - fullLayout.margin.l - fullLayout.margin.r) :
                        (fullLayout.height - fullLayout.margin.t - fullLayout.margin.b);
                doextra('colorbar.len', contFull.colorbar.len *
                    (newVal === 'fraction' ? 1 / lennorm : lennorm), i);
            }
            else if(ai === 'colorbar.tick0' || ai === 'colorbar.dtick') {
                doextra('colorbar.tickmode', 'linear', i);
            }

            if(ai === 'type' && (newVal === 'pie') !== (oldVal === 'pie')) {
                var labelsTo = 'x',
                    valuesTo = 'y';
                if((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') {
                    labelsTo = 'y';
                    valuesTo = 'x';
                }
                Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo);
                Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo);
                Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo);

                if(oldVal === 'pie') {
                    Lib.nestedProperty(cont, 'marker.color')
                        .set(Lib.nestedProperty(cont, 'marker.colors').get());

                    // super kludgy - but if all pies are gone we won't remove them otherwise
                    fullLayout._pielayer.selectAll('g.trace').remove();
                } else if(Registry.traceIs(cont, 'cartesian')) {
                    Lib.nestedProperty(cont, 'marker.colors')
                        .set(Lib.nestedProperty(cont, 'marker.color').get());
                }
            }

            undoit[ai][i] = undefinedToNull(oldVal);
            // set the new value - if val is an array, it's one el per trace
            // first check for attributes that get more complex alterations
            var swapAttrs = [
                'swapxy', 'swapxyaxes', 'orientation', 'orientationaxes'
            ];
            if(swapAttrs.indexOf(ai) !== -1) {
                // setting an orientation: make sure it's changing
                // before we swap everything else
                if(ai === 'orientation') {
                    param.set(newVal);
                    // obnoxious that we need this level of coupling... but in order to
                    // properly handle setting orientation to `null` we need to mimic
                    // the logic inside Bars.supplyDefaults for default orientation
                    var defaultOrientation = (cont.x && !cont.y) ? 'h' : 'v';
                    if((param.get() || defaultOrientation) === contFull.orientation) {
                        continue;
                    }
                }
                // orientationaxes has no value,
                // it flips everything and the axes
                else if(ai === 'orientationaxes') {
                    cont.orientation =
                        {v: 'h', h: 'v'}[contFull.orientation];
                }
                helpers.swapXYData(cont);
                flags.calc = flags.clearAxisTypes = true;
            }
            else if(Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) {
                // TODO: use manageArrays.applyContainerArrayChanges here too
                helpers.manageArrayContainers(param, newVal, undoit);
                flags.calc = true;
            }
            else {
                if(valObject) {
                    // must redo calcdata when restyling array values of arrayOk attributes
                    if(valObject.arrayOk && (
                        Lib.isArrayOrTypedArray(newVal) || Lib.isArrayOrTypedArray(oldVal))
                    ) {
                        flags.calc = true;
                    }
                    else editTypes.update(flags, valObject);
                }
                else {
                    /*
                     * if we couldn't find valObject,  assume a full recalc.
                     * This can happen if you're changing type and making
                     * some other edits too, so the modules we're
                     * looking at don't have these attributes in them.
                     */
                    flags.calc = true;
                }

                // all the other ones, just modify that one attribute
                param.set(newVal);
            }
        }

        // swap the data attributes of the relevant x and y axes?
        if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) {
            Axes.swap(gd, traces);
        }

        // swap hovermode if set to "compare x/y data"
        if(ai === 'orientationaxes') {
            var hovermode = Lib.nestedProperty(gd.layout, 'hovermode');
            if(hovermode.get() === 'x') {
                hovermode.set('y');
            } else if(hovermode.get() === 'y') {
                hovermode.set('x');
            }
        }

        // major enough changes deserve autoscale, autobin, and
        // non-reversed axes so people don't get confused
        if(['orientation', 'type'].indexOf(ai) !== -1) {
            axlist = [];
            for(i = 0; i < traces.length; i++) {
                var trace = data[traces[i]];

                if(Registry.traceIs(trace, 'cartesian')) {
                    addToAxlist(trace.xaxis || 'x');
                    addToAxlist(trace.yaxis || 'y');

                    if(ai === 'type') {
                        doextra(['autobinx', 'autobiny'], true, i);
                    }
                }
            }

            doextra(axlist.map(autorangeAttr), true, 0);
            doextra(axlist.map(rangeAttr), [0, 1], 0);
        }
    }

    // do we need to force a recalc?
    var autorangeOn = false;
    var axList = Axes.list(gd);
    for(i = 0; i < axList.length; i++) {
        if(axList[i].autorange) {
            autorangeOn = true;
            break;
        }
    }

    // combine a few flags together;
    if(flags.calc || (flags.calcIfAutorange && autorangeOn)) {
        flags.clearCalc = true;
    }
    if(flags.calc || flags.plot || flags.calcIfAutorange) {
        flags.fullReplot = true;
    }

    return {
        flags: flags,
        undoit: undoit,
        redoit: redoit,
        traces: traces,
        eventData: Lib.extendDeepNoArrays([], [redoit, traces])
    };
}

/**
 * relayout: update layout attributes of an existing plot
 *
 * Can be called two ways:
 *
 * Signature 1:
 * @param {String | HTMLDivElement} gd
 *  the id or dom element of the graph container div
 * @param {String} astr
 *  attribute string (like `'xaxis.range[0]'`) to update
 * @param {*} val
 *  value to give this attribute
 *
 * Signature 2:
 * @param {String | HTMLDivElement} gd
 *  (as in signature 1)
 * @param {Object} aobj
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  allows setting multiple attributes simultaneously
 */
exports.relayout = function relayout(gd, astr, val) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    if(gd.framework && gd.framework.isPolar) {
        return Promise.resolve(gd);
    }

    var aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = val;
    } else if(Lib.isPlainObject(astr)) {
        aobj = Lib.extendFlat({}, astr);
    } else {
        Lib.warn('Relayout fail.', astr, val);
        return Promise.reject();
    }

    if(Object.keys(aobj).length) gd.changed = true;

    var specs = _relayout(gd, aobj);
    var flags = specs.flags;

    // clear calcdata if required
    if(flags.calc) gd.calcdata = undefined;
    if(flags.margins) helpers.clearAxisAutomargins(gd);

    // fill in redraw sequence

    // even if we don't have anything left in aobj,
    // something may have happened within relayout that we
    // need to wait for
    var seq = [Plots.previousPromises];

    if(flags.layoutReplot) {
        seq.push(subroutines.layoutReplot);
    }
    else if(Object.keys(aobj).length) {
        Plots.supplyDefaults(gd);

        if(flags.legend) seq.push(subroutines.doLegend);
        if(flags.layoutstyle) seq.push(subroutines.layoutStyles);

        if(flags.axrange) {
            // N.B. leave as sequence of subroutines (for now) instead of
            // subroutine of its own so that finalDraw always gets
            // executed after drawData
            seq.push(
                // TODO
                // no test fail when commenting out doAutoRangeAndConstraints,
                // but I think we do need this (maybe just the enforce part?)
                // Am I right?
                // More info in:
                // https://github.com/plotly/plotly.js/issues/2540
                subroutines.doAutoRangeAndConstraints,
                // TODO
                // can target specific axes,
                // do not have to redraw all axes here
                // See:
                // https://github.com/plotly/plotly.js/issues/2547
                subroutines.doTicksRelayout,
                subroutines.drawData,
                subroutines.finalDraw
            );
        }

        if(flags.ticks) seq.push(subroutines.doTicksRelayout);
        if(flags.modebar) seq.push(subroutines.doModeBar);
        if(flags.camera) seq.push(subroutines.doCamera);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        relayout, [gd, specs.undoit],
        relayout, [gd, specs.redoit]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);

    return plotDone.then(function() {
        gd.emit('plotly_relayout', specs.eventData);
        return gd;
    });
};

function _relayout(gd, aobj) {
    var layout = gd.layout,
        fullLayout = gd._fullLayout,
        keys = Object.keys(aobj),
        axes = Axes.list(gd),
        arrayEdits = {},
        arrayStr,
        i,
        j;

    // look for 'allaxes', split out into all axes
    // in case of 3D the axis are nested within a scene which is held in _id
    for(i = 0; i < keys.length; i++) {
        if(keys[i].indexOf('allaxes') === 0) {
            for(j = 0; j < axes.length; j++) {
                var scene = axes[j]._id.substr(1),
                    axisAttr = (scene.indexOf('scene') !== -1) ? (scene + '.') : '',
                    newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name);

                if(!aobj[newkey]) aobj[newkey] = aobj[keys[i]];
            }

            delete aobj[keys[i]];
        }
    }

    // initialize flags
    var flags = editTypes.layoutFlags();

    // copies of the change (and previous values of anything affected)
    // for the undo / redo queue
    var redoit = {},
        undoit = {};

    // for attrs that interact (like scales & autoscales), save the
    // old vals before making the change
    // val=undefined will not set a value, just record what the value was.
    // attr can be an array to set several at once (all to the same val)
    function doextra(attr, val) {
        if(Array.isArray(attr)) {
            attr.forEach(function(a) { doextra(a, val); });
            return;
        }

        // if we have another value for this attribute (explicitly or
        // via a parent) do not override with this auto-generated extra
        if(attr in aobj || helpers.hasParent(aobj, attr)) return;

        var p = Lib.nestedProperty(layout, attr);
        if(!(attr in undoit)) {
            undoit[attr] = undefinedToNull(p.get());
        }
        if(val !== undefined) p.set(val);
    }

    // for constraint enforcement: keep track of all axes (as {id: name})
    // we're editing the (auto)range of, so we can tell the others constrained
    // to scale with them that it's OK for them to shrink
    var rangesAltered = {};
    var axId;

    function recordAlteredAxis(pleafPlus) {
        var axId = Axes.name2id(pleafPlus.split('.')[0]);
        rangesAltered[axId] = 1;
        return axId;
    }

    // alter gd.layout
    for(var ai in aobj) {
        if(helpers.hasParent(aobj, ai)) {
            throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously');
        }

        var p = Lib.nestedProperty(layout, ai);
        var vi = aobj[ai];
        var plen = p.parts.length;
        // p.parts may end with an index integer if the property is an array
        var pend = plen - 1;
        while(pend > 0 && typeof p.parts[plen - 1] !== 'string') { pend--; }
        // last property in chain (leaf node)
        var pleaf = p.parts[pend];
        // leaf plus immediate parent
        var pleafPlus = p.parts[pend - 1] + '.' + pleaf;
        // trunk nodes (everything except the leaf)
        var ptrunk = p.parts.slice(0, pend).join('.');
        var parentIn = Lib.nestedProperty(gd.layout, ptrunk).get();
        var parentFull = Lib.nestedProperty(fullLayout, ptrunk).get();
        var vOld = p.get();

        if(vi === undefined) continue;

        redoit[ai] = vi;

        // axis reverse is special - it is its own inverse
        // op and has no flag.
        undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld);

        var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts);

        if(valObject && valObject.impliedEdits && vi !== null) {
            for(var impliedKey in valObject.impliedEdits) {
                doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]);
            }
        }

        // Setting width or height to null must reset the graph's width / height
        // back to its initial value as computed during the first pass in Plots.plotAutoSize.
        //
        // To do so, we must manually set them back here using the _initialAutoSize cache.
        if(['width', 'height'].indexOf(ai) !== -1 && vi === null) {
            fullLayout[ai] = gd._initialAutoSize[ai];
        }
        // check autorange vs range
        else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) {
            recordAlteredAxis(pleafPlus);
            Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
        }
        else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) {
            recordAlteredAxis(pleafPlus);
            Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
            var axFull = Lib.nestedProperty(fullLayout, ptrunk).get();
            if(axFull._inputDomain) {
                // if we're autoranging and this axis has a constrained domain,
                // reset it so we don't get locked into a shrunken size
                axFull._input.domain = axFull._inputDomain.slice();
            }
        }
        else if(pleafPlus.match(/^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/)) {
            Lib.nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null);
        }

        // toggling axis type between log and linear: we need to convert
        // positions for components that are still using linearized values,
        // not data values like newer components.
        // previously we did this for log <-> not-log, but now only do it
        // for log <-> linear
        if(pleaf === 'type') {
            var ax = parentIn,
                toLog = parentFull.type === 'linear' && vi === 'log',
                fromLog = parentFull.type === 'log' && vi === 'linear';

            if(toLog || fromLog) {
                if(!ax || !ax.range) {
                    // 2D never gets here, but 3D does
                    // I don't think this is needed, but left here in case there
                    // are edge cases I'm not thinking of.
                    doextra(ptrunk + '.autorange', true);
                }
                else if(!parentFull.autorange) {
                    // toggling log without autorange: need to also recalculate ranges
                    // because log axes use linearized values for range endpoints
                    var r0 = ax.range[0],
                        r1 = ax.range[1];
                    if(toLog) {
                        // if both limits are negative, autorange
                        if(r0 <= 0 && r1 <= 0) {
                            doextra(ptrunk + '.autorange', true);
                        }
                        // if one is negative, set it 6 orders below the other.
                        if(r0 <= 0) r0 = r1 / 1e6;
                        else if(r1 <= 0) r1 = r0 / 1e6;
                        // now set the range values as appropriate
                        doextra(ptrunk + '.range[0]', Math.log(r0) / Math.LN10);
                        doextra(ptrunk + '.range[1]', Math.log(r1) / Math.LN10);
                    }
                    else {
                        doextra(ptrunk + '.range[0]', Math.pow(10, r0));
                        doextra(ptrunk + '.range[1]', Math.pow(10, r1));
                    }
                }
                else if(toLog) {
                    // just make sure the range is positive and in the right
                    // order, it'll get recalculated later
                    ax.range = (ax.range[1] > ax.range[0]) ? [1, 2] : [2, 1];
                }

                // clear polar view initial stash for radial range so that
                // value get recomputed in correct units
                if(Array.isArray(fullLayout._subplots.polar) &&
                    fullLayout._subplots.polar.length &&
                    fullLayout[p.parts[0]] &&
                    p.parts[1] === 'radialaxis'
                ) {
                    delete fullLayout[p.parts[0]]._subplot.viewInitial['radialaxis.range'];
                }

                // Annotations and images also need to convert to/from linearized coords
                // Shapes do not need this :)
                Registry.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra);
                Registry.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra);
            }
            else {
                // any other type changes: the range from the previous type
                // will not make sense, so autorange it.
                doextra(ptrunk + '.autorange', true);
                doextra(ptrunk + '.range', null);
            }
            Lib.nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
        }
        else if(pleaf.match(AX_NAME_PATTERN)) {
            var fullProp = Lib.nestedProperty(fullLayout, ai).get(),
                newType = (vi || {}).type;

            // This can potentially cause strange behavior if the autotype is not
            // numeric (linear, because we don't auto-log) but the previous type
            // was log. That's a very strange edge case though
            if(!newType || newType === '-') newType = 'linear';
            Registry.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra);
            Registry.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra);
        }

        // alter gd.layout

        // collect array component edits for execution all together
        // so we can ensure consistent behavior adding/removing items
        // and order-independence for add/remove/edit all together in
        // one relayout call
        var containerArrayMatch = manageArrays.containerArrayMatch(ai);
        if(containerArrayMatch) {
            arrayStr = containerArrayMatch.array;
            i = containerArrayMatch.index;
            var propStr = containerArrayMatch.property;
            var componentArray = Lib.nestedProperty(layout, arrayStr);
            var obji = (componentArray || [])[i] || {};
            var objToAutorange = obji;

            var updateValObject = valObject || {editType: 'calc'};
            var checkForAutorange = updateValObject.editType.indexOf('calcIfAutorange') !== -1;

            if(i === '') {
                // replacing the entire array - too many possibilities, just recalc
                if(checkForAutorange) flags.calc = true;
                else editTypes.update(flags, updateValObject);
                checkForAutorange = false; // clear this, we're already doing a recalc
            }
            else if(propStr === '') {
                // special handling of undoit if we're adding or removing an element
                // ie 'annotations[2]' which can be {...} (add) or null (remove)
                objToAutorange = vi;
                if(manageArrays.isAddVal(vi)) {
                    undoit[ai] = null;
                }
                else if(manageArrays.isRemoveVal(vi)) {
                    undoit[ai] = obji;
                    objToAutorange = obji;
                }
                else Lib.warn('unrecognized full object value', aobj);
            }

            if(checkForAutorange && (refAutorange(gd, objToAutorange, 'x') || refAutorange(gd, objToAutorange, 'y'))) {
                flags.calc = true;
            }
            else {
                editTypes.update(flags, updateValObject);
            }

            // prepare the edits object we'll send to applyContainerArrayChanges
            if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {};
            var objEdits = arrayEdits[arrayStr][i];
            if(!objEdits) objEdits = arrayEdits[arrayStr][i] = {};
            objEdits[propStr] = vi;

            delete aobj[ai];
        }
        // handle axis reversal explicitly, as there's no 'reverse' attribute
        else if(pleaf === 'reverse') {
            if(parentIn.range) parentIn.range.reverse();
            else {
                doextra(ptrunk + '.autorange', true);
                parentIn.range = [1, 0];
            }

            if(parentFull.autorange) flags.calc = true;
            else flags.plot = true;
        }
        else {
            if((fullLayout._has('scatter-like') && fullLayout._has('regl')) &&
                (ai === 'dragmode' &&
                (vi === 'lasso' || vi === 'select') &&
                !(vOld === 'lasso' || vOld === 'select'))
            ) {
                flags.plot = true;
            }
            else if(valObject) editTypes.update(flags, valObject);
            else flags.calc = true;

            p.set(vi);
        }
    }

    // now we've collected component edits - execute them all together
    for(arrayStr in arrayEdits) {
        var finished = manageArrays.applyContainerArrayChanges(gd,
            Lib.nestedProperty(layout, arrayStr), arrayEdits[arrayStr], flags);
        if(!finished) flags.plot = true;
    }

    // figure out if we need to recalculate axis constraints
    var constraints = fullLayout._axisConstraintGroups || [];
    for(axId in rangesAltered) {
        for(i = 0; i < constraints.length; i++) {
            var group = constraints[i];
            if(group[axId]) {
                // Always recalc if we're changing constrained ranges.
                // Otherwise it's possible to violate the constraints by
                // specifying arbitrary ranges for all axes in the group.
                // this way some ranges may expand beyond what's specified,
                // as they do at first draw, to satisfy the constraints.
                flags.calc = true;
                for(var groupAxId in group) {
                    if(!rangesAltered[groupAxId]) {
                        Axes.getFromId(gd, groupAxId)._constraintShrinkable = true;
                    }
                }
            }
        }
    }

    // If the autosize changed or height or width was explicitly specified,
    // this triggers a redraw
    // TODO: do we really need special aobj.height/width handling here?
    // couldn't editType do this?
    if(updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true;

    if(flags.plot || flags.calc) {
        flags.layoutReplot = true;
    }

    // now all attribute mods are done, as are
    // redo and undo so we can save them

    return {
        flags: flags,
        undoit: undoit,
        redoit: redoit,
        eventData: Lib.extendDeep({}, redoit)
    };
}

/*
 * updateAutosize: we made a change, does it change the autosize result?
 * puts the new size into fullLayout
 * returns true if either height or width changed
 */
function updateAutosize(gd) {
    var fullLayout = gd._fullLayout;
    var oldWidth = fullLayout.width;
    var oldHeight = fullLayout.height;

    // calculate autosizing
    if(gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout);

    return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight);
}

// for editing annotations or shapes - is it on autoscaled axes?
function refAutorange(gd, obj, axLetter) {
    if(!Lib.isPlainObject(obj)) return false;
    var axRef = obj[axLetter + 'ref'] || axLetter,
        ax = Axes.getFromId(gd, axRef);

    if(!ax && axRef.charAt(0) === axLetter) {
        // fall back on the primary axis in case we've referenced a
        // nonexistent axis (as we do above if axRef is missing).
        // This assumes the object defaults to data referenced, which
        // is the case for shapes and annotations but not for images.
        // The only thing this is used for is to determine whether to
        // do a full `recalc`, so the only ill effect of this error is
        // to waste some time.
        ax = Axes.getFromId(gd, axLetter);
    }
    return (ax || {}).autorange;
}

/**
 * update: update trace and layout attributes of an existing plot
 *
 * @param {String | HTMLDivElement} gd
 *  the id or DOM element of the graph container div
 * @param {Object} traceUpdate
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  corresponding to updates in the plot's traces
 * @param {Object} layoutUpdate
 *  attribute object `{astr1: val1, astr2: val2 ...}`
 *  corresponding to updates in the plot's layout
 * @param {Number[] | Number} [traces]
 *  integer or array of integers for the traces to alter (all if omitted)
 *
 */
exports.update = function update(gd, traceUpdate, layoutUpdate, _traces) {
    gd = Lib.getGraphDiv(gd);
    helpers.clearPromiseQueue(gd);

    if(gd.framework && gd.framework.isPolar) {
        return Promise.resolve(gd);
    }

    if(!Lib.isPlainObject(traceUpdate)) traceUpdate = {};
    if(!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {};

    if(Object.keys(traceUpdate).length) gd.changed = true;
    if(Object.keys(layoutUpdate).length) gd.changed = true;

    var traces = helpers.coerceTraceIndices(gd, _traces);

    var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces);
    var restyleFlags = restyleSpecs.flags;

    var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate));
    var relayoutFlags = relayoutSpecs.flags;

    // clear calcdata and/or axis types if required
    if(restyleFlags.clearCalc || relayoutFlags.calc) gd.calcdata = undefined;
    if(restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate);
    if(relayoutFlags.margins) helpers.clearAxisAutomargins(gd);

    // fill in redraw sequence
    var seq = [];

    if(restyleFlags.fullReplot && relayoutFlags.layoutReplot) {
        var data = gd.data,
            layout = gd.layout;

        // clear existing data/layout on gd
        // so that Plotly.plot doesn't try to extend them
        gd.data = undefined;
        gd.layout = undefined;

        seq.push(function() { return exports.plot(gd, data, layout); });
    }
    else if(restyleFlags.fullReplot) {
        seq.push(exports.plot);
    }
    else if(relayoutFlags.layoutReplot) {
        seq.push(subroutines.layoutReplot);
    }
    else {
        seq.push(Plots.previousPromises);
        Plots.supplyDefaults(gd);

        if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
        if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
        if(relayoutFlags.legend) seq.push(subroutines.doLegend);
        if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
        if(relayoutFlags.axrange) {
            seq.push(
                subroutines.doAutoRangeAndConstraints,
                subroutines.doTicksRelayout,
                subroutines.drawData,
                subroutines.finalDraw
            );
        }
        if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
        if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
        if(relayoutFlags.camera) seq.push(subroutines.doCamera);
    }

    seq.push(Plots.rehover);

    Queue.add(gd,
        update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces],
        update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces]
    );

    var plotDone = Lib.syncOrAsync(seq, gd);
    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);

    return plotDone.then(function() {
        gd.emit('plotly_update', {
            data: restyleSpecs.eventData,
            layout: relayoutSpecs.eventData
        });

        return gd;
    });
};

/**
 * Plotly.react:
 * A plot/update method that takes the full plot state (same API as plot/newPlot)
 * and diffs to determine the minimal update pathway
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {array of objects} data
 *      array of traces, containing the data and display information for each trace
 * @param {object} layout
 *      object describing the overall display of the plot,
 *      all the stuff that doesn't pertain to any individual trace
 * @param {object} config
 *      configuration options (see ./plot_config.js for more info)
 *
 * OR
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 * @param {object} figure
 *      object containing `data`, `layout`, `config`, and `frames` members
 *
 */
exports.react = function(gd, data, layout, config) {
    var frames, plotDone;

    function addFrames() { return exports.addFrames(gd, frames); }

    gd = Lib.getGraphDiv(gd);

    var oldFullData = gd._fullData;
    var oldFullLayout = gd._fullLayout;

    // you can use this as the initial draw as well as to update
    if(!Lib.isPlotDiv(gd) || !oldFullData || !oldFullLayout) {
        plotDone = exports.newPlot(gd, data, layout, config);
    }
    else {

        if(Lib.isPlainObject(data)) {
            var obj = data;
            data = obj.data;
            layout = obj.layout;
            config = obj.config;
            frames = obj.frames;
        }

        var configChanged = false;
        // assume that if there's a config at all, we're reacting to it too,
        // and completely replace the previous config
        if(config) {
            var oldConfig = Lib.extendDeep({}, gd._context);
            gd._context = undefined;
            setPlotContext(gd, config);
            configChanged = diffConfig(oldConfig, gd._context);
        }

        gd.data = data || [];
        helpers.cleanData(gd.data, []);
        gd.layout = layout || {};
        helpers.cleanLayout(gd.layout);

        // "true" skips updating calcdata and remapping arrays from calcTransforms,
        // which supplyDefaults usually does at the end, but we may need to NOT do
        // if the diff (which we haven't determined yet) says we'll recalc
        Plots.supplyDefaults(gd, {skipUpdateCalc: true});

        var newFullData = gd._fullData;
        var newFullLayout = gd._fullLayout;
        var immutable = newFullLayout.datarevision === undefined;

        var restyleFlags = diffData(gd, oldFullData, newFullData, immutable);
        var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable);

        // TODO: how to translate this part of relayout to Plotly.react?
        // // Setting width or height to null must reset the graph's width / height
        // // back to its initial value as computed during the first pass in Plots.plotAutoSize.
        // //
        // // To do so, we must manually set them back here using the _initialAutoSize cache.
        // if(['width', 'height'].indexOf(ai) !== -1 && vi === null) {
        //     fullLayout[ai] = gd._initialAutoSize[ai];
        // }

        if(updateAutosize(gd)) relayoutFlags.layoutReplot = true;

        // clear calcdata if required
        if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
        // otherwise do the calcdata updates and calcTransform array remaps that we skipped earlier
        else Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);

        if(relayoutFlags.margins) helpers.clearAxisAutomargins(gd);

        // Note: what restyle/relayout use impliedEdits and clearAxisTypes for
        // must be handled by the user when using Plotly.react.

        // fill in redraw sequence
        var seq = [];

        if(frames) {
            gd._transitionData = {};
            Plots.createTransitionData(gd);
            seq.push(addFrames);
        }

        if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) {
            gd._fullLayout._skipDefaults = true;
            seq.push(exports.plot);
        }
        else {
            for(var componentType in relayoutFlags.arrays) {
                var indices = relayoutFlags.arrays[componentType];
                if(indices.length) {
                    var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
                    if(drawOne !== Lib.noop) {
                        for(var i = 0; i < indices.length; i++) {
                            drawOne(gd, indices[i]);
                        }
                    }
                    else {
                        var draw = Registry.getComponentMethod(componentType, 'draw');
                        if(draw === Lib.noop) {
                            throw new Error('cannot draw components: ' + componentType);
                        }
                        draw(gd);
                    }
                }
            }

            seq.push(Plots.previousPromises);
            if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
            if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
            if(relayoutFlags.legend) seq.push(subroutines.doLegend);
            if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
            if(relayoutFlags.axrange) {
                seq.push(
                    subroutines.doAutoRangeAndConstraints,
                    subroutines.doTicksRelayout,
                    subroutines.drawData,
                    subroutines.finalDraw
                );
            }
            if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
            if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
            if(relayoutFlags.camera) seq.push(subroutines.doCamera);
        }

        seq.push(Plots.rehover);

        plotDone = Lib.syncOrAsync(seq, gd);
        if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
    }

    return plotDone.then(function() {
        gd.emit('plotly_react', {
            data: data,
            layout: layout
        });

        return gd;
    });

};

function diffData(gd, oldFullData, newFullData, immutable) {
    if(oldFullData.length !== newFullData.length) {
        return {
            fullReplot: true,
            calc: true
        };
    }

    var flags = editTypes.traceFlags();
    flags.arrays = {};
    var i, trace;

    function getTraceValObject(parts) {
        return PlotSchema.getTraceValObject(trace, parts);
    }

    var diffOpts = {
        getValObject: getTraceValObject,
        flags: flags,
        immutable: immutable,
        gd: gd
    };


    var seenUIDs = {};

    for(i = 0; i < oldFullData.length; i++) {
        trace = newFullData[i]._fullInput;
        if(seenUIDs[trace.uid]) continue;
        seenUIDs[trace.uid] = 1;

        diffOpts.autoranged = trace.xaxis ? (
            Axes.getFromId(gd, trace.xaxis).autorange ||
            Axes.getFromId(gd, trace.yaxis).autorange
        ) : false;
        getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts);
    }

    if(flags.calc || flags.plot || flags.calcIfAutorange) {
        flags.fullReplot = true;
    }

    return flags;
}

function diffLayout(gd, oldFullLayout, newFullLayout, immutable) {
    var flags = editTypes.layoutFlags();
    flags.arrays = {};

    function getLayoutValObject(parts) {
        return PlotSchema.getLayoutValObject(newFullLayout, parts);
    }

    var diffOpts = {
        getValObject: getLayoutValObject,
        flags: flags,
        immutable: immutable,
        gd: gd
    };

    getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts);

    if(flags.plot || flags.calc) {
        flags.layoutReplot = true;
    }

    return flags;
}

function getDiffFlags(oldContainer, newContainer, outerparts, opts) {
    var valObject, key;

    var getValObject = opts.getValObject;
    var flags = opts.flags;
    var immutable = opts.immutable;
    var inArray = opts.inArray;
    var arrayIndex = opts.arrayIndex;
    var gd = opts.gd;
    var autoranged = opts.autoranged;

    function changed() {
        var editType = valObject.editType;
        if(editType.indexOf('calcIfAutorange') !== -1 && (autoranged || (autoranged === undefined && (
            refAutorange(gd, newContainer, 'x') || refAutorange(gd, newContainer, 'y')
        )))) {
            flags.calc = true;
            return;
        }
        if(inArray && editType.indexOf('arraydraw') !== -1) {
            Lib.pushUnique(flags.arrays[inArray], arrayIndex);
            return;
        }
        editTypes.update(flags, valObject);
    }

    function valObjectCanBeDataArray(valObject) {
        return valObject.valType === 'data_array' || valObject.arrayOk;
    }

    for(key in oldContainer) {
        // short-circuit based on previous calls or previous keys that already maximized the pathway
        if(flags.calc) return;

        var oldVal = oldContainer[key];
        var newVal = newContainer[key];

        if(key.charAt(0) === '_' || typeof oldVal === 'function' || oldVal === newVal) continue;

        // FIXME: ax.tick0 and dtick get filled in during plotting, and unlike other auto values
        // they don't make it back into the input, so newContainer won't have them.
        // similar for axis ranges for 3D
        // contourcarpet doesn't HAVE zmin/zmax, they're just auto-added. It needs them.
        if(key === 'tick0' || key === 'dtick') {
            var tickMode = newContainer.tickmode;
            if(tickMode === 'auto' || tickMode === 'array' || !tickMode) continue;
        }
        if(key === 'range' && newContainer.autorange) continue;
        if((key === 'zmin' || key === 'zmax') && newContainer.type === 'contourcarpet') continue;

        var parts = outerparts.concat(key);
        valObject = getValObject(parts);

        // in case type changed, we may not even *have* a valObject.
        if(!valObject) continue;

        if(valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;

        var valType = valObject.valType;
        var i;

        var canBeDataArray = valObjectCanBeDataArray(valObject);
        var wasArray = Array.isArray(oldVal);
        var nowArray = Array.isArray(newVal);

        // hack for traces that modify the data in supplyDefaults, like
        // converting 1D to 2D arrays, which will always create new objects
        if(wasArray && nowArray) {
            var inputKey = '_input_' + key;
            var oldValIn = oldContainer[inputKey];
            var newValIn = newContainer[inputKey];
            if(Array.isArray(oldValIn) && oldValIn === newValIn) continue;
        }

        if(newVal === undefined) {
            if(canBeDataArray && wasArray) flags.calc = true;
            else changed();
        }
        else if(valObject._isLinkedToArray) {
            var arrayEditIndices = [];
            var extraIndices = false;
            if(!inArray) flags.arrays[key] = arrayEditIndices;

            var minLen = Math.min(oldVal.length, newVal.length);
            var maxLen = Math.max(oldVal.length, newVal.length);
            if(minLen !== maxLen) {
                if(valObject.editType === 'arraydraw') {
                    extraIndices = true;
                }
                else {
                    changed();
                    continue;
                }
            }

            for(i = 0; i < minLen; i++) {
                getDiffFlags(oldVal[i], newVal[i], parts.concat(i),
                    // add array indices, but not if we're already in an array
                    Lib.extendFlat({inArray: key, arrayIndex: i}, opts));
            }

            // put this at the end so that we know our collected array indices are sorted
            // but the check for length changes happens up front so we can short-circuit
            // diffing if appropriate
            if(extraIndices) {
                for(i = minLen; i < maxLen; i++) {
                    arrayEditIndices.push(i);
                }
            }
        }
        else if(!valType && Lib.isPlainObject(oldVal)) {
            getDiffFlags(oldVal, newVal, parts, opts);
        }
        else if(canBeDataArray) {
            if(wasArray && nowArray) {

                // don't try to diff two data arrays. If immutable we know the data changed,
                // if not, assume it didn't and let `layout.datarevision` tell us if it did
                if(immutable) {
                    flags.calc = true;
                }
            }
            else if(wasArray !== nowArray) {
                flags.calc = true;
            }
            else changed();
        }
        else if(wasArray && nowArray) {
            // info array, colorscale, 'any' - these are short, just stringify.
            // I don't *think* that covers up any real differences post-validation, does it?
            // otherwise we need to dive in 1 (info_array) or 2 (colorscale) levels and compare
            // all elements.
            if(oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) {
                changed();
            }
        }
        else {
            changed();
        }
    }

    for(key in newContainer) {
        if(!(key in oldContainer || key.charAt(0) === '_' || typeof newContainer[key] === 'function')) {
            valObject = getValObject(outerparts.concat(key));

            if(valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) {
                flags.calc = true;
                return;
            }
            else changed();
        }
    }
}

/*
 * simple diff for config - for now, just treat all changes as equivalent
 */
function diffConfig(oldConfig, newConfig) {
    var key;

    for(key in oldConfig) {
        var oldVal = oldConfig[key];
        var newVal = newConfig[key];
        if(oldVal !== newVal) {
            if(Lib.isPlainObject(oldVal) && Lib.isPlainObject(newVal)) {
                if(diffConfig(oldVal, newVal)) {
                    return true;
                }
            }
            else if(Array.isArray(oldVal) && Array.isArray(newVal)) {
                if(oldVal.length !== newVal.length) {
                    return true;
                }
                for(var i = 0; i < oldVal.length; i++) {
                    if(oldVal[i] !== newVal[i]) {
                        if(Lib.isPlainObject(oldVal[i]) && Lib.isPlainObject(newVal[i])) {
                            if(diffConfig(oldVal[i], newVal[i])) {
                                return true;
                            }
                        }
                        else {
                            return true;
                        }
                    }
                }
            }
            else {
                return true;
            }
        }
    }
}

/**
 * Animate to a frame, sequence of frame, frame group, or frame definition
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {string or object or array of strings or array of objects} frameOrGroupNameOrFrameList
 *      a single frame, array of frames, or group to which to animate. The intent is
 *      inferred by the type of the input. Valid inputs are:
 *
 *      - string, e.g. 'groupname': animate all frames of a given `group` in the order
 *            in which they are defined via `Plotly.addFrames`.
 *
 *      - array of strings, e.g. ['frame1', frame2']: a list of frames by name to which
 *            to animate in sequence
 *
 *      - object: {data: ...}: a frame definition to which to animate. The frame is not
 *            and does not need to be added via `Plotly.addFrames`. It may contain any of
 *            the properties of a frame, including `data`, `layout`, and `traces`. The
 *            frame is used as provided and does not use the `baseframe` property.
 *
 *      - array of objects, e.g. [{data: ...}, {data: ...}]: a list of frame objects,
 *            each following the same rules as a single `object`.
 *
 * @param {object} animationOpts
 *      configuration for the animation
 */
exports.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error(
            'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
            'to create a plot before animating it. For more details, see ' +
            'https://plot.ly/javascript/animations/'
        );
    }

    var trans = gd._transitionData;

    // This is the queue of frames that will be animated as soon as possible. They
    // are popped immediately upon the *start* of a transition:
    if(!trans._frameQueue) {
        trans._frameQueue = [];
    }

    animationOpts = Plots.supplyAnimationDefaults(animationOpts);
    var transitionOpts = animationOpts.transition;
    var frameOpts = animationOpts.frame;

    // Since frames are popped immediately, an empty queue only means all frames have
    // *started* to transition, not that the animation is complete. To solve that,
    // track a separate counter that increments at the same time as frames are added
    // to the queue, but decrements only when the transition is complete.
    if(trans._frameWaitingCnt === undefined) {
        trans._frameWaitingCnt = 0;
    }

    function getTransitionOpts(i) {
        if(Array.isArray(transitionOpts)) {
            if(i >= transitionOpts.length) {
                return transitionOpts[0];
            } else {
                return transitionOpts[i];
            }
        } else {
            return transitionOpts;
        }
    }

    function getFrameOpts(i) {
        if(Array.isArray(frameOpts)) {
            if(i >= frameOpts.length) {
                return frameOpts[0];
            } else {
                return frameOpts[i];
            }
        } else {
            return frameOpts;
        }
    }

    // Execute a callback after the wrapper function has been called n times.
    // This is used to defer the resolution until a transition has resovled *and*
    // the frame has completed. If it's not done this way, then we get a race
    // condition in which the animation might resolve before a transition is complete
    // or vice versa.
    function callbackOnNthTime(cb, n) {
        var cnt = 0;
        return function() {
            if(cb && ++cnt === n) {
                return cb();
            }
        };
    }

    return new Promise(function(resolve, reject) {
        function discardExistingFrames() {
            if(trans._frameQueue.length === 0) {
                return;
            }

            while(trans._frameQueue.length) {
                var next = trans._frameQueue.pop();
                if(next.onInterrupt) {
                    next.onInterrupt();
                }
            }

            gd.emit('plotly_animationinterrupted', []);
        }

        function queueFrames(frameList) {
            if(frameList.length === 0) return;

            for(var i = 0; i < frameList.length; i++) {
                var computedFrame;

                if(frameList[i].type === 'byname') {
                    // If it's a named frame, compute it:
                    computedFrame = Plots.computeFrame(gd, frameList[i].name);
                } else {
                    // Otherwise we must have been given a simple object, so treat
                    // the input itself as the computed frame.
                    computedFrame = frameList[i].data;
                }

                var frameOpts = getFrameOpts(i);
                var transitionOpts = getTransitionOpts(i);

                // It doesn't make much sense for the transition duration to be greater than
                // the frame duration, so limit it:
                transitionOpts.duration = Math.min(transitionOpts.duration, frameOpts.duration);

                var nextFrame = {
                    frame: computedFrame,
                    name: frameList[i].name,
                    frameOpts: frameOpts,
                    transitionOpts: transitionOpts,
                };
                if(i === frameList.length - 1) {
                    // The last frame in this .animate call stores the promise resolve
                    // and reject callbacks. This is how we ensure that the animation
                    // loop (which may exist as a result of a *different* .animate call)
                    // still resolves or rejecdts this .animate call's promise. once it's
                    // complete.
                    nextFrame.onComplete = callbackOnNthTime(resolve, 2);
                    nextFrame.onInterrupt = reject;
                }

                trans._frameQueue.push(nextFrame);
            }

            // Set it as never having transitioned to a frame. This will cause the animation
            // loop to immediately transition to the next frame (which, for immediate mode,
            // is the first frame in the list since all others would have been discarded
            // below)
            if(animationOpts.mode === 'immediate') {
                trans._lastFrameAt = -Infinity;
            }

            // Only it's not already running, start a RAF loop. This could be avoided in the
            // case that there's only one frame, but it significantly complicated the logic
            // and only sped things up by about 5% or so for a lorenz attractor simulation.
            // It would be a fine thing to implement, but the benefit of that optimization
            // doesn't seem worth the extra complexity.
            if(!trans._animationRaf) {
                beginAnimationLoop();
            }
        }

        function stopAnimationLoop() {
            gd.emit('plotly_animated');

            // Be sure to unset also since it's how we know whether a loop is already running:
            window.cancelAnimationFrame(trans._animationRaf);
            trans._animationRaf = null;
        }

        function nextFrame() {
            if(trans._currentFrame && trans._currentFrame.onComplete) {
                // Execute the callback and unset it to ensure it doesn't
                // accidentally get called twice
                trans._currentFrame.onComplete();
            }

            var newFrame = trans._currentFrame = trans._frameQueue.shift();

            if(newFrame) {
                // Since it's sometimes necessary to do deep digging into frame data,
                // we'll consider it not 100% impossible for nulls or numbers to sneak through,
                // so check when casting the name, just to be absolutely certain:
                var stringName = newFrame.name ? newFrame.name.toString() : null;
                gd._fullLayout._currentFrame = stringName;

                trans._lastFrameAt = Date.now();
                trans._timeToNext = newFrame.frameOpts.duration;

                // This is simply called and it's left to .transition to decide how to manage
                // interrupting current transitions. That means we don't need to worry about
                // how it resolves or what happens after this:
                Plots.transition(gd,
                    newFrame.frame.data,
                    newFrame.frame.layout,
                    helpers.coerceTraceIndices(gd, newFrame.frame.traces),
                    newFrame.frameOpts,
                    newFrame.transitionOpts
                ).then(function() {
                    if(newFrame.onComplete) {
                        newFrame.onComplete();
                    }

                });

                gd.emit('plotly_animatingframe', {
                    name: stringName,
                    frame: newFrame.frame,
                    animation: {
                        frame: newFrame.frameOpts,
                        transition: newFrame.transitionOpts,
                    }
                });
            } else {
                // If there are no more frames, then stop the RAF loop:
                stopAnimationLoop();
            }
        }

        function beginAnimationLoop() {
            gd.emit('plotly_animating');

            // If no timer is running, then set last frame = long ago so that the next
            // frame is immediately transitioned:
            trans._lastFrameAt = -Infinity;
            trans._timeToNext = 0;
            trans._runningTransitions = 0;
            trans._currentFrame = null;

            var doFrame = function() {
                // This *must* be requested before nextFrame since nextFrame may decide
                // to cancel it if there's nothing more to animated:
                trans._animationRaf = window.requestAnimationFrame(doFrame);

                // Check if we're ready for a new frame:
                if(Date.now() - trans._lastFrameAt > trans._timeToNext) {
                    nextFrame();
                }
            };

            doFrame();
        }

        // This is an animate-local counter that helps match up option input list
        // items with the particular frame.
        var configCounter = 0;
        function setTransitionConfig(frame) {
            if(Array.isArray(transitionOpts)) {
                if(configCounter >= transitionOpts.length) {
                    frame.transitionOpts = transitionOpts[configCounter];
                } else {
                    frame.transitionOpts = transitionOpts[0];
                }
            } else {
                frame.transitionOpts = transitionOpts;
            }
            configCounter++;
            return frame;
        }

        // Disambiguate what's sort of frames have been received
        var i, frame;
        var frameList = [];
        var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null;
        var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList);
        var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList);

        if(isSingleFrame) {
            // In this case, a simple object has been passed to animate.
            frameList.push({
                type: 'object',
                data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList))
            });
        } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) {
            // In this case, null or undefined has been passed so that we want to
            // animate *all* currently defined frames
            for(i = 0; i < trans._frames.length; i++) {
                frame = trans._frames[i];

                if(!frame) continue;

                if(allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) {
                    frameList.push({
                        type: 'byname',
                        name: String(frame.name),
                        data: setTransitionConfig({name: frame.name})
                    });
                }
            }
        } else if(isFrameArray) {
            for(i = 0; i < frameOrGroupNameOrFrameList.length; i++) {
                var frameOrName = frameOrGroupNameOrFrameList[i];
                if(['number', 'string'].indexOf(typeof frameOrName) !== -1) {
                    frameOrName = String(frameOrName);
                    // In this case, there's an array and this frame is a string name:
                    frameList.push({
                        type: 'byname',
                        name: frameOrName,
                        data: setTransitionConfig({name: frameOrName})
                    });
                } else if(Lib.isPlainObject(frameOrName)) {
                    frameList.push({
                        type: 'object',
                        data: setTransitionConfig(Lib.extendFlat({}, frameOrName))
                    });
                }
            }
        }

        // Verify that all of these frames actually exist; return and reject if not:
        for(i = 0; i < frameList.length; i++) {
            frame = frameList[i];
            if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) {
                Lib.warn('animate failure: frame not found: "' + frame.data.name + '"');
                reject();
                return;
            }
        }

        // If the mode is either next or immediate, then all currently queued frames must
        // be dumped and the corresponding .animate promises rejected.
        if(['next', 'immediate'].indexOf(animationOpts.mode) !== -1) {
            discardExistingFrames();
        }

        if(animationOpts.direction === 'reverse') {
            frameList.reverse();
        }

        var currentFrame = gd._fullLayout._currentFrame;
        if(currentFrame && animationOpts.fromcurrent) {
            var idx = -1;
            for(i = 0; i < frameList.length; i++) {
                frame = frameList[i];
                if(frame.type === 'byname' && frame.name === currentFrame) {
                    idx = i;
                    break;
                }
            }

            if(idx > 0 && idx < frameList.length - 1) {
                var filteredFrameList = [];
                for(i = 0; i < frameList.length; i++) {
                    frame = frameList[i];
                    if(frameList[i].type !== 'byname' || i > idx) {
                        filteredFrameList.push(frame);
                    }
                }
                frameList = filteredFrameList;
            }
        }

        if(frameList.length > 0) {
            queueFrames(frameList);
        } else {
            // This is the case where there were simply no frames. It's a little strange
            // since there's not much to do:
            gd.emit('plotly_animated');
            resolve();
        }
    });
};

/**
 * Register new frames
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {array of objects} frameList
 *      list of frame definitions, in which each object includes any of:
 *      - name: {string} name of frame to add
 *      - data: {array of objects} trace data
 *      - layout {object} layout definition
 *      - traces {array} trace indices
 *      - baseframe {string} name of frame from which this frame gets defaults
 *
 *  @param {array of integers} indices
 *      an array of integer indices matching the respective frames in `frameList`. If not
 *      provided, an index will be provided in serial order. If already used, the frame
 *      will be overwritten.
 */
exports.addFrames = function(gd, frameList, indices) {
    gd = Lib.getGraphDiv(gd);

    if(frameList === null || frameList === undefined) {
        return Promise.resolve();
    }

    if(!Lib.isPlotDiv(gd)) {
        throw new Error(
            'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
            'to create a plot before adding frames. For more details, see ' +
            'https://plot.ly/javascript/animations/'
        );
    }

    var i, frame, j, idx;
    var _frames = gd._transitionData._frames;
    var _frameHash = gd._transitionData._frameHash;


    if(!Array.isArray(frameList)) {
        throw new Error('addFrames failure: frameList must be an Array of frame definitions' + frameList);
    }

    // Create a sorted list of insertions since we run into lots of problems if these
    // aren't in ascending order of index:
    //
    // Strictly for sorting. Make sure this is guaranteed to never collide with any
    // already-exisisting indices:
    var bigIndex = _frames.length + frameList.length * 2;

    var insertions = [];
    var _frameHashLocal = {};
    for(i = frameList.length - 1; i >= 0; i--) {
        if(!Lib.isPlainObject(frameList[i])) continue;

        // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and
        // use a Map instead of an Object instance, as Map keys aren't converted to strings.
        var lookupName = frameList[i].name;
        var name = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name;
        var newName = frameList[i].name;
        var collisionPresent = _frameHash[name] || _frameHashLocal[name];

        if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) {
            numericNameWarningCount++;

            Lib.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name +
                '" with a frame whose name of type "number" also equates to "' +
                name + '". This is valid but may potentially lead to unexpected ' +
                'behavior since all plotly.js frame names are stored internally ' +
                'as strings.');

            if(numericNameWarningCount === numericNameWarningCountLimit) {
                Lib.warn('addFrames: This API call has yielded too many of these warnings. ' +
                    'For the rest of this call, further warnings about numeric frame ' +
                    'names will be suppressed.');
            }
        }

        _frameHashLocal[lookupName] = {name: lookupName};

        insertions.push({
            frame: Plots.supplyFrameDefaults(frameList[i]),
            index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i
        });
    }

    // Sort this, taking note that undefined insertions end up at the end:
    insertions.sort(function(a, b) {
        if(a.index > b.index) return -1;
        if(a.index < b.index) return 1;
        return 0;
    });

    var ops = [];
    var revops = [];
    var frameCount = _frames.length;

    for(i = insertions.length - 1; i >= 0; i--) {
        frame = insertions[i].frame;

        if(typeof frame.name === 'number') {
            Lib.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' +
                'implicitly cast to strings');

        }

        if(!frame.name) {
            // Repeatedly assign a default name, incrementing the counter each time until
            // we get a name that's not in the hashed lookup table:
            while(_frameHash[(frame.name = 'frame ' + gd._transitionData._counter++)]);
        }

        if(_frameHash[frame.name]) {
            // If frame is present, overwrite its definition:
            for(j = 0; j < _frames.length; j++) {
                if((_frames[j] || {}).name === frame.name) break;
            }
            ops.push({type: 'replace', index: j, value: frame});
            revops.unshift({type: 'replace', index: j, value: _frames[j]});
        } else {
            // Otherwise insert it at the end of the list:
            idx = Math.max(0, Math.min(insertions[i].index, frameCount));

            ops.push({type: 'insert', index: idx, value: frame});
            revops.unshift({type: 'delete', index: idx});
            frameCount++;
        }
    }

    var undoFunc = Plots.modifyFrames,
        redoFunc = Plots.modifyFrames,
        undoArgs = [gd, revops],
        redoArgs = [gd, ops];

    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return Plots.modifyFrames(gd, ops);
};

/**
 * Delete frame
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 *
 * @param {array of integers} frameList
 *      list of integer indices of frames to be deleted
 */
exports.deleteFrames = function(gd, frameList) {
    gd = Lib.getGraphDiv(gd);

    if(!Lib.isPlotDiv(gd)) {
        throw new Error('This element is not a Plotly plot: ' + gd);
    }

    var i, idx;
    var _frames = gd._transitionData._frames;
    var ops = [];
    var revops = [];

    if(!frameList) {
        frameList = [];
        for(i = 0; i < _frames.length; i++) {
            frameList.push(i);
        }
    }

    frameList = frameList.slice(0);
    frameList.sort();

    for(i = frameList.length - 1; i >= 0; i--) {
        idx = frameList[i];
        ops.push({type: 'delete', index: idx});
        revops.unshift({type: 'insert', index: idx, value: _frames[idx]});
    }

    var undoFunc = Plots.modifyFrames,
        redoFunc = Plots.modifyFrames,
        undoArgs = [gd, revops],
        redoArgs = [gd, ops];

    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);

    return Plots.modifyFrames(gd, ops);
};

/**
 * Purge a graph container div back to its initial pre-Plotly.plot state
 *
 * @param {string id or DOM element} gd
 *      the id or DOM element of the graph container div
 */
exports.purge = function purge(gd) {
    gd = Lib.getGraphDiv(gd);

    var fullLayout = gd._fullLayout || {};
    var fullData = gd._fullData || [];
    var calcdata = gd.calcdata || [];

    // remove gl contexts
    Plots.cleanPlot([], {}, fullData, fullLayout, calcdata);

    // purge properties
    Plots.purge(gd);

    // purge event emitter methods
    Events.purge(gd);

    // remove plot container
    if(fullLayout._container) fullLayout._container.remove();

    // in contrast to Plotly.Plots.purge which does NOT clear _context!
    delete gd._context;

    return gd;
};

// -------------------------------------------------------
// makePlotFramework: Create the plot container and axes
// -------------------------------------------------------
function makePlotFramework(gd) {
    var gd3 = d3.select(gd);
    var fullLayout = gd._fullLayout;

    // Plot container
    fullLayout._container = gd3.selectAll('.plot-container').data([0]);
    fullLayout._container.enter().insert('div', ':first-child')
        .classed('plot-container', true)
        .classed('plotly', true);

    // Make the svg container
    fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]);
    fullLayout._paperdiv.enter().append('div')
        .classed('svg-container', true)
        .style('position', 'relative');

    // Make the graph containers
    // start fresh each time we get here, so we know the order comes out
    // right, rather than enter/exit which can muck up the order
    // TODO: sort out all the ordering so we don't have to
    // explicitly delete anything
    // FIXME: parcoords reuses this object, not the best pattern
    fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container')
        .data([{}]);

    fullLayout._glcontainer.enter().append('div')
        .classed('gl-container', true);

    // That is initialized in drawFramework if there are `gl` traces
    fullLayout._glcanvas = null;

    fullLayout._paperdiv.selectAll('.main-svg').remove();

    fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child')
        .classed('main-svg', true);

    fullLayout._toppaper = fullLayout._paperdiv.append('svg')
        .classed('main-svg', true);

    if(!fullLayout._uid) {
        var otherUids = [];
        d3.selectAll('defs').each(function() {
            if(this.id) otherUids.push(this.id.split('-')[1]);
        });
        fullLayout._uid = Lib.randstr(otherUids);
    }

    fullLayout._paperdiv.selectAll('.main-svg')
        .attr(xmlnsNamespaces.svgAttrs);

    fullLayout._defs = fullLayout._paper.append('defs')
        .attr('id', 'defs-' + fullLayout._uid);

    fullLayout._clips = fullLayout._defs.append('g')
        .classed('clips', true);

    fullLayout._topdefs = fullLayout._toppaper.append('defs')
        .attr('id', 'topdefs-' + fullLayout._uid);

    fullLayout._topclips = fullLayout._topdefs.append('g')
        .classed('clips', true);

    fullLayout._bgLayer = fullLayout._paper.append('g')
        .classed('bglayer', true);

    fullLayout._draggers = fullLayout._paper.append('g')
        .classed('draglayer', true);

    // lower shape/image layer - note that this is behind
    // all subplots data/grids but above the backgrounds
    // except inset subplots, whose backgrounds are drawn
    // inside their own group so that they appear above
    // the data for the main subplot
    // lower shapes and images which are fully referenced to
    // a subplot still get drawn within the subplot's group
    // so they will work correctly on insets
    var layerBelow = fullLayout._paper.append('g')
        .classed('layer-below', true);
    fullLayout._imageLowerLayer = layerBelow.append('g')
        .classed('imagelayer', true);
    fullLayout._shapeLowerLayer = layerBelow.append('g')
        .classed('shapelayer', true);

    // single cartesian layer for the whole plot
    fullLayout._cartesianlayer = fullLayout._paper.append('g').classed('cartesianlayer', true);

    // single polar layer for the whole plot
    fullLayout._polarlayer = fullLayout._paper.append('g').classed('polarlayer', true);

    // single ternary layer for the whole plot
    fullLayout._ternarylayer = fullLayout._paper.append('g').classed('ternarylayer', true);

    // single geo layer for the whole plot
    fullLayout._geolayer = fullLayout._paper.append('g').classed('geolayer', true);

    // single pie layer for the whole plot
    fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true);

    // fill in image server scrape-svg
    fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true);

    // lastly upper shapes, info (legend, annotations) and hover layers go on top
    // these are in a different svg element normally, but get collapsed into a single
    // svg when exporting (after inserting 3D)
    // upper shapes/images are only those drawn above the whole plot, including subplots
    var layerAbove = fullLayout._toppaper.append('g')
        .classed('layer-above', true);
    fullLayout._imageUpperLayer = layerAbove.append('g')
        .classed('imagelayer', true);
    fullLayout._shapeUpperLayer = layerAbove.append('g')
        .classed('shapelayer', true);

    fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true);
    fullLayout._menulayer = fullLayout._toppaper.append('g').classed('menulayer', true);
    fullLayout._zoomlayer = fullLayout._toppaper.append('g').classed('zoomlayer', true);
    fullLayout._hoverlayer = fullLayout._toppaper.append('g').classed('hoverlayer', true);

    gd.emit('plotly_framework');
}

},{"../components/color":43,"../components/drawing":68,"../constants/xmlns_namespaces":147,"../lib":164,"../lib/events":156,"../lib/queue":178,"../lib/svg_text_utils":185,"../plots/cartesian/axes":206,"../plots/cartesian/constants":211,"../plots/cartesian/graph_interact":215,"../plots/plots":245,"../plots/polar/legacy":248,"../registry":254,"./edit_types":191,"./helpers":192,"./manage_arrays":194,"./plot_config":196,"./plot_schema":197,"./subroutines":198,"d3":6,"fast-isnumeric":9,"has-hover":11}],196:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/**
 * This will be transferred over to gd and overridden by
 * config args to Plotly.plot.
 *
 * The defaults are the appropriate settings for plotly.js,
 * so we get the right experience without any config argument.
 */

module.exports = {

    // no interactivity, for export or image generation
    staticPlot: false,

    /*
     * we can edit titles, move annotations, etc - sets all pieces of `edits`
     * unless a separate `edits` config item overrides individual parts
     */
    editable: false,
    edits: {
        /*
         * annotationPosition: the main anchor of the annotation, which is the
         * text (if no arrow) or the arrow (which drags the whole thing leaving
         * the arrow length & direction unchanged)
         */
        annotationPosition: false,
        // just for annotations with arrows, change the length  and direction of the arrow
        annotationTail: false,
        annotationText: false,
        axisTitleText: false,
        colorbarPosition: false,
        colorbarTitleText: false,
        legendPosition: false,
        // edit the trace name fields from the legend
        legendText: false,
        shapePosition: false,
        // the global `layout.title`
        titleText: false
    },

    /*
     * DO autosize once regardless of layout.autosize
     * (use default width or height values otherwise)
     */
    autosizable: false,

    // set the length of the undo/redo queue
    queueLength: 0,

    // if we DO autosize, do we fill the container or the screen?
    fillFrame: false,

    // if we DO autosize, set the frame margins in percents of plot size
    frameMargins: 0,

    // mousewheel or two-finger scroll zooms the plot
    scrollZoom: false,

    // double click interaction (false, 'reset', 'autosize' or 'reset+autosize')
    doubleClick: 'reset+autosize',

    // new users see some hints about interactivity
    showTips: true,

    // enable axis pan/zoom drag handles
    showAxisDragHandles: true,

    /*
     * enable direct range entry at the pan/zoom drag points
     * (drag handles must be enabled above)
     */
    showAxisRangeEntryBoxes: true,

    // link to open this plot in plotly
    showLink: false,

    // if we show a link, does it contain data or just link to a plotly file?
    sendData: true,

    // text appearing in the sendData link
    linkText: 'Edit chart',

    // false or function adding source(s) to linkText <text>
    showSources: false,

    // display the mode bar (true, false, or 'hover')
    displayModeBar: 'hover',

    /*
     * remove mode bar button by name
     * (see ./components/modebar/buttons.js for the list of names)
     */
    modeBarButtonsToRemove: [],

    /*
     * add mode bar button using config objects
     * (see ./components/modebar/buttons.js for list of arguments)
     */
    modeBarButtonsToAdd: [],

    /*
     * fully custom mode bar buttons as nested array,
     * where the outer arrays represents button groups, and
     * the inner arrays have buttons config objects or names of default buttons
     * (see ./components/modebar/buttons.js for more info)
     */
    modeBarButtons: false,

    // add the plotly logo on the end of the mode bar
    displaylogo: true,

    // increase the pixel ratio for Gl plot images
    plotGlPixelRatio: 2,

    /*
     * background setting function
     * 'transparent' sets the background `layout.paper_color`
     * 'opaque' blends bg color with white ensuring an opaque background
     * or any other custom function of gd
     */
    setBackground: 'transparent',

    // URL to topojson files used in geo charts
    topojsonURL: 'https://cdn.plot.ly/',

    /*
     * Mapbox access token (required to plot mapbox trace types)
     * If using an Mapbox Atlas server, set this option to '',
     * so that plotly.js won't attempt to authenticate to the public Mapbox server.
     */
    mapboxAccessToken: null,

    /*
     * Turn all console logging on or off (errors will be thrown)
     * This should ONLY be set via Plotly.setPlotConfig
     * 0: no logs
     * 1: warnings and errors, but not informational messages
     * 2: verbose logs
     */
    logging: 1,

    /*
     * Set global transform to be applied to all traces with no
     * specification needed
     */
    globalTransforms: [],

    /*
     * Which localization should we use?
     * Should be a string like 'en' or 'en-US'.
     */
    locale: 'en-US',

    /*
     * Localization definitions
     * Locales can be provided either here (specific to one chart) or globally
     * by registering them as modules.
     * Should be an object of objects {locale: {dictionary: {...}, format: {...}}}
     * {
     *     da: {
     *         dictionary: {'Reset axes': 'Nulstil aksler', ...},
     *         format: {months: [...], shortMonths: [...]}
     *     },
     *     ...
     * }
     * All parts are optional. When looking for translation or format fields, we
     * look first for an exact match in a config locale, then in a registered
     * module. If those fail, we strip off any regionalization ('en-US' -> 'en')
     * and try each (config, registry) again. The final fallback for translation
     * is untranslated (which is US English) and for formats is the base English
     * (the only consequence being the last fallback date format %x is DD/MM/YYYY
     * instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored
     * for our automatic number formatting, but can be used in custom formats.
     */
    locales: {}
};

},{}],197:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../registry');
var Lib = require('../lib');

var baseAttributes = require('../plots/attributes');
var baseLayoutAttributes = require('../plots/layout_attributes');
var frameAttributes = require('../plots/frame_attributes');
var animationAttributes = require('../plots/animation_attributes');

// polar attributes are not part of the Registry yet
var polarAreaAttrs = require('../plots/polar/legacy/area_attributes');
var polarAxisAttrs = require('../plots/polar/legacy/axis_attributes');

var editTypes = require('./edit_types');

var extendFlat = Lib.extendFlat;
var extendDeepAll = Lib.extendDeepAll;
var isPlainObject = Lib.isPlainObject;

var IS_SUBPLOT_OBJ = '_isSubplotObj';
var IS_LINKED_TO_ARRAY = '_isLinkedToArray';
var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps';
var DEPRECATED = '_deprecated';
var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED];

exports.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ;
exports.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY;
exports.DEPRECATED = DEPRECATED;
exports.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS;

/** Outputs the full plotly.js plot schema
 *
 * @return {object}
 *  - defs
 *  - traces
 *  - layout
 *  - transforms
 *  - frames
 *  - animations
 *  - config (coming soon ...)
 */
exports.get = function() {
    var traces = {};

    Registry.allTypes.concat('area').forEach(function(type) {
        traces[type] = getTraceAttributes(type);
    });

    var transforms = {};

    Object.keys(Registry.transformsRegistry).forEach(function(type) {
        transforms[type] = getTransformAttributes(type);
    });

    return {
        defs: {
            valObjects: Lib.valObjectMeta,
            metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']),
            editType: {
                traces: editTypes.traces,
                layout: editTypes.layout
            },
            impliedEdits: {
                
            }
        },

        traces: traces,
        layout: getLayoutAttributes(),

        transforms: transforms,

        frames: getFramesAttributes(),
        animation: formatAttributes(animationAttributes)
    };
};

/**
 * Crawl the attribute tree, recursively calling a callback function
 *
 * @param {object} attrs
 *  The node of the attribute tree (e.g. the root) from which recursion originates
 * @param {Function} callback
 *  A callback function with the signature:
 *          @callback callback
 *          @param {object} attr an attribute
 *          @param {String} attrName name string
 *          @param {object[]} attrs all the attributes
 *          @param {Number} level the recursion level, 0 at the root
 * @param {Number} [specifiedLevel]
 *  The level in the tree, in order to let the callback function detect descend or backtrack,
 *  typically unsupplied (implied 0), just used by the self-recursive call.
 *  The necessity arises because the tree traversal is not controlled by callback return values.
 *  The decision to not use callback return values for controlling tree pruning arose from
 *  the goal of keeping the crawler backwards compatible. Observe that one of the pruning conditions
 *  precedes the callback call.
 * @param {string} [attrString]
 *  the path to the current attribute, as an attribute string (ie 'marker.line')
 *  typically unsupplied, but you may supply it if you want to disambiguate which attrs tree you
 *  are starting from
 *
 * @return {object} transformOut
 *  copy of transformIn that contains attribute defaults
 */
exports.crawl = function(attrs, callback, specifiedLevel, attrString) {
    var level = specifiedLevel || 0;
    attrString = attrString || '';

    Object.keys(attrs).forEach(function(attrName) {
        var attr = attrs[attrName];

        if(UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;

        var fullAttrString = (attrString ? attrString + '.' : '') + attrName;
        callback(attr, attrName, attrs, level, fullAttrString);

        if(exports.isValObject(attr)) return;

        if(isPlainObject(attr) && attrName !== 'impliedEdits') {
            exports.crawl(attr, callback, level + 1, fullAttrString);
        }
    });
};

/** Is object a value object (or a container object)?
 *
 * @param {object} obj
 * @return {boolean}
 *  returns true for a valid value object and
 *  false for tree nodes in the attribute hierarchy
 */
exports.isValObject = function(obj) {
    return obj && obj.valType !== undefined;
};

/**
 * Find all data array attributes in a given trace object - including
 * `arrayOk` attributes.
 *
 * @param {object} trace
 *  full trace object that contains a reference to `_module.attributes`
 *
 * @return {array} arrayAttributes
 *  list of array attributes for the given trace
 */
exports.findArrayAttributes = function(trace) {
    var arrayAttributes = [];
    var stack = [];
    var isArrayStack = [];
    var baseContainer, baseAttrName;

    function callback(attr, attrName, attrs, level) {
        stack = stack.slice(0, level).concat([attrName]);
        isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);

        var splittableAttr = (
            attr &&
            (attr.valType === 'data_array' || attr.arrayOk === true) &&
            !(stack[level - 1] === 'colorbar' && (attrName === 'ticktext' || attrName === 'tickvals'))
        );

        // Manually exclude 'colorbar.tickvals' and 'colorbar.ticktext' for now
        // which are declared as `valType: 'data_array'` but scale independently of
        // the coordinate arrays.
        //
        // Down the road, we might want to add a schema field (e.g `uncorrelatedArray: true`)
        // to distinguish attributes of the likes.

        if(!splittableAttr) return;

        crawlIntoTrace(baseContainer, 0, '');
    }

    function crawlIntoTrace(container, i, astrPartial) {
        var item = container[stack[i]];
        var newAstrPartial = astrPartial + stack[i];
        if(i === stack.length - 1) {
            if(Lib.isArrayOrTypedArray(item)) {
                arrayAttributes.push(baseAttrName + newAstrPartial);
            }
        }
        else {
            if(isArrayStack[i]) {
                if(Array.isArray(item)) {
                    for(var j = 0; j < item.length; j++) {
                        if(Lib.isPlainObject(item[j])) {
                            crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
                        }
                    }
                }
            }
            else if(Lib.isPlainObject(item)) {
                crawlIntoTrace(item, i + 1, newAstrPartial + '.');
            }
        }
    }

    baseContainer = trace;
    baseAttrName = '';
    exports.crawl(baseAttributes, callback);
    if(trace._module && trace._module.attributes) {
        exports.crawl(trace._module.attributes, callback);
    }

    var transforms = trace.transforms;
    if(transforms) {
        for(var i = 0; i < transforms.length; i++) {
            var transform = transforms[i];
            var module = transform._module;

            if(module) {
                baseAttrName = 'transforms[' + i + '].';
                baseContainer = transform;

                exports.crawl(module.attributes, callback);
            }
        }
    }

    return arrayAttributes;
};

/*
 * Find the valObject for one attribute in an existing trace
 *
 * @param {object} trace
 *  full trace object that contains a reference to `_module.attributes`
 * @param {object} parts
 *  an array of parts, like ['transforms', 1, 'value']
 *  typically from nestedProperty(...).parts
 *
 * @return {object|false}
 *  the valObject for this attribute, or the last found parent
 *  in some cases the innermost valObject will not exist, for example
 *  `valType: 'any'` attributes where we might set a part of the attribute.
 *  In that case, stop at the deepest valObject we *do* find.
 */
exports.getTraceValObject = function(trace, parts) {
    var head = parts[0];
    var i = 1; // index to start recursing from
    var moduleAttrs, valObject;

    if(head === 'transforms') {
        if(parts.length === 1) {
            return baseAttributes.transforms;
        }
        var transforms = trace.transforms;
        if(!Array.isArray(transforms) || !transforms.length) return false;
        var tNum = parts[1];
        if(!isIndex(tNum) || tNum >= transforms.length) {
            return false;
        }
        moduleAttrs = (Registry.transformsRegistry[transforms[tNum].type] || {}).attributes;
        valObject = moduleAttrs && moduleAttrs[parts[2]];
        i = 3; // start recursing only inside the transform
    }
    else if(trace.type === 'area') {
        valObject = polarAreaAttrs[head];
    }
    else {
        // first look in the module for this trace
        // components have already merged their trace attributes in here
        var _module = trace._module;
        if(!_module) _module = (Registry.modules[trace.type || baseAttributes.type.dflt] || {})._module;
        if(!_module) return false;

        moduleAttrs = _module.attributes;
        valObject = moduleAttrs && moduleAttrs[head];

        // then look in the subplot attributes
        if(!valObject) {
            var subplotModule = _module.basePlotModule;
            if(subplotModule && subplotModule.attributes) {
                valObject = subplotModule.attributes[head];
            }
        }

        // finally look in the global attributes
        if(!valObject) valObject = baseAttributes[head];
    }

    return recurseIntoValObject(valObject, parts, i);
};

/*
 * Find the valObject for one layout attribute
 *
 * @param {array} parts
 *  an array of parts, like ['annotations', 1, 'x']
 *  typically from nestedProperty(...).parts
 *
 * @return {object|false}
 *  the valObject for this attribute, or the last found parent
 *  in some cases the innermost valObject will not exist, for example
 *  `valType: 'any'` attributes where we might set a part of the attribute.
 *  In that case, stop at the deepest valObject we *do* find.
 */
exports.getLayoutValObject = function(fullLayout, parts) {
    var valObject = layoutHeadAttr(fullLayout, parts[0]);

    return recurseIntoValObject(valObject, parts, 1);
};

function layoutHeadAttr(fullLayout, head) {
    var i, key, _module, attributes;

    // look for attributes of the subplot types used on the plot
    var basePlotModules = fullLayout._basePlotModules;
    if(basePlotModules) {
        var out;
        for(i = 0; i < basePlotModules.length; i++) {
            _module = basePlotModules[i];
            if(_module.attrRegex && _module.attrRegex.test(head)) {
                // if a module defines overrides, these take precedence
                // initially this is to allow gl2d different editTypes from svg cartesian
                if(_module.layoutAttrOverrides) return _module.layoutAttrOverrides;

                // otherwise take the first attributes we find
                if(!out && _module.layoutAttributes) out = _module.layoutAttributes;
            }

            // a module can also override the behavior of base (and component) module layout attrs
            // again see gl2d for initial use case
            var baseOverrides = _module.baseLayoutAttrOverrides;
            if(baseOverrides && head in baseOverrides) return baseOverrides[head];
        }
        if(out) return out;
    }

    // look for layout attributes contributed by traces on the plot
    var modules = fullLayout._modules;
    if(modules) {
        for(i = 0; i < modules.length; i++) {
            attributes = modules[i].layoutAttributes;
            if(attributes && head in attributes) {
                return attributes[head];
            }
        }
    }

    /*
     * Next look in components.
     * Components that define a schema have already merged this into
     * base and subplot attribute defs, so ignore these.
     * Others (older style) all put all their attributes
     * inside a container matching the module `name`
     * eg `attributes` (array) or `legend` (object)
     */
    for(key in Registry.componentsRegistry) {
        _module = Registry.componentsRegistry[key];
        if(!_module.schema && (head === _module.name)) {
            return _module.layoutAttributes;
        }
    }

    if(head in baseLayoutAttributes) return baseLayoutAttributes[head];

    // Polar doesn't populate _modules or _basePlotModules
    // just fall back on these when the others fail
    if(head === 'radialaxis' || head === 'angularaxis') {
        return polarAxisAttrs[head];
    }
    return polarAxisAttrs.layout[head] || false;
}

function recurseIntoValObject(valObject, parts, i) {
    if(!valObject) return false;

    if(valObject._isLinkedToArray) {
        // skip array index, abort if we try to dive into an array without an index
        if(isIndex(parts[i])) i++;
        else if(i < parts.length) return false;
    }

    // now recurse as far as we can. Occasionally we have an attribute
    // setting an internal part below what's in the schema; just return
    // the innermost schema item we find.
    for(; i < parts.length; i++) {
        var newValObject = valObject[parts[i]];
        if(isPlainObject(newValObject)) valObject = newValObject;
        else break;

        if(i === parts.length - 1) break;

        if(valObject._isLinkedToArray) {
            i++;
            if(!isIndex(parts[i])) return false;
        }
        else if(valObject.valType === 'info_array') {
            i++;
            var index = parts[i];
            if(!isIndex(index)) return false;

            var items = valObject.items;
            if(Array.isArray(items)) {
                if(index >= items.length) return false;
                if(valObject.dimensions === 2) {
                    i++;
                    if(parts.length === i) return valObject;
                    var index2 = parts[i];
                    if(!isIndex(index2)) return false;
                    valObject = items[index][index2];
                }
                else valObject = items[index];
            }
            else {
                valObject = items;
            }
        }
    }

    return valObject;
}

function isIndex(val) {
    return val === Math.round(val) && val >= 0;
}

function getTraceAttributes(type) {
    var _module, basePlotModule;

    if(type === 'area') {
        _module = { attributes: polarAreaAttrs };
        basePlotModule = {};
    }
    else {
        _module = Registry.modules[type]._module,
        basePlotModule = _module.basePlotModule;
    }

    var attributes = {};

    // make 'type' the first attribute in the object
    attributes.type = null;

    // base attributes (same for all trace types)
    extendDeepAll(attributes, baseAttributes);

    // module attributes
    extendDeepAll(attributes, _module.attributes);

    // subplot attributes
    if(basePlotModule.attributes) {
        extendDeepAll(attributes, basePlotModule.attributes);
    }

    // 'type' gets overwritten by baseAttributes; reset it here
    attributes.type = type;

    var out = {
        meta: _module.meta || {},
        attributes: formatAttributes(attributes),
    };

    // trace-specific layout attributes
    if(_module.layoutAttributes) {
        var layoutAttributes = {};

        extendDeepAll(layoutAttributes, _module.layoutAttributes);
        out.layoutAttributes = formatAttributes(layoutAttributes);
    }

    return out;
}

function getLayoutAttributes() {
    var layoutAttributes = {};
    var key, _module;

    // global layout attributes
    extendDeepAll(layoutAttributes, baseLayoutAttributes);

    // add base plot module layout attributes
    for(key in Registry.subplotsRegistry) {
        _module = Registry.subplotsRegistry[key];

        if(!_module.layoutAttributes) continue;

        if(Array.isArray(_module.attr)) {
            for(var i = 0; i < _module.attr.length; i++) {
                handleBasePlotModule(layoutAttributes, _module, _module.attr[i]);
            }
        } else {
            var astr = _module.attr === 'subplot' ? _module.name : _module.attr;
            handleBasePlotModule(layoutAttributes, _module, astr);
        }
    }

    // polar layout attributes
    layoutAttributes = assignPolarLayoutAttrs(layoutAttributes);

    // add registered components layout attributes
    for(key in Registry.componentsRegistry) {
        _module = Registry.componentsRegistry[key];
        var schema = _module.schema;

        /*
         * Components with defined schema have already been merged in at register time
         * but a few components define attributes that apply only to xaxis
         * not yaxis (rangeselector, rangeslider) - delete from y schema.
         * Note that the input attributes for xaxis/yaxis are the same object
         * so it's not possible to only add them to xaxis from the start.
         * If we ever have such asymmetry the other way, or anywhere else,
         * we will need to extend both this code and mergeComponentAttrsToSubplot
         * (which will not find yaxis only for example)
         */
        if(schema && (schema.subplots || schema.layout)) {
            var subplots = schema.subplots;
            if(subplots && subplots.xaxis && !subplots.yaxis) {
                for(var xkey in subplots.xaxis) delete layoutAttributes.yaxis[xkey];
            }
        }
        // older style without schema need to be explicitly merged in now
        else if(_module.layoutAttributes) {
            insertAttrs(layoutAttributes, _module.layoutAttributes, _module.name);
        }
    }

    return {
        layoutAttributes: formatAttributes(layoutAttributes)
    };
}

function getTransformAttributes(type) {
    var _module = Registry.transformsRegistry[type];
    var attributes = extendDeepAll({}, _module.attributes);

    // add registered components transform attributes
    Object.keys(Registry.componentsRegistry).forEach(function(k) {
        var _module = Registry.componentsRegistry[k];

        if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) {
            Object.keys(_module.schema.transforms[type]).forEach(function(v) {
                insertAttrs(attributes, _module.schema.transforms[type][v], v);
            });
        }
    });

    return {
        attributes: formatAttributes(attributes)
    };
}

function getFramesAttributes() {
    var attrs = {
        frames: Lib.extendDeepAll({}, frameAttributes)
    };

    formatAttributes(attrs);

    return attrs.frames;
}

function formatAttributes(attrs) {
    mergeValTypeAndRole(attrs);
    formatArrayContainers(attrs);
    stringify(attrs);

    return attrs;
}

function mergeValTypeAndRole(attrs) {

    function makeSrcAttr(attrName) {
        return {
            valType: 'string',
            
            
            editType: 'none'
        };
    }

    function callback(attr, attrName, attrs) {
        if(exports.isValObject(attr)) {
            if(attr.valType === 'data_array') {
                // all 'data_array' attrs have role 'data'
                attr.role = 'data';
                // all 'data_array' attrs have a corresponding 'src' attr
                attrs[attrName + 'src'] = makeSrcAttr(attrName);
            }
            else if(attr.arrayOk === true) {
                // all 'arrayOk' attrs have a corresponding 'src' attr
                attrs[attrName + 'src'] = makeSrcAttr(attrName);
            }
        }
        else if(isPlainObject(attr)) {
            // all attrs container objects get role 'object'
            attr.role = 'object';
        }
    }

    exports.crawl(attrs, callback);
}

function formatArrayContainers(attrs) {

    function callback(attr, attrName, attrs) {
        if(!attr) return;

        var itemName = attr[IS_LINKED_TO_ARRAY];

        if(!itemName) return;

        delete attr[IS_LINKED_TO_ARRAY];

        attrs[attrName] = { items: {} };
        attrs[attrName].items[itemName] = attr;
        attrs[attrName].role = 'object';
    }

    exports.crawl(attrs, callback);
}

// this can take around 10ms and should only be run from PlotSchema.get(),
// to ensure JSON.stringify(PlotSchema.get()) gives the intended result.
function stringify(attrs) {
    function walk(attr) {
        for(var k in attr) {
            if(isPlainObject(attr[k])) {
                walk(attr[k]);
            } else if(Array.isArray(attr[k])) {
                for(var i = 0; i < attr[k].length; i++) {
                    walk(attr[k][i]);
                }
            } else {
                // as JSON.stringify(/test/) // => {}
                if(attr[k] instanceof RegExp) {
                    attr[k] = attr[k].toString();
                }
            }
        }
    }

    walk(attrs);
}

function assignPolarLayoutAttrs(layoutAttributes) {
    extendFlat(layoutAttributes, {
        radialaxis: polarAxisAttrs.radialaxis,
        angularaxis: polarAxisAttrs.angularaxis
    });

    extendFlat(layoutAttributes, polarAxisAttrs.layout);

    return layoutAttributes;
}

function handleBasePlotModule(layoutAttributes, _module, astr) {
    var np = Lib.nestedProperty(layoutAttributes, astr),
        attrs = extendDeepAll({}, _module.layoutAttributes);

    attrs[IS_SUBPLOT_OBJ] = true;
    np.set(attrs);
}

function insertAttrs(baseAttrs, newAttrs, astr) {
    var np = Lib.nestedProperty(baseAttrs, astr);

    np.set(extendDeepAll(np.get() || {}, newAttrs));
}

},{"../lib":164,"../plots/animation_attributes":201,"../plots/attributes":203,"../plots/frame_attributes":233,"../plots/layout_attributes":236,"../plots/polar/legacy/area_attributes":246,"../plots/polar/legacy/axis_attributes":247,"../registry":254,"./edit_types":191}],198:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');
var Registry = require('../registry');
var Plots = require('../plots/plots');

var Lib = require('../lib');
var clearGlCanvases = require('../lib/clear_gl_canvases');

var Color = require('../components/color');
var Drawing = require('../components/drawing');
var Titles = require('../components/titles');
var ModeBar = require('../components/modebar');

var Axes = require('../plots/cartesian/axes');
var alignmentConstants = require('../constants/alignment');
var axisConstraints = require('../plots/cartesian/constraints');
var enforceAxisConstraints = axisConstraints.enforce;
var cleanAxisConstraints = axisConstraints.clean;
var doAutoRange = require('../plots/cartesian/autorange').doAutoRange;

exports.layoutStyles = function(gd) {
    return Lib.syncOrAsync([Plots.doAutoMargin, exports.lsInner], gd);
};

function overlappingDomain(xDomain, yDomain, domains) {
    for(var i = 0; i < domains.length; i++) {
        var existingX = domains[i][0],
            existingY = domains[i][1];

        if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
            continue;
        }
        if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
            return true;
        }
    }
    return false;
}

exports.lsInner = function(gd) {
    var fullLayout = gd._fullLayout;
    var gs = fullLayout._size;
    var pad = gs.p;
    var axList = Axes.list(gd);

    // _has('cartesian') means SVG specifically, not GL2D - but GL2D
    // can still get here because it makes some of the SVG structure
    // for shared features like selections.
    var hasSVGCartesian = fullLayout._has('cartesian');
    var i;

    function getLinePosition(ax, counterAx, side) {
        var lwHalf = ax._lw / 2;

        if(ax._id.charAt(0) === 'x') {
            if(!counterAx) return gs.t + gs.h * (1 - (ax.position || 0)) + (lwHalf % 1);
            else if(side === 'top') return counterAx._offset - pad - lwHalf;
            return counterAx._offset + counterAx._length + pad + lwHalf;
        }

        if(!counterAx) return gs.l + gs.w * (ax.position || 0) + (lwHalf % 1);
        else if(side === 'right') return counterAx._offset + counterAx._length + pad + lwHalf;
        return counterAx._offset - pad - lwHalf;
    }

    // some preparation of axis position info
    for(i = 0; i < axList.length; i++) {
        var ax = axList[i];

        // reset scale in case the margins have changed
        ax.setScale();

        var counterAx = ax._anchorAxis;

        // clear axis line positions, to be set in the subplot loop below
        ax._linepositions = {};

        // stash crispRounded linewidth so we don't need to pass gd all over the place
        ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);

        // figure out the main axis line and main mirror line position.
        // it's easier to follow the logic if we handle these separately from
        // ax._linepositions, which are really only used by mirror=allticks
        // for the non-main-subplot ticks.
        ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
        ax._mainMirrorPosition = (ax.mirror && counterAx) ?
            getLinePosition(ax, counterAx,
                alignmentConstants.OPPOSITE_SIDE[ax.side]) : null;
    }

    fullLayout._paperdiv
        .style({
            width: fullLayout.width + 'px',
            height: fullLayout.height + 'px'
        })
        .selectAll('.main-svg')
            .call(Drawing.setSize, fullLayout.width, fullLayout.height);

    gd._context.setBackground(gd, fullLayout.paper_bgcolor);

    var subplotSelection = fullLayout._paper.selectAll('g.subplot');

    // figure out which backgrounds we need to draw, and in which layers
    // to put them
    var lowerBackgroundIDs = [];
    var lowerDomains = [];
    subplotSelection.each(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];

        if(plotinfo.mainplot) {
            // mainplot is a reference to the main plot this one is overlaid on
            // so if it exists, this is an overlaid plot and we don't need to
            // give it its own background
            if(plotinfo.bg) {
                plotinfo.bg.remove();
            }
            plotinfo.bg = undefined;
            return;
        }

        var xDomain = plotinfo.xaxis.domain;
        var yDomain = plotinfo.yaxis.domain;
        var plotgroup = plotinfo.plotgroup;

        if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
            var pgNode = plotgroup.node();
            var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, 'rect', 'bg');
            pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
        } else {
            plotgroup.select('rect.bg').remove();
            lowerBackgroundIDs.push(subplot);
            lowerDomains.push([xDomain, yDomain]);
        }
    });

    // now create all the lower-layer backgrounds at once now that
    // we have the list of subplots that need them
    var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
        .data(lowerBackgroundIDs);

    lowerBackgrounds.enter().append('rect')
        .classed('bg', true);

    lowerBackgrounds.exit().remove();

    lowerBackgrounds.each(function(subplot) {
        fullLayout._plots[subplot].bg = d3.select(this);
    });

    subplotSelection.each(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        if(plotinfo.bg && hasSVGCartesian) {
            plotinfo.bg
                .call(Drawing.setRect,
                    xa._offset - pad, ya._offset - pad,
                    xa._length + 2 * pad, ya._length + 2 * pad)
                .call(Color.fill, fullLayout.plot_bgcolor)
                .style('stroke-width', 0);
        }

        // Clip so that data only shows up on the plot area.
        var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';

        var plotClip = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
            s.classed('plotclip', true)
                .append('rect');
        });

        plotinfo.clipRect = plotClip.select('rect').attr({
            width: xa._length,
            height: ya._length
        });

        Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);

        var plotClipId;
        var layerClipId;

        if(plotinfo._hasClipOnAxisFalse) {
            plotClipId = null;
            layerClipId = clipId;
        } else {
            plotClipId = clipId;
            layerClipId = null;
        }

        Drawing.setClipUrl(plotinfo.plot, plotClipId);

        // stash layer clipId value (null or same as clipId)
        // to DRY up Drawing.setClipUrl calls on trace-module and trace layers
        // downstream
        plotinfo.layerClipId = layerClipId;

        // figure out extra axis line and tick positions as needed
        if(!hasSVGCartesian) return;

        var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop,
            leftYLineWidth, rightYLineWidth;
        var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight,
            connectYBottom, connectYTop;
        var extraSubplot;

        function xLinePath(y) {
            return 'M' + xLinesXLeft + ',' + y + 'H' + xLinesXRight;
        }

        function xLinePathFree(y) {
            return 'M' + xa._offset + ',' + y + 'h' + xa._length;
        }

        function yLinePath(x) {
            return 'M' + x + ',' + yLinesYTop + 'V' + yLinesYBottom;
        }

        function yLinePathFree(x) {
            return 'M' + x + ',' + ya._offset + 'v' + ya._length;
        }

        function mainPath(ax, pathFn, pathFnFree) {
            if(!ax.showline || subplot !== ax._mainSubplot) return '';
            if(!ax._anchorAxis) return pathFnFree(ax._mainLinePosition);
            var out = pathFn(ax._mainLinePosition);
            if(ax.mirror) out += pathFn(ax._mainMirrorPosition);
            return out;
        }

        /*
         * x lines get longer where they meet y lines, to make a crisp corner.
         * The x lines get the padding (margin.pad) plus the y line width to
         * fill up the corner nicely. Free x lines are excluded - they always
         * span exactly the data area of the plot
         *
         *  | XXXXX
         *  | XXXXX
         *  |
         *  +------
         *     x1
         *    -----
         *     x2
         */
        var xPath = 'M0,0';
        if(shouldShowLinesOrTicks(xa, subplot)) {
            leftYLineWidth = findCounterAxisLineWidth(xa, 'left', ya, axList);
            xLinesXLeft = xa._offset - (leftYLineWidth ? (pad + leftYLineWidth) : 0);
            rightYLineWidth = findCounterAxisLineWidth(xa, 'right', ya, axList);
            xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? (pad + rightYLineWidth) : 0);
            xLinesYBottom = getLinePosition(xa, ya, 'bottom');
            xLinesYTop = getLinePosition(xa, ya, 'top');

            // save axis line positions for extra ticks to reference
            // each subplot that gets ticks from "allticks" gets an entry:
            //    [left or bottom, right or top]
            extraSubplot = (!xa._anchorAxis || subplot !== xa._mainSubplot);
            if(extraSubplot && xa.ticks && xa.mirror === 'allticks') {
                xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
            }

            xPath = mainPath(xa, xLinePath, xLinePathFree);
            if(extraSubplot && xa.showline && (xa.mirror === 'all' || xa.mirror === 'allticks')) {
                xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
            }

            plotinfo.xlines
                .style('stroke-width', xa._lw + 'px')
                .call(Color.stroke, xa.showline ?
                    xa.linecolor : 'rgba(0,0,0,0)');
        }
        plotinfo.xlines.attr('d', xPath);

        /*
         * y lines that meet x axes get longer only by margin.pad, because
         * the x axes fill in the corner space. Free y axes, like free x axes,
         * always span exactly the data area of the plot
         *
         *   |   | XXXX
         * y2| y1| XXXX
         *   |   | XXXX
         *       |
         *       +-----
         */
        var yPath = 'M0,0';
        if(shouldShowLinesOrTicks(ya, subplot)) {
            connectYBottom = findCounterAxisLineWidth(ya, 'bottom', xa, axList);
            yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
            connectYTop = findCounterAxisLineWidth(ya, 'top', xa, axList);
            yLinesYTop = ya._offset - (connectYTop ? pad : 0);
            yLinesXLeft = getLinePosition(ya, xa, 'left');
            yLinesXRight = getLinePosition(ya, xa, 'right');

            extraSubplot = (!ya._anchorAxis || subplot !== xa._mainSubplot);
            if(extraSubplot && ya.ticks && ya.mirror === 'allticks') {
                ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
            }

            yPath = mainPath(ya, yLinePath, yLinePathFree);
            if(extraSubplot && ya.showline && (ya.mirror === 'all' || ya.mirror === 'allticks')) {
                yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
            }

            plotinfo.ylines
                .style('stroke-width', ya._lw + 'px')
                .call(Color.stroke, ya.showline ?
                    ya.linecolor : 'rgba(0,0,0,0)');
        }
        plotinfo.ylines.attr('d', yPath);
    });

    Axes.makeClipPaths(gd);
    exports.drawMainTitle(gd);
    ModeBar.manage(gd);

    return gd._promises.length && Promise.all(gd._promises);
};

function shouldShowLinesOrTicks(ax, subplot) {
    return (ax.ticks || ax.showline) &&
        (subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks');
}

/*
 * should we draw a line on counterAx at this side of ax?
 * It's assumed that counterAx is known to overlay the subplot we're working on
 * but it may not be its main axis.
 */
function shouldShowLineThisSide(ax, side, counterAx) {
    // does counterAx get a line at all?
    if(!counterAx.showline || !counterAx._lw) return false;

    // are we drawing *all* lines for counterAx?
    if(counterAx.mirror === 'all' || counterAx.mirror === 'allticks') return true;

    var anchorAx = counterAx._anchorAxis;

    // is this a free axis? free axes can only have a subplot side-line with all(ticks)? mirroring
    if(!anchorAx) return false;

    // in order to handle cases where the user forgot to anchor this axis correctly
    // (because its default anchor has the same domain on the relevant end)
    // check whether the relevant position is the same.
    var sideIndex = alignmentConstants.FROM_BL[side];
    if(counterAx.side === side) {
        return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
    }
    return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
}

/*
 * Is there another axis intersecting `side` end of `ax`?
 * First look at `counterAx` (the axis for this subplot),
 * then at all other potential counteraxes on or overlaying this subplot.
 * Take the line width from the first one that has a line.
 */
function findCounterAxisLineWidth(ax, side, counterAx, axList) {
    if(shouldShowLineThisSide(ax, side, counterAx)) {
        return counterAx._lw;
    }
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
            return axi._lw;
        }
    }
    return 0;
}

exports.drawMainTitle = function(gd) {
    var fullLayout = gd._fullLayout;

    Titles.draw(gd, 'gtitle', {
        propContainer: fullLayout,
        propName: 'title',
        placeholder: fullLayout._dfltTitle.plot,
        attributes: {
            x: fullLayout.width / 2,
            y: fullLayout._size.t / 2,
            'text-anchor': 'middle'
        }
    });
};

// First, see if we need to do arraysToCalcdata
// call it regardless of what change we made, in case
// supplyDefaults brought in an array that was already
// in gd.data but not in gd._fullData previously
exports.doTraceStyle = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi = gd.calcdata[i],
            _module = ((cdi[0] || {}).trace || {})._module || {},
            arraysToCalcdata = _module.arraysToCalcdata;

        if(arraysToCalcdata) arraysToCalcdata(cdi, cdi[0].trace);
    }

    Plots.style(gd);
    Registry.getComponentMethod('legend', 'draw')(gd);

    return Plots.previousPromises(gd);
};

exports.doColorBars = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi0 = gd.calcdata[i][0];

        if((cdi0.t || {}).cb) {
            var trace = cdi0.trace,
                cb = cdi0.t.cb;

            if(Registry.traceIs(trace, 'contour')) {
                cb.line({
                    width: trace.contours.showlines !== false ?
                        trace.line.width : 0,
                    dash: trace.line.dash,
                    color: trace.contours.coloring === 'line' ?
                        cb._opts.line.color : trace.line.color
                });
            }
            if(Registry.traceIs(trace, 'markerColorscale')) {
                cb.options(trace.marker.colorbar)();
            }
            else cb.options(trace.colorbar)();
        }
    }

    return Plots.previousPromises(gd);
};

// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function(gd) {
    var layout = gd.layout;
    gd.layout = undefined;
    return Registry.call('plot', gd, '', layout);
};

exports.doLegend = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    return Plots.previousPromises(gd);
};

exports.doTicksRelayout = function(gd) {
    Axes.doTicks(gd, 'redraw');

    if(gd._fullLayout._hasOnlyLargeSploms) {
        clearGlCanvases(gd);
        Registry.subplotsRegistry.splom.plot(gd);
    }

    exports.drawMainTitle(gd);
    return Plots.previousPromises(gd);
};

exports.doModeBar = function(gd) {
    var fullLayout = gd._fullLayout;

    ModeBar.manage(gd);

    for(var i = 0; i < fullLayout._basePlotModules.length; i++) {
        var updateFx = fullLayout._basePlotModules[i].updateFx;
        if(updateFx) updateFx(fullLayout);
    }

    return Plots.previousPromises(gd);
};

exports.doCamera = function(gd) {
    var fullLayout = gd._fullLayout;
    var sceneIds = fullLayout._subplots.gl3d;

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]];
        var scene = sceneLayout._scene;

        scene.setCamera(sceneLayout.camera);
    }
};

exports.drawData = function(gd) {
    var fullLayout = gd._fullLayout;
    var calcdata = gd.calcdata;
    var i;

    // remove old colorbars explicitly
    for(i = 0; i < calcdata.length; i++) {
        var trace = calcdata[i][0].trace;
        if(trace.visible !== true || !trace._module.colorbar) {
            fullLayout._infolayer.select('.cb' + trace.uid).remove();
        }
    }

    clearGlCanvases(gd);

    // loop over the base plot modules present on graph
    var basePlotModules = fullLayout._basePlotModules;
    for(i = 0; i < basePlotModules.length; i++) {
        basePlotModules[i].plot(gd);
    }

    // styling separate from drawing
    Plots.style(gd);

    // show annotations and shapes
    Registry.getComponentMethod('shapes', 'draw')(gd);
    Registry.getComponentMethod('annotations', 'draw')(gd);

    // Mark the first render as complete
    fullLayout._replotting = false;

    return Plots.previousPromises(gd);
};

exports.doAutoRangeAndConstraints = function(gd) {
    var axList = Axes.list(gd, '', true);

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];
        cleanAxisConstraints(gd, ax);
        doAutoRange(ax);
    }

    enforceAxisConstraints(gd);
};

// An initial paint must be completed before these components can be
// correctly sized and the whole plot re-margined. fullLayout._replotting must
// be set to false before these will work properly.
exports.finalDraw = function(gd) {
    Registry.getComponentMethod('shapes', 'draw')(gd);
    Registry.getComponentMethod('images', 'draw')(gd);
    Registry.getComponentMethod('annotations', 'draw')(gd);
    Registry.getComponentMethod('legend', 'draw')(gd);
    Registry.getComponentMethod('rangeslider', 'draw')(gd);
    Registry.getComponentMethod('rangeselector', 'draw')(gd);
    Registry.getComponentMethod('sliders', 'draw')(gd);
    Registry.getComponentMethod('updatemenus', 'draw')(gd);
};

},{"../components/color":43,"../components/drawing":68,"../components/modebar":106,"../components/titles":136,"../constants/alignment":143,"../lib":164,"../lib/clear_gl_canvases":152,"../plots/cartesian/autorange":205,"../plots/cartesian/axes":206,"../plots/cartesian/constraints":213,"../plots/plots":245,"../registry":254,"d3":6}],199:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var plotApi = require('./plot_api');
var Lib = require('../lib');

var helpers = require('../snapshot/helpers');
var toSVG = require('../snapshot/tosvg');
var svgToImg = require('../snapshot/svgtoimg');

var attrs = {
    format: {
        valType: 'enumerated',
        values: ['png', 'jpeg', 'webp', 'svg'],
        dflt: 'png',
        
    },
    width: {
        valType: 'number',
        min: 1,
        
    },
    height: {
        valType: 'number',
        min: 1,
        
    },
    scale: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
    },
    setBackground: {
        valType: 'any',
        dflt: false,
        
    },
    imageDataOnly: {
        valType: 'boolean',
        dflt: false,
        
    }
};

var IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;

/** Plotly.toImage
 *
 * @param {object | string | HTML div} gd
 *   can either be a data/layout/config object
 *   or an existing graph <div>
 *   or an id to an existing graph <div>
 * @param {object} opts (see above)
 * @return {promise}
 */
function toImage(gd, opts) {
    opts = opts || {};

    var data;
    var layout;
    var config;

    if(Lib.isPlainObject(gd)) {
        data = gd.data || [];
        layout = gd.layout || {};
        config = gd.config || {};
    } else {
        gd = Lib.getGraphDiv(gd);
        data = Lib.extendDeep([], gd.data);
        layout = Lib.extendDeep({}, gd.layout);
        config = gd._context;
    }

    function isImpliedOrValid(attr) {
        return !(attr in opts) || Lib.validate(opts[attr], attrs[attr]);
    }

    if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) {
        throw new Error('Height and width should be pixel values.');
    }

    if(!isImpliedOrValid('format')) {
        throw new Error('Image format is not jpeg, png, svg or webp.');
    }

    var fullOpts = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts, fullOpts, attrs, attr, dflt);
    }

    var format = coerce('format');
    var width = coerce('width');
    var height = coerce('height');
    var scale = coerce('scale');
    var setBackground = coerce('setBackground');
    var imageDataOnly = coerce('imageDataOnly');

    // put the cloned div somewhere off screen before attaching to DOM
    var clonedGd = document.createElement('div');
    clonedGd.style.position = 'absolute';
    clonedGd.style.left = '-5000px';
    document.body.appendChild(clonedGd);

    // extend layout with image options
    var layoutImage = Lib.extendFlat({}, layout);
    if(width) layoutImage.width = width;
    if(height) layoutImage.height = height;

    // extend config for static plot
    var configImage = Lib.extendFlat({}, config, {
        staticPlot: true,
        setBackground: setBackground
    });

    var redrawFunc = helpers.getRedrawFunc(clonedGd);

    function wait() {
        return new Promise(function(resolve) {
            setTimeout(resolve, helpers.getDelay(clonedGd._fullLayout));
        });
    }

    function convert() {
        return new Promise(function(resolve, reject) {
            var svg = toSVG(clonedGd, format, scale);
            var width = clonedGd._fullLayout.width;
            var height = clonedGd._fullLayout.height;

            plotApi.purge(clonedGd);
            document.body.removeChild(clonedGd);

            if(format === 'svg') {
                if(imageDataOnly) {
                    return resolve(svg);
                } else {
                    return resolve('data:image/svg+xml,' + encodeURIComponent(svg));
                }
            }

            var canvas = document.createElement('canvas');
            canvas.id = Lib.randstr();

            svgToImg({
                format: format,
                width: width,
                height: height,
                scale: scale,
                canvas: canvas,
                svg: svg,
                // ask svgToImg to return a Promise
                //  rather than EventEmitter
                //  leave EventEmitter for backward
                //  compatibility
                promise: true
            })
            .then(resolve)
            .catch(reject);
        });
    }

    function urlToImageData(url) {
        if(imageDataOnly) {
            return url.replace(IMAGE_URL_PREFIX, '');
        } else {
            return url;
        }
    }

    return new Promise(function(resolve, reject) {
        plotApi.plot(clonedGd, data, layoutImage, configImage)
            .then(redrawFunc)
            .then(wait)
            .then(convert)
            .then(function(url) { resolve(urlToImageData(url)); })
            .catch(function(err) { reject(err); });
    });
}

module.exports = toImage;

},{"../lib":164,"../snapshot/helpers":258,"../snapshot/svgtoimg":260,"../snapshot/tosvg":262,"./plot_api":195}],200:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../lib');
var Plots = require('../plots/plots');
var PlotSchema = require('./plot_schema');
var dfltConfig = require('./plot_config');

var isPlainObject = Lib.isPlainObject;
var isArray = Array.isArray;
var isArrayOrTypedArray = Lib.isArrayOrTypedArray;

/**
 * Validate a data array and layout object.
 *
 * @param {array} data
 * @param {object} layout
 *
 * @return {array} array of error objects each containing:
 *  - {string} code
 *      error code ('object', 'array', 'schema', 'unused', 'invisible' or 'value')
 *  - {string} container
 *      container where the error occurs ('data' or 'layout')
 *  - {number} trace
 *      trace index of the 'data' container where the error occurs
 *  - {array} path
 *      nested path to the key that causes the error
 *  - {string} astr
 *      attribute string variant of 'path' compatible with Plotly.restyle and
 *      Plotly.relayout.
 *  - {string} msg
 *      error message (shown in console in logger config argument is enable)
 */
module.exports = function valiate(data, layout) {
    var schema = PlotSchema.get();
    var errorList = [];
    var gd = {_context: Lib.extendFlat({}, dfltConfig)};

    var dataIn, layoutIn;

    if(isArray(data)) {
        gd.data = Lib.extendDeep([], data);
        dataIn = data;
    }
    else {
        gd.data = [];
        dataIn = [];
        errorList.push(format('array', 'data'));
    }

    if(isPlainObject(layout)) {
        gd.layout = Lib.extendDeep({}, layout);
        layoutIn = layout;
    }
    else {
        gd.layout = {};
        layoutIn = {};
        if(arguments.length > 1) {
            errorList.push(format('object', 'layout'));
        }
    }

    // N.B. dataIn and layoutIn are in general not the same as
    // gd.data and gd.layout after supplyDefaults as some attributes
    // in gd.data and gd.layout (still) get mutated during this step.

    Plots.supplyDefaults(gd);

    var dataOut = gd._fullData,
        len = dataIn.length;

    for(var i = 0; i < len; i++) {
        var traceIn = dataIn[i],
            base = ['data', i];

        if(!isPlainObject(traceIn)) {
            errorList.push(format('object', base));
            continue;
        }

        var traceOut = dataOut[i],
            traceType = traceOut.type,
            traceSchema = schema.traces[traceType].attributes;

        // PlotSchema does something fancy with trace 'type', reset it here
        // to make the trace schema compatible with Lib.validate.
        traceSchema.type = {
            valType: 'enumerated',
            values: [traceType]
        };

        if(traceOut.visible === false && traceIn.visible !== false) {
            errorList.push(format('invisible', base));
        }

        crawl(traceIn, traceOut, traceSchema, errorList, base);

        var transformsIn = traceIn.transforms,
            transformsOut = traceOut.transforms;

        if(transformsIn) {
            if(!isArray(transformsIn)) {
                errorList.push(format('array', base, ['transforms']));
            }

            base.push('transforms');

            for(var j = 0; j < transformsIn.length; j++) {
                var path = ['transforms', j],
                    transformType = transformsIn[j].type;

                if(!isPlainObject(transformsIn[j])) {
                    errorList.push(format('object', base, path));
                    continue;
                }

                var transformSchema = schema.transforms[transformType] ?
                    schema.transforms[transformType].attributes :
                    {};

                // add 'type' to transform schema to validate the transform type
                transformSchema.type = {
                    valType: 'enumerated',
                    values: Object.keys(schema.transforms)
                };

                crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path);
            }
        }
    }

    var layoutOut = gd._fullLayout,
        layoutSchema = fillLayoutSchema(schema, dataOut);

    crawl(layoutIn, layoutOut, layoutSchema, errorList, 'layout');

    // return undefined if no validation errors were found
    return (errorList.length === 0) ? void(0) : errorList;
};

function crawl(objIn, objOut, schema, list, base, path) {
    path = path || [];

    var keys = Object.keys(objIn);

    for(var i = 0; i < keys.length; i++) {
        var k = keys[i];

        // transforms are handled separately
        if(k === 'transforms') continue;

        var p = path.slice();
        p.push(k);

        var valIn = objIn[k],
            valOut = objOut[k];

        var nestedSchema = getNestedSchema(schema, k);
        var isInfoArray = (nestedSchema || {}).valType === 'info_array';
        var isColorscale = (nestedSchema || {}).valType === 'colorscale';
        var items = (nestedSchema || {}).items;

        if(!isInSchema(schema, k)) {
            list.push(format('schema', base, p));
        }
        else if(isPlainObject(valIn) && isPlainObject(valOut)) {
            crawl(valIn, valOut, nestedSchema, list, base, p);
        }
        else if(isInfoArray && isArray(valIn)) {
            if(valIn.length > valOut.length) {
                list.push(format('unused', base, p.concat(valOut.length)));
            }
            var len = valOut.length;
            var arrayItems = Array.isArray(items);
            if(arrayItems) len = Math.min(len, items.length);
            var m, n, item, valInPart, valOutPart;
            if(nestedSchema.dimensions === 2) {
                for(n = 0; n < len; n++) {
                    if(isArray(valIn[n])) {
                        if(valIn[n].length > valOut[n].length) {
                            list.push(format('unused', base, p.concat(n, valOut[n].length)));
                        }
                        var len2 = valOut[n].length;
                        for(m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) {
                            item = arrayItems ? items[n][m] : items;
                            valInPart = valIn[n][m];
                            valOutPart = valOut[n][m];
                            if(!Lib.validate(valInPart, item)) {
                                list.push(format('value', base, p.concat(n, m), valInPart));
                            }
                            else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
                                list.push(format('dynamic', base, p.concat(n, m), valInPart, valOutPart));
                            }
                        }
                    }
                    else {
                        list.push(format('array', base, p.concat(n), valIn[n]));
                    }
                }
            }
            else {
                for(n = 0; n < len; n++) {
                    item = arrayItems ? items[n] : items;
                    valInPart = valIn[n];
                    valOutPart = valOut[n];
                    if(!Lib.validate(valInPart, item)) {
                        list.push(format('value', base, p.concat(n), valInPart));
                    }
                    else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
                        list.push(format('dynamic', base, p.concat(n), valInPart, valOutPart));
                    }
                }
            }
        }
        else if(nestedSchema.items && !isInfoArray && isArray(valIn)) {
            var _nestedSchema = items[Object.keys(items)[0]],
                indexList = [];

            var j, _p;

            // loop over valOut items while keeping track of their
            // corresponding input container index (given by _index)
            for(j = 0; j < valOut.length; j++) {
                var _index = valOut[j]._index || j;

                _p = p.slice();
                _p.push(_index);

                if(isPlainObject(valIn[_index]) && isPlainObject(valOut[j])) {
                    indexList.push(_index);
                    crawl(valIn[_index], valOut[j], _nestedSchema, list, base, _p);
                }
            }

            // loop over valIn to determine where it went wrong for some items
            for(j = 0; j < valIn.length; j++) {
                _p = p.slice();
                _p.push(j);

                if(!isPlainObject(valIn[j])) {
                    list.push(format('object', base, _p, valIn[j]));
                }
                else if(indexList.indexOf(j) === -1) {
                    list.push(format('unused', base, _p));
                }
            }
        }
        else if(!isPlainObject(valIn) && isPlainObject(valOut)) {
            list.push(format('object', base, p, valIn));
        }
        else if(!isArrayOrTypedArray(valIn) && isArrayOrTypedArray(valOut) && !isInfoArray && !isColorscale) {
            list.push(format('array', base, p, valIn));
        }
        else if(!(k in objOut)) {
            list.push(format('unused', base, p, valIn));
        }
        else if(!Lib.validate(valIn, nestedSchema)) {
            list.push(format('value', base, p, valIn));
        }
        else if(nestedSchema.valType === 'enumerated' &&
            ((nestedSchema.coerceNumber && valIn !== +valOut) || valIn !== valOut)
        ) {
            list.push(format('dynamic', base, p, valIn, valOut));
        }
    }

    return list;
}

// the 'full' layout schema depends on the traces types presents
function fillLayoutSchema(schema, dataOut) {
    for(var i = 0; i < dataOut.length; i++) {
        var traceType = dataOut[i].type,
            traceLayoutAttr = schema.traces[traceType].layoutAttributes;

        if(traceLayoutAttr) {
            Lib.extendFlat(schema.layout.layoutAttributes, traceLayoutAttr);
        }
    }

    return schema.layout.layoutAttributes;
}

// validation error codes
var code2msgFunc = {
    object: function(base, astr) {
        var prefix;

        if(base === 'layout' && astr === '') prefix = 'The layout argument';
        else if(base[0] === 'data' && astr === '') {
            prefix = 'Trace ' + base[1] + ' in the data argument';
        }
        else prefix = inBase(base) + 'key ' + astr;

        return prefix + ' must be linked to an object container';
    },
    array: function(base, astr) {
        var prefix;

        if(base === 'data') prefix = 'The data argument';
        else prefix = inBase(base) + 'key ' + astr;

        return prefix + ' must be linked to an array container';
    },
    schema: function(base, astr) {
        return inBase(base) + 'key ' + astr + ' is not part of the schema';
    },
    unused: function(base, astr, valIn) {
        var target = isPlainObject(valIn) ? 'container' : 'key';

        return inBase(base) + target + ' ' + astr + ' did not get coerced';
    },
    dynamic: function(base, astr, valIn, valOut) {
        return [
            inBase(base) + 'key',
            astr,
            '(set to \'' + valIn + '\')',
            'got reset to',
            '\'' + valOut + '\'',
            'during defaults.'
        ].join(' ');
    },
    invisible: function(base) {
        return 'Trace ' + base[1] + ' got defaulted to be not visible';
    },
    value: function(base, astr, valIn) {
        return [
            inBase(base) + 'key ' + astr,
            'is set to an invalid value (' + valIn + ')'
        ].join(' ');
    }
};

function inBase(base) {
    if(isArray(base)) return 'In data trace ' + base[1] + ', ';

    return 'In ' + base + ', ';
}

function format(code, base, path, valIn, valOut) {
    path = path || '';

    var container, trace;

    // container is either 'data' or 'layout
    // trace is the trace index if 'data', null otherwise

    if(isArray(base)) {
        container = base[0];
        trace = base[1];
    }
    else {
        container = base;
        trace = null;
    }

    var astr = convertPathToAttributeString(path);
    var msg = code2msgFunc[code](base, astr, valIn, valOut);

    // log to console if logger config option is enabled
    Lib.log(msg);

    return {
        code: code,
        container: container,
        trace: trace,
        path: path,
        astr: astr,
        msg: msg
    };
}

function isInSchema(schema, key) {
    var parts = splitKey(key),
        keyMinusId = parts.keyMinusId,
        id = parts.id;

    if((keyMinusId in schema) && schema[keyMinusId]._isSubplotObj && id) {
        return true;
    }

    return (key in schema);
}

function getNestedSchema(schema, key) {
    var parts = splitKey(key);

    return schema[parts.keyMinusId];
}

var idRegex = Lib.counterRegex('([a-z]+)');

function splitKey(key) {
    var idMatch = key.match(idRegex);

    return {
        keyMinusId: idMatch && idMatch[1],
        id: idMatch && idMatch[2]
    };
}

function convertPathToAttributeString(path) {
    if(!isArray(path)) return String(path);

    var astr = '';

    for(var i = 0; i < path.length; i++) {
        var p = path[i];

        if(typeof p === 'number') {
            astr = astr.substr(0, astr.length - 1) + '[' + p + ']';
        }
        else {
            astr += p;
        }

        if(i < path.length - 1) astr += '.';
    }

    return astr;
}

},{"../lib":164,"../plots/plots":245,"./plot_config":196,"./plot_schema":197}],201:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    mode: {
        valType: 'enumerated',
        dflt: 'afterall',
        
        values: ['immediate', 'next', 'afterall'],
        
    },
    direction: {
        valType: 'enumerated',
        
        values: ['forward', 'reverse'],
        dflt: 'forward',
        
    },
    fromcurrent: {
        valType: 'boolean',
        dflt: false,
        
        
    },
    frame: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 500,
            
        },
        redraw: {
            valType: 'boolean',
            
            dflt: true,
            
        },
    },
    transition: {
        duration: {
            valType: 'number',
            
            min: 0,
            dflt: 500,
            
        },
        easing: {
            valType: 'enumerated',
            dflt: 'cubic-in-out',
            values: [
                'linear',
                'quad',
                'cubic',
                'sin',
                'exp',
                'circle',
                'elastic',
                'back',
                'bounce',
                'linear-in',
                'quad-in',
                'cubic-in',
                'sin-in',
                'exp-in',
                'circle-in',
                'elastic-in',
                'back-in',
                'bounce-in',
                'linear-out',
                'quad-out',
                'cubic-out',
                'sin-out',
                'exp-out',
                'circle-out',
                'elastic-out',
                'back-out',
                'bounce-out',
                'linear-in-out',
                'quad-in-out',
                'cubic-in-out',
                'sin-in-out',
                'exp-in-out',
                'circle-in-out',
                'elastic-in-out',
                'back-in-out',
                'bounce-in-out'
            ],
            
            
        },
    }
};

},{}],202:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../lib');

/** Convenience wrapper for making array container logic DRY and consistent
 *
 * @param {object} parentObjIn
 *  user input object where the container in question is linked
 *  (i.e. either a user trace object or the user layout object)
 *
 * @param {object} parentObjOut
 *  full object where the coerced container will be linked
 *  (i.e. either a full trace object or the full layout object)
 *
 * @param {object} opts
 *  options object:
 *   - name {string}
 *      name of the key linking the container in question
 *   - handleItemDefaults {function}
 *      defaults method to be called on each item in the array container in question
 *
 *      Its arguments are:
 *          - itemIn {object} item in user layout
 *          - itemOut {object} item in full layout
 *          - parentObj {object} (as in closure)
 *          - opts {object} (as in closure)
 *          - itemOpts {object}
 *              - itemIsNotPlainObject {boolean}
 * N.B.
 *
 *  - opts is passed to handleItemDefaults so it can also store
 *    links to supplementary data (e.g. fullData for layout components)
 *
 */
module.exports = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) {
    var name = opts.name;

    var previousContOut = parentObjOut[name];

    var contIn = Lib.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [],
        contOut = parentObjOut[name] = [],
        i;

    for(i = 0; i < contIn.length; i++) {
        var itemIn = contIn[i],
            itemOut = {},
            itemOpts = {};

        if(!Lib.isPlainObject(itemIn)) {
            itemOpts.itemIsNotPlainObject = true;
            itemIn = {};
        }

        opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts, itemOpts);

        itemOut._input = itemIn;
        itemOut._index = i;

        contOut.push(itemOut);
    }

    // in case this array gets its defaults rebuilt independent of the whole layout,
    // relink the private keys just for this array.
    if(Lib.isArrayOrTypedArray(previousContOut)) {
        var len = Math.min(previousContOut.length, contOut.length);
        for(i = 0; i < len; i++) {
            Lib.relinkPrivateKeys(contOut[i], previousContOut[i]);
        }
    }
};

},{"../lib":164}],203:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fxAttrs = require('../components/fx/attributes');

module.exports = {
    type: {
        valType: 'enumerated',
        
        values: [],     // listed dynamically
        dflt: 'scatter',
        editType: 'calc+clearAxisTypes'
    },
    visible: {
        valType: 'enumerated',
        values: [true, false, 'legendonly'],
        
        dflt: true,
        editType: 'calc',
        
    },
    showlegend: {
        valType: 'boolean',
        
        dflt: true,
        editType: 'style',
        
    },
    legendgroup: {
        valType: 'string',
        
        dflt: '',
        editType: 'style',
        
    },
    opacity: {
        valType: 'number',
        
        min: 0,
        max: 1,
        dflt: 1,
        editType: 'style',
        
    },
    name: {
        valType: 'string',
        
        editType: 'style',
        
    },
    uid: {
        valType: 'string',
        
        dflt: '',
        editType: 'calc'
    },
    ids: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    customdata: {
        valType: 'data_array',
        editType: 'calc',
        
    },

    // N.B. these cannot be 'data_array' as they do not have the same length as
    // other data arrays and arrayOk attributes in general
    //
    // Maybe add another valType:
    // https://github.com/plotly/plotly.js/issues/1894
    selectedpoints: {
        valType: 'any',
        
        editType: 'calc',
        
    },

    hoverinfo: {
        valType: 'flaglist',
        
        flags: ['x', 'y', 'z', 'text', 'name'],
        extras: ['all', 'none', 'skip'],
        arrayOk: true,
        dflt: 'all',
        editType: 'none',
        
    },
    hoverlabel: fxAttrs.hoverlabel,
    stream: {
        token: {
            valType: 'string',
            noBlank: true,
            strict: true,
            
            editType: 'calc',
            
        },
        maxpoints: {
            valType: 'number',
            min: 0,
            max: 10000,
            dflt: 500,
            
            editType: 'calc',
            
        },
        editType: 'calc'
    },
    transforms: {
        _isLinkedToArray: 'transform',
        editType: 'calc',
        
    }
};

},{"../components/fx/attributes":77}],204:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


module.exports = {
    xaxis: {
        valType: 'subplotid',
        
        dflt: 'x',
        editType: 'calc+clearAxisTypes',
        
    },
    yaxis: {
        valType: 'subplotid',
        
        dflt: 'y',
        editType: 'calc+clearAxisTypes',
        
    }
};

},{}],205:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');
var FP_SAFE = require('../../constants/numerical').FP_SAFE;

module.exports = {
    getAutoRange: getAutoRange,
    makePadFn: makePadFn,
    doAutoRange: doAutoRange,
    expand: expand
};

// Find the autorange for this axis
//
// assumes ax._min and ax._max have already been set by calling axes.expand
// using calcdata from all traces. These are arrays of objects:
// {
//    val: calcdata value,
//    pad: extra pixels beyond this value,
//    extrapad: bool, does this point want 5% extra padding
// }
//
// Returns an array of [min, max]. These are calcdata for log and category axes
// and data for linear and date axes.
//
// TODO: we want to change log to data as well, but it's hard to do this
// maintaining backward compatibility. category will always have to use calcdata
// though, because otherwise values between categories (or outside all categories)
// would be impossible.
function getAutoRange(ax) {
    var newRange = [];
    var minmin = ax._min[0].val;
    var maxmax = ax._max[0].val;
    var mbest = 0;
    var axReverse = false;

    var getPad = makePadFn(ax);

    var i, j, minpt, maxpt, minbest, maxbest, dp, dv;

    for(i = 1; i < ax._min.length; i++) {
        if(minmin !== maxmax) break;
        minmin = Math.min(minmin, ax._min[i].val);
    }
    for(i = 1; i < ax._max.length; i++) {
        if(minmin !== maxmax) break;
        maxmax = Math.max(maxmax, ax._max[i].val);
    }

    if(ax.range) {
        var rng = Lib.simpleMap(ax.range, ax.r2l);
        axReverse = rng[1] < rng[0];
    }

    // one-time setting to easily reverse the axis
    // when plotting from code
    if(ax.autorange === 'reversed') {
        axReverse = true;
        ax.autorange = true;
    }

    for(i = 0; i < ax._min.length; i++) {
        minpt = ax._min[i];
        for(j = 0; j < ax._max.length; j++) {
            maxpt = ax._max[j];
            dv = maxpt.val - minpt.val;
            dp = ax._length - getPad(minpt) - getPad(maxpt);
            if(dv > 0 && dp > 0 && dv / dp > mbest) {
                minbest = minpt;
                maxbest = maxpt;
                mbest = dv / dp;
            }
        }
    }

    if(minmin === maxmax) {
        var lower = minmin - 1;
        var upper = minmin + 1;
        if(ax.rangemode === 'tozero') {
            newRange = minmin < 0 ? [lower, 0] : [0, upper];
        }
        else if(ax.rangemode === 'nonnegative') {
            newRange = [Math.max(0, lower), Math.max(0, upper)];
        }
        else {
            newRange = [lower, upper];
        }
    }
    else if(mbest) {
        if(ax.type === 'linear' || ax.type === '-') {
            if(ax.rangemode === 'tozero') {
                if(minbest.val >= 0) {
                    minbest = {val: 0, pad: 0};
                }
                if(maxbest.val <= 0) {
                    maxbest = {val: 0, pad: 0};
                }
            }
            else if(ax.rangemode === 'nonnegative') {
                if(minbest.val - mbest * getPad(minbest) < 0) {
                    minbest = {val: 0, pad: 0};
                }
                if(maxbest.val < 0) {
                    maxbest = {val: 1, pad: 0};
                }
            }

            // in case it changed again...
            mbest = (maxbest.val - minbest.val) /
                (ax._length - getPad(minbest) - getPad(maxbest));

        }

        newRange = [
            minbest.val - mbest * getPad(minbest),
            maxbest.val + mbest * getPad(maxbest)
        ];
    }

    // don't let axis have zero size, while still respecting tozero and nonnegative
    if(newRange[0] === newRange[1]) {
        if(ax.rangemode === 'tozero') {
            if(newRange[0] < 0) {
                newRange = [newRange[0], 0];
            }
            else if(newRange[0] > 0) {
                newRange = [0, newRange[0]];
            }
            else {
                newRange = [0, 1];
            }
        }
        else {
            newRange = [newRange[0] - 1, newRange[0] + 1];
            if(ax.rangemode === 'nonnegative') {
                newRange[0] = Math.max(0, newRange[0]);
            }
        }
    }

    // maintain reversal
    if(axReverse) newRange.reverse();

    return Lib.simpleMap(newRange, ax.l2r || Number);
}

/*
 * calculate the pixel padding for ax._min and ax._max entries with
 * optional extrapad as 5% of the total axis length
 */
function makePadFn(ax) {
    // 5% padding for points that specify extrapad: true
    var extrappad = ax._length / 20;

    // domain-constrained axes: base extrappad on the unconstrained
    // domain so it's consistent as the domain changes
    if((ax.constrain === 'domain') && ax._inputDomain) {
        extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) /
            (ax.domain[1] - ax.domain[0]);
    }

    return function getPad(pt) { return pt.pad + (pt.extrapad ? extrappad : 0); };
}

function doAutoRange(ax) {
    if(!ax._length) ax.setScale();

    // TODO do we really need this?
    var hasDeps = (ax._min && ax._max && ax._min.length && ax._max.length);
    var axIn;

    if(ax.autorange && hasDeps) {
        ax.range = getAutoRange(ax);

        ax._r = ax.range.slice();
        ax._rl = Lib.simpleMap(ax._r, ax.r2l);

        // doAutoRange will get called on fullLayout,
        // but we want to report its results back to layout

        axIn = ax._input;
        axIn.range = ax.range.slice();
        axIn.autorange = ax.autorange;
    }

    if(ax._anchorAxis && ax._anchorAxis.rangeslider) {
        var axeRangeOpts = ax._anchorAxis.rangeslider[ax._name];
        if(axeRangeOpts) {
            if(axeRangeOpts.rangemode === 'auto') {
                if(hasDeps) {
                    axeRangeOpts.range = getAutoRange(ax);
                } else {
                    axeRangeOpts.range = ax._rangeInitial ? ax._rangeInitial.slice() : ax.range.slice();
                }
            }
        }
        axIn = ax._anchorAxis._input;
        axIn.rangeslider[ax._name] = Lib.extendFlat({}, axeRangeOpts);
    }
}

function needsAutorange(ax) {
    return ax.autorange || ax._rangesliderAutorange;
}

/*
 * expand: if autoranging, include new data in the outer limits for this axis.
 * Note that `expand` is called during `calc`, when we don't yet know the axis
 * length; all the inputs should be based solely on the trace data, nothing
 * about the axis layout.
 * Note that `ppad` and `vpad` as well as their asymmetric variants refer to
 * the before and after padding of the passed `data` array, not to the whole axis.
 *
 * @param {object} ax: the axis being expanded. The result will be more entries
 *      in ax._min and ax._max if necessary to include the new data
 * @param {array} data: an array of numbers (ie already run through ax.d2c)
 * @param {object} options: available keys are:
 *      vpad: (number or number array) pad values (data value +-vpad)
 *      ppad: (number or number array) pad pixels (pixel location +-ppad)
 *      ppadplus, ppadminus, vpadplus, vpadminus:
 *          separate padding for each side, overrides symmetric
 *      padded: (boolean) add 5% padding to both ends
 *          (unless one end is overridden by tozero)
 *      tozero: (boolean) make sure to include zero if axis is linear,
 *          and make it a tight bound if possible
 */
function expand(ax, data, options) {
    if(!needsAutorange(ax) || !data) return;

    if(!ax._min) ax._min = [];
    if(!ax._max) ax._max = [];
    if(!options) options = {};
    if(!ax._m) ax.setScale();

    var len = data.length;
    var extrapad = options.padded || false;
    var tozero = options.tozero && (ax.type === 'linear' || ax.type === '-');
    var isLog = (ax.type === 'log');

    var i, j, k, v, di, dmin, dmax, ppadiplus, ppadiminus, includeThis, vmin, vmax;

    var hasArrayOption = false;

    function makePadAccessor(item) {
        if(Array.isArray(item)) {
            hasArrayOption = true;
            return function(i) { return Math.max(Number(item[i]||0), 0); };
        }
        else {
            var v = Math.max(Number(item||0), 0);
            return function() { return v; };
        }
    }

    var ppadplus = makePadAccessor((ax._m > 0 ?
        options.ppadplus : options.ppadminus) || options.ppad || 0);
    var ppadminus = makePadAccessor((ax._m > 0 ?
        options.ppadminus : options.ppadplus) || options.ppad || 0);
    var vpadplus = makePadAccessor(options.vpadplus || options.vpad);
    var vpadminus = makePadAccessor(options.vpadminus || options.vpad);

    if(!hasArrayOption) {
        // with no arrays other than `data` we don't need to consider
        // every point, only the extreme data points
        vmin = Infinity;
        vmax = -Infinity;

        if(isLog) {
            for(i = 0; i < len; i++) {
                v = data[i];
                // data is not linearized yet so we still have to filter out negative logs
                if(v < vmin && v > 0) vmin = v;
                if(v > vmax && v < FP_SAFE) vmax = v;
            }
        }
        else {
            for(i = 0; i < len; i++) {
                v = data[i];
                if(v < vmin && v > -FP_SAFE) vmin = v;
                if(v > vmax && v < FP_SAFE) vmax = v;
            }
        }

        data = [vmin, vmax];
        len = 2;
    }

    function addItem(i) {
        di = data[i];
        if(!isNumeric(di)) return;
        ppadiplus = ppadplus(i);
        ppadiminus = ppadminus(i);
        vmin = di - vpadminus(i);
        vmax = di + vpadplus(i);
        // special case for log axes: if vpad makes this object span
        // more than an order of mag, clip it to one order. This is so
        // we don't have non-positive errors or absurdly large lower
        // range due to rounding errors
        if(isLog && vmin < vmax / 10) vmin = vmax / 10;

        dmin = ax.c2l(vmin);
        dmax = ax.c2l(vmax);

        if(tozero) {
            dmin = Math.min(0, dmin);
            dmax = Math.max(0, dmax);
        }

        for(k = 0; k < 2; k++) {
            var newVal = k ? dmax : dmin;
            if(goodNumber(newVal)) {
                var extremes = k ? ax._max : ax._min;
                var newPad = k ? ppadiplus : ppadiminus;
                var atLeastAsExtreme = k ? greaterOrEqual : lessOrEqual;

                includeThis = true;
                /*
                 * Take items v from ax._min/_max and compare them to the presently active point:
                 * - Since we don't yet know the relationship between pixels and values
                 *   (that's what we're trying to figure out!) AND we don't yet know how
                 *   many pixels `extrapad` represents (it's going to be 5% of the length,
                 *   but we don't want to have to redo _min and _max just because length changed)
                 *   two point must satisfy three criteria simultaneously for one to supersede the other:
                 *   - at least as extreme a `val`
                 *   - at least as big a `pad`
                 *   - an unpadded point cannot supersede a padded point, but any other combination can
                 *
                 * - If the item supersedes the new point, set includethis false
                 * - If the new pt supersedes the item, delete it from ax._min/_max
                 */
                for(j = 0; j < extremes.length && includeThis; j++) {
                    v = extremes[j];
                    if(atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) {
                        includeThis = false;
                        break;
                    }
                    else if(atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) {
                        extremes.splice(j, 1);
                        j--;
                    }
                }
                if(includeThis) {
                    var clipAtZero = (tozero && newVal === 0);
                    extremes.push({
                        val: newVal,
                        pad: clipAtZero ? 0 : newPad,
                        extrapad: clipAtZero ? false : extrapad
                    });
                }
            }
        }
    }

    // For efficiency covering monotonic or near-monotonic data,
    // check a few points at both ends first and then sweep
    // through the middle
    var iMax = Math.min(6, len);
    for(i = 0; i < iMax; i++) addItem(i);
    for(i = len - 1; i >= iMax; i--) addItem(i);
}

// In order to stop overflow errors, don't consider points
// too close to the limits of js floating point
function goodNumber(v) {
    return isNumeric(v) && Math.abs(v) < FP_SAFE;
}

function lessOrEqual(v0, v1) { return v0 <= v1; }
function greaterOrEqual(v0, v1) { return v0 >= v1; }

},{"../../constants/numerical":145,"../../lib":164,"fast-isnumeric":9}],206:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');
var Plots = require('../../plots/plots');

var Registry = require('../../registry');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');
var Titles = require('../../components/titles');
var Color = require('../../components/color');
var Drawing = require('../../components/drawing');

var constants = require('../../constants/numerical');
var ONEAVGYEAR = constants.ONEAVGYEAR;
var ONEAVGMONTH = constants.ONEAVGMONTH;
var ONEDAY = constants.ONEDAY;
var ONEHOUR = constants.ONEHOUR;
var ONEMIN = constants.ONEMIN;
var ONESEC = constants.ONESEC;
var MINUS_SIGN = constants.MINUS_SIGN;
var BADNUM = constants.BADNUM;

var MID_SHIFT = require('../../constants/alignment').MID_SHIFT;
var LINE_SPACING = require('../../constants/alignment').LINE_SPACING;

var axes = module.exports = {};

axes.setConvert = require('./set_convert');
var autoType = require('./axis_autotype');

var axisIds = require('./axis_ids');
axes.id2name = axisIds.id2name;
axes.name2id = axisIds.name2id;
axes.cleanId = axisIds.cleanId;
axes.list = axisIds.list;
axes.listIds = axisIds.listIds;
axes.getFromId = axisIds.getFromId;
axes.getFromTrace = axisIds.getFromTrace;

var autorange = require('./autorange');
axes.expand = autorange.expand;
axes.getAutoRange = autorange.getAutoRange;

/*
 * find the list of possible axes to reference with an xref or yref attribute
 * and coerce it to that list
 *
 * attr: the attribute we're generating a reference for. Should end in 'x' or 'y'
 *     but can be prefixed, like 'ax' for annotation's arrow x
 * dflt: the default to coerce to, or blank to use the first axis (falling back on
 *     extraOption if there is no axis)
 * extraOption: aside from existing axes with this letter, what non-axis value is allowed?
 *     Only required if it's different from `dflt`
 */
axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) {
    var axLetter = attr.charAt(attr.length - 1);
    var axlist = gd._fullLayout._subplots[axLetter + 'axis'];
    var refAttr = attr + 'ref';
    var attrDef = {};

    if(!dflt) dflt = axlist[0] || extraOption;
    if(!extraOption) extraOption = dflt;

    // data-ref annotations are not supported in gl2d yet

    attrDef[refAttr] = {
        valType: 'enumerated',
        values: axlist.concat(extraOption ? [extraOption] : []),
        dflt: dflt
    };

    // xref, yref
    return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
};

/*
 * coerce position attributes (range-type) that can be either on axes or absolute
 * (paper or pixel) referenced. The biggest complication here is that we don't know
 * before looking at the axis whether the value must be a number or not (it may be
 * a date string), so we can't use the regular valType='number' machinery
 *
 * axRef (string): the axis this position is referenced to, or:
 *     paper: fraction of the plot area
 *     pixel: pixels relative to some starting position
 * attr (string): the attribute in containerOut we are coercing
 * dflt (number): the default position, as a fraction or pixels. If the attribute
 *     is to be axis-referenced, this will be converted to an axis data value
 *
 * Also cleans the values, since the attribute definition itself has to say
 * valType: 'any' to handle date axes. This allows us to accept:
 * - for category axes: category names, and convert them here into serial numbers.
 *   Note that this will NOT work for axis range endpoints, because we don't know
 *   the category list yet (it's set by ax.makeCalcdata during calc)
 *   but it works for component (note, shape, images) positions.
 * - for date axes: JS Dates or milliseconds, and convert to date strings
 * - for other types: coerce them to numbers
 */
axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) {
    var cleanPos, pos;

    if(axRef === 'paper' || axRef === 'pixel') {
        cleanPos = Lib.ensureNumber;
        pos = coerce(attr, dflt);
    } else {
        var ax = axes.getFromId(gd, axRef);
        dflt = ax.fraction2r(dflt);
        pos = coerce(attr, dflt);
        cleanPos = ax.cleanPos;
    }

    containerOut[attr] = cleanPos(pos);
};

axes.cleanPosition = function(pos, gd, axRef) {
    var cleanPos = (axRef === 'paper' || axRef === 'pixel') ?
        Lib.ensureNumber :
        axes.getFromId(gd, axRef).cleanPos;

    return cleanPos(pos);
};

var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) {
    var ax;

    // If target points to an axis, use the type we already have for that
    // axis to find the data type. Otherwise use the values to autotype.
    var d2cTarget = (target === 'x' || target === 'y' || target === 'z') ?
        target :
        targetArray;

    // In the case of an array target, make a mock data array
    // and call supplyDefaults to the data type and
    // setup the data-to-calc method.
    if(Array.isArray(d2cTarget)) {
        ax = {
            type: autoType(targetArray),
            _categories: []
        };
        axes.setConvert(ax);

        // build up ax._categories (usually done during ax.makeCalcdata()
        if(ax.type === 'category') {
            for(var i = 0; i < targetArray.length; i++) {
                ax.d2c(targetArray[i]);
            }
        }
    } else {
        ax = axes.getFromTrace(gd, trace, d2cTarget);
    }

    // if 'target' has corresponding axis
    // -> use setConvert method
    if(ax) return {d2c: ax.d2c, c2d: ax.c2d};

    // special case for 'ids'
    // -> cast to String
    if(d2cTarget === 'ids') return {d2c: toString, c2d: toString};

    // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size')
    // -> cast to Number

    return {d2c: toNum, c2d: toNum};
};

function toNum(v) { return +v; }
function toString(v) { return String(v); }

axes.getDataToCoordFunc = function(gd, trace, target, targetArray) {
    return getDataConversions(gd, trace, target, targetArray).d2c;
};

// get counteraxis letter for this axis (name or id)
// this can also be used as the id for default counter axis
axes.counterLetter = function(id) {
    var axLetter = id.charAt(0);
    if(axLetter === 'x') return 'y';
    if(axLetter === 'y') return 'x';
};

// incorporate a new minimum difference and first tick into
// forced
// note that _forceTick0 is linearized, so needs to be turned into
// a range value for setting tick0
axes.minDtick = function(ax, newDiff, newFirst, allow) {
    // doesn't make sense to do forced min dTick on log or category axes,
    // and the plot itself may decide to cancel (ie non-grouped bars)
    if(['log', 'category'].indexOf(ax.type) !== -1 || !allow) {
        ax._minDtick = 0;
    }
    // undefined means there's nothing there yet
    else if(ax._minDtick === undefined) {
        ax._minDtick = newDiff;
        ax._forceTick0 = newFirst;
    }
    else if(ax._minDtick) {
        // existing minDtick is an integer multiple of newDiff
        // (within rounding err)
        // and forceTick0 can be shifted to newFirst
        if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 &&
                (((newFirst - ax._forceTick0) / newDiff % 1) +
                    1.000001) % 1 < 2e-6) {
            ax._minDtick = newDiff;
            ax._forceTick0 = newFirst;
        }
        // if the converse is true (newDiff is a multiple of minDtick and
        // newFirst can be shifted to forceTick0) then do nothing - same
        // forcing stands. Otherwise, cancel forced minimum
        else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 ||
                (((newFirst - ax._forceTick0) / ax._minDtick % 1) +
                    1.000001) % 1 > 2e-6) {
            ax._minDtick = 0;
        }
    }
};

// save a copy of the initial axis ranges in fullLayout
// use them in mode bar and dblclick events
axes.saveRangeInitial = function(gd, overwrite) {
    var axList = axes.list(gd, '', true),
        hasOneAxisChanged = false;

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];

        var isNew = (ax._rangeInitial === undefined);
        var hasChanged = (
            isNew || !(
                ax.range[0] === ax._rangeInitial[0] &&
                ax.range[1] === ax._rangeInitial[1]
            )
        );

        if((isNew && ax.autorange === false) || (overwrite && hasChanged)) {
            ax._rangeInitial = ax.range.slice();
            hasOneAxisChanged = true;
        }
    }

    return hasOneAxisChanged;
};

// save a copy of the initial spike visibility
axes.saveShowSpikeInitial = function(gd, overwrite) {
    var axList = axes.list(gd, '', true),
        hasOneAxisChanged = false,
        allSpikesEnabled = 'on';

    for(var i = 0; i < axList.length; i++) {
        var ax = axList[i];

        var isNew = (ax._showSpikeInitial === undefined);
        var hasChanged = (
            isNew || !(
                ax.showspikes === ax._showspikes
            )
        );

        if((isNew) || (overwrite && hasChanged)) {
            ax._showSpikeInitial = ax.showspikes;
            hasOneAxisChanged = true;
        }

        if(allSpikesEnabled === 'on' && !ax.showspikes) {
            allSpikesEnabled = 'off';
        }
    }
    gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
    return hasOneAxisChanged;
};

axes.autoBin = function(data, ax, nbins, is2d, calendar) {
    var dataMin = Lib.aggNums(Math.min, null, data),
        dataMax = Lib.aggNums(Math.max, null, data);

    if(!calendar) calendar = ax.calendar;

    if(ax.type === 'category') {
        return {
            start: dataMin - 0.5,
            end: dataMax + 0.5,
            size: 1,
            _dataSpan: dataMax - dataMin,
        };
    }

    var size0;
    if(nbins) size0 = ((dataMax - dataMin) / nbins);
    else {
        // totally auto: scale off std deviation so the highest bin is
        // somewhat taller than the total number of bins, but don't let
        // the size get smaller than the 'nice' rounded down minimum
        // difference between values
        var distinctData = Lib.distinctVals(data),
            msexp = Math.pow(10, Math.floor(
                Math.log(distinctData.minDiff) / Math.LN10)),
            minSize = msexp * Lib.roundUp(
                distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true);
        size0 = Math.max(minSize, 2 * Lib.stdev(data) /
            Math.pow(data.length, is2d ? 0.25 : 0.4));

        // fallback if ax.d2c output BADNUMs
        // e.g. when user try to plot categorical bins
        // on a layout.xaxis.type: 'linear'
        if(!isNumeric(size0)) size0 = 1;
    }

    // piggyback off autotick code to make "nice" bin sizes
    var dummyAx;
    if(ax.type === 'log') {
        dummyAx = {
            type: 'linear',
            range: [dataMin, dataMax]
        };
    }
    else {
        dummyAx = {
            type: ax.type,
            range: Lib.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar),
            calendar: calendar
        };
    }
    axes.setConvert(dummyAx);

    axes.autoTicks(dummyAx, size0);
    var binStart = axes.tickIncrement(
            axes.tickFirst(dummyAx), dummyAx.dtick, 'reverse', calendar);
    var binEnd, bincount;

    // check for too many data points right at the edges of bins
    // (>50% within 1% of bin edges) or all data points integral
    // and offset the bins accordingly
    if(typeof dummyAx.dtick === 'number') {
        binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax);

        bincount = 1 + Math.floor((dataMax - binStart) / dummyAx.dtick);
        binEnd = binStart + bincount * dummyAx.dtick;
    }
    else {
        // month ticks - should be the only nonlinear kind we have at this point.
        // dtick (as supplied by axes.autoTick) only has nonlinear values on
        // date and log axes, but even if you display a histogram on a log axis
        // we bin it on a linear axis (which one could argue against, but that's
        // a separate issue)
        if(dummyAx.dtick.charAt(0) === 'M') {
            binStart = autoShiftMonthBins(binStart, data, dummyAx.dtick, dataMin, calendar);
        }

        // calculate the endpoint for nonlinear ticks - you have to
        // just increment until you're done
        binEnd = binStart;
        bincount = 0;
        while(binEnd <= dataMax) {
            binEnd = axes.tickIncrement(binEnd, dummyAx.dtick, false, calendar);
            bincount++;
        }
    }

    return {
        start: ax.c2r(binStart, 0, calendar),
        end: ax.c2r(binEnd, 0, calendar),
        size: dummyAx.dtick,
        _dataSpan: dataMax - dataMin
    };
};


function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) {
    var edgecount = 0,
        midcount = 0,
        intcount = 0,
        blankCount = 0;

    function nearEdge(v) {
        // is a value within 1% of a bin edge?
        return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2;
    }

    for(var i = 0; i < data.length; i++) {
        if(data[i] % 1 === 0) intcount++;
        else if(!isNumeric(data[i])) blankCount++;

        if(nearEdge(data[i])) edgecount++;
        if(nearEdge(data[i] + ax.dtick / 2)) midcount++;
    }
    var dataCount = data.length - blankCount;

    if(intcount === dataCount && ax.type !== 'date') {
        // all integers: if bin size is <1, it's because
        // that was specifically requested (large nbins)
        // so respect that... but center the bins containing
        // integers on those integers
        if(ax.dtick < 1) {
            binStart = dataMin - 0.5 * ax.dtick;
        }
        // otherwise start half an integer down regardless of
        // the bin size, just enough to clear up endpoint
        // ambiguity about which integers are in which bins.
        else {
            binStart -= 0.5;
            if(binStart + ax.dtick < dataMin) binStart += ax.dtick;
        }
    }
    else if(midcount < dataCount * 0.1) {
        if(edgecount > dataCount * 0.3 ||
                nearEdge(dataMin) || nearEdge(dataMax)) {
            // lots of points at the edge, not many in the middle
            // shift half a bin
            var binshift = ax.dtick / 2;
            binStart += (binStart + binshift < dataMin) ? binshift : -binshift;
        }
    }
    return binStart;
}


function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) {
    var stats = Lib.findExactDates(data, calendar);
    // number of data points that needs to be an exact value
    // to shift that increment to (near) the bin center
    var threshold = 0.8;

    if(stats.exactDays > threshold) {
        var numMonths = Number(dtick.substr(1));

        if((stats.exactYears > threshold) && (numMonths % 12 === 0)) {
            // The exact middle of a non-leap-year is 1.5 days into July
            // so if we start the bins here, all but leap years will
            // get hover-labeled as exact years.
            binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + ONEDAY * 1.5;
        }
        else if(stats.exactMonths > threshold) {
            // Months are not as clean, but if we shift half the *longest*
            // month (31/2 days) then 31-day months will get labeled exactly
            // and shorter months will get labeled with the correct month
            // but shifted 12-36 hours into it.
            binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + ONEDAY * 15.5;
        }
        else {
            // Shifting half a day is exact, but since these are month bins it
            // will always give a somewhat odd-looking label, until we do something
            // smarter like showing the bin boundaries (or the bounds of the actual
            // data in each bin)
            binStart -= ONEDAY / 2;
        }
        var nextBinStart = axes.tickIncrement(binStart, dtick);

        if(nextBinStart <= dataMin) return nextBinStart;
    }
    return binStart;
}

// ----------------------------------------------------
// Ticks and grids
// ----------------------------------------------------

// ensure we have tick0, dtick, and tick rounding calculated
axes.prepTicks = function(ax) {
    var rng = Lib.simpleMap(ax.range, ax.r2l);

    // calculate max number of (auto) ticks to display based on plot size
    if(ax.tickmode === 'auto' || !ax.dtick) {
        var nt = ax.nticks,
            minPx;
        if(!nt) {
            if(ax.type === 'category') {
                minPx = ax.tickfont ? (ax.tickfont.size || 12) * 1.2 : 15;
                nt = ax._length / minPx;
            }
            else {
                minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
                nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
            }

            // radial axes span half their domain,
            // multiply nticks value by two to get correct number of auto ticks.
            if(ax._name === 'radialaxis') nt *= 2;
        }

        // add a couple of extra digits for filling in ticks when we
        // have explicit tickvals without tick text
        if(ax.tickmode === 'array') nt *= 100;

        axes.autoTicks(ax, Math.abs(rng[1] - rng[0]) / nt);
        // check for a forced minimum dtick
        if(ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
            ax.dtick = ax._minDtick;
            ax.tick0 = ax.l2r(ax._forceTick0);
        }
    }

    // check for missing tick0
    if(!ax.tick0) {
        ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0;
    }

    // now figure out rounding of tick values
    autoTickRound(ax);
};

// calculate the ticks: text, values, positioning
// if ticks are set to automatic, determine the right values (tick0,dtick)
// in any case, set tickround to # of digits to round tick labels to,
// or codes to this effect for log and date scales
axes.calcTicks = function calcTicks(ax) {
    axes.prepTicks(ax);
    var rng = Lib.simpleMap(ax.range, ax.r2l);

    // now that we've figured out the auto values for formatting
    // in case we're missing some ticktext, we can break out for array ticks
    if(ax.tickmode === 'array') return arrayTicks(ax);

    // find the first tick
    ax._tmin = axes.tickFirst(ax);

    // add a tiny bit so we get ticks which may have rounded out
    var startTick = rng[0] * 1.0001 - rng[1] * 0.0001;
    var endTick = rng[1] * 1.0001 - rng[0] * 0.0001;
    // check for reversed axis
    var axrev = (rng[1] < rng[0]);

    // No visible ticks? Quit.
    // I've only seen this on category axes with all categories off the edge.
    if((ax._tmin < startTick) !== axrev) return [];

    // return the full set of tick vals
    var vals = [];
    if(ax.type === 'category') {
        endTick = (axrev) ? Math.max(-0.5, endTick) :
            Math.min(ax._categories.length - 0.5, endTick);
    }

    var xPrevious = null;
    var maxTicks = Math.max(1000, ax._length || 0);
    for(var x = ax._tmin;
            (axrev) ? (x >= endTick) : (x <= endTick);
            x = axes.tickIncrement(x, ax.dtick, axrev, ax.calendar)) {
        // prevent infinite loops - no more than one tick per pixel,
        // and make sure each value is different from the previous
        if(vals.length > maxTicks || x === xPrevious) break;
        xPrevious = x;

        vals.push(x);
    }

    // If same angle over a full circle, the last tick vals is a duplicate.
    // TODO must do something similar for angular date axes.
    if(ax._id === 'angular' && Math.abs(rng[1] - rng[0]) === 360) {
        vals.pop();
    }

    // save the last tick as well as first, so we can
    // show the exponent only on the last one
    ax._tmax = vals[vals.length - 1];

    // for showing the rest of a date when the main tick label is only the
    // latter part: ax._prevDateHead holds what we showed most recently.
    // Start with it cleared and mark that we're in calcTicks (ie calculating a
    // whole string of these so we should care what the previous date head was!)
    ax._prevDateHead = '';
    ax._inCalcTicks = true;

    var ticksOut = new Array(vals.length);
    for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]);

    ax._inCalcTicks = false;

    return ticksOut;
};

function arrayTicks(ax) {
    var vals = ax.tickvals,
        text = ax.ticktext,
        ticksOut = new Array(vals.length),
        rng = Lib.simpleMap(ax.range, ax.r2l),
        r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001,
        r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001,
        tickMin = Math.min(r0expanded, r1expanded),
        tickMax = Math.max(r0expanded, r1expanded),
        vali,
        i,
        j = 0;

    // without a text array, just format the given values as any other ticks
    // except with more precision to the numbers
    if(!Array.isArray(text)) text = [];

    // make sure showing ticks doesn't accidentally add new categories
    var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l;

    // array ticks on log axes always show the full number
    // (if no explicit ticktext overrides it)
    if(ax.type === 'log' && String(ax.dtick).charAt(0) !== 'L') {
        ax.dtick = 'L' + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1);
    }

    for(i = 0; i < vals.length; i++) {
        vali = tickVal2l(vals[i]);
        if(vali > tickMin && vali < tickMax) {
            if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali);
            else ticksOut[j] = tickTextObj(ax, vali, String(text[i]));
            j++;
        }
    }

    if(j < vals.length) ticksOut.splice(j, vals.length - j);

    return ticksOut;
}

var roundBase10 = [2, 5, 10],
    roundBase24 = [1, 2, 3, 6, 12],
    roundBase60 = [1, 2, 5, 10, 15, 30],
    // 2&3 day ticks are weird, but need something btwn 1&7
    roundDays = [1, 2, 3, 7, 14],
    // approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
    // these don't have to be exact, just close enough to round to the right value
    roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1],
    roundLog2 = [-0.301, 0, 0.301, 0.699, 1],
    // N.B. `thetaunit; 'radians' angular axes must be converted to degrees
    roundAngles = [15, 30, 45, 90, 180];

function roundDTick(roughDTick, base, roundingSet) {
    return base * Lib.roundUp(roughDTick / base, roundingSet);
}

// autoTicks: calculate best guess at pleasant ticks for this axis
// inputs:
//      ax - an axis object
//      roughDTick - rough tick spacing (to be turned into a nice round number)
// outputs (into ax):
//   tick0: starting point for ticks (not necessarily on the graph)
//      usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
//   dtick: the actual, nice round tick spacing, usually a little larger than roughDTick
//      if the ticks are spaced linearly (linear scale, categories,
//          log with only full powers, date ticks < month),
//          this will just be a number
//      months: M#
//      years: M# where # is 12*number of years
//      log with linear ticks: L# where # is the linear tick spacing
//      log showing powers plus some intermediates:
//          D1 shows all digits, D2 shows 2 and 5
axes.autoTicks = function(ax, roughDTick) {
    var base;

    function getBase(v) {
        return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10));
    }

    if(ax.type === 'date') {
        ax.tick0 = Lib.dateTick0(ax.calendar);
        // the criteria below are all based on the rough spacing we calculate
        // being > half of the final unit - so precalculate twice the rough val
        var roughX2 = 2 * roughDTick;

        if(roughX2 > ONEAVGYEAR) {
            roughDTick /= ONEAVGYEAR;
            base = getBase(10);
            ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10));
        }
        else if(roughX2 > ONEAVGMONTH) {
            roughDTick /= ONEAVGMONTH;
            ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
        }
        else if(roughX2 > ONEDAY) {
            ax.dtick = roundDTick(roughDTick, ONEDAY, roundDays);
            // get week ticks on sunday
            // this will also move the base tick off 2000-01-01 if dtick is
            // 2 or 3 days... but that's a weird enough case that we'll ignore it.
            ax.tick0 = Lib.dateTick0(ax.calendar, true);
        }
        else if(roughX2 > ONEHOUR) {
            ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24);
        }
        else if(roughX2 > ONEMIN) {
            ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60);
        }
        else if(roughX2 > ONESEC) {
            ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60);
        }
        else {
            // milliseconds
            base = getBase(10);
            ax.dtick = roundDTick(roughDTick, base, roundBase10);
        }
    }
    else if(ax.type === 'log') {
        ax.tick0 = 0;
        var rng = Lib.simpleMap(ax.range, ax.r2l);

        if(roughDTick > 0.7) {
            // only show powers of 10
            ax.dtick = Math.ceil(roughDTick);
        }
        else if(Math.abs(rng[1] - rng[0]) < 1) {
            // span is less than one power of 10
            var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick);

            // ticks on a linear scale, labeled fully
            roughDTick = Math.abs(Math.pow(10, rng[1]) -
                Math.pow(10, rng[0])) / nt;
            base = getBase(10);
            ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
        }
        else {
            // include intermediates between powers of 10,
            // labeled with small digits
            // ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
            ax.dtick = (roughDTick > 0.3) ? 'D2' : 'D1';
        }
    }
    else if(ax.type === 'category') {
        ax.tick0 = 0;
        ax.dtick = Math.ceil(Math.max(roughDTick, 1));
    }
    else if(ax._id === 'angular') {
        ax.tick0 = 0;
        base = 1;
        ax.dtick = roundDTick(roughDTick, base, roundAngles);
    }
    else {
        // auto ticks always start at 0
        ax.tick0 = 0;
        base = getBase(10);
        ax.dtick = roundDTick(roughDTick, base, roundBase10);
    }

    // prevent infinite loops
    if(ax.dtick === 0) ax.dtick = 1;

    // TODO: this is from log axis histograms with autorange off
    if(!isNumeric(ax.dtick) && typeof ax.dtick !== 'string') {
        var olddtick = ax.dtick;
        ax.dtick = 1;
        throw 'ax.dtick error: ' + String(olddtick);
    }
};

// after dtick is already known, find tickround = precision
// to display in tick labels
//   for numeric ticks, integer # digits after . to round to
//   for date ticks, the last date part to show (y,m,d,H,M,S)
//      or an integer # digits past seconds
function autoTickRound(ax) {
    var dtick = ax.dtick;

    ax._tickexponent = 0;
    if(!isNumeric(dtick) && typeof dtick !== 'string') {
        dtick = 1;
    }

    if(ax.type === 'category') {
        ax._tickround = null;
    }
    if(ax.type === 'date') {
        // If tick0 is unusual, give tickround a bit more information
        // not necessarily *all* the information in tick0 though, if it's really odd
        // minimal string length for tick0: 'd' is 10, 'M' is 16, 'S' is 19
        // take off a leading minus (year < 0) and i (intercalary month) so length is consistent
        var tick0ms = ax.r2l(ax.tick0),
            tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ''),
            tick0len = tick0str.length;

        if(String(dtick).charAt(0) === 'M') {
            // any tick0 more specific than a year: alway show the full date
            if(tick0len > 10 || tick0str.substr(5) !== '01-01') ax._tickround = 'd';
            // show the month unless ticks are full multiples of a year
            else ax._tickround = (+(dtick.substr(1)) % 12 === 0) ? 'y' : 'm';
        }
        else if((dtick >= ONEDAY && tick0len <= 10) || (dtick >= ONEDAY * 15)) ax._tickround = 'd';
        else if((dtick >= ONEMIN && tick0len <= 16) || (dtick >= ONEHOUR)) ax._tickround = 'M';
        else if((dtick >= ONESEC && tick0len <= 19) || (dtick >= ONEMIN)) ax._tickround = 'S';
        else {
            // tickround is a number of digits of fractional seconds
            // of any two adjacent ticks, at least one will have the maximum fractional digits
            // of all possible ticks - so take the max. length of tick0 and the next one
            var tick1len = ax.l2r(tick0ms + dtick).replace(/^-/, '').length;
            ax._tickround = Math.max(tick0len, tick1len) - 20;
        }
    }
    else if(isNumeric(dtick) || dtick.charAt(0) === 'L') {
        // linear or log (except D1, D2)
        var rng = ax.range.map(ax.r2d || Number);
        if(!isNumeric(dtick)) dtick = Number(dtick.substr(1));
        // 2 digits past largest digit of dtick
        ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);

        var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1]));

        var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
        if(Math.abs(rangeexp) > 3) {
            if(isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) {
                ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
            }
            else ax._tickexponent = rangeexp;
        }
    }
    // D1 or D2 (log)
    else ax._tickround = null;
}

// months and years don't have constant millisecond values
// (but a year is always 12 months so we only need months)
// log-scale ticks are also not consistently spaced, except
// for pure powers of 10
// numeric ticks always have constant differences, other datetime ticks
// can all be calculated as constant number of milliseconds
axes.tickIncrement = function(x, dtick, axrev, calendar) {
    var axSign = axrev ? -1 : 1;

    // includes linear, all dates smaller than month, and pure 10^n in log
    if(isNumeric(dtick)) return x + axSign * dtick;

    // everything else is a string, one character plus a number
    var tType = dtick.charAt(0),
        dtSigned = axSign * Number(dtick.substr(1));

    // Dates: months (or years - see Lib.incrementMonth)
    if(tType === 'M') return Lib.incrementMonth(x, dtSigned, calendar);

    // Log scales: Linear, Digits
    else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;

    // log10 of 2,5,10, or all digits (logs just have to be
    // close enough to round)
    else if(tType === 'D') {
        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1,
            x2 = x + axSign * 0.01,
            frac = Lib.roundUp(Lib.mod(x2, 1), tickset, axrev);

        return Math.floor(x2) +
            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
    }
    else throw 'unrecognized dtick ' + String(dtick);
};

// calculate the first tick on an axis
axes.tickFirst = function(ax) {
    var r2l = ax.r2l || Number,
        rng = Lib.simpleMap(ax.range, r2l),
        axrev = rng[1] < rng[0],
        sRound = axrev ? Math.floor : Math.ceil,
        // add a tiny extra bit to make sure we get ticks
        // that may have been rounded out
        r0 = rng[0] * 1.0001 - rng[1] * 0.0001,
        dtick = ax.dtick,
        tick0 = r2l(ax.tick0);

    if(isNumeric(dtick)) {
        var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;

        // make sure no ticks outside the category list
        if(ax.type === 'category') {
            tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
        }
        return tmin;
    }

    var tType = dtick.charAt(0),
        dtNum = Number(dtick.substr(1));

    // Dates: months (or years)
    if(tType === 'M') {
        var cnt = 0,
            t0 = tick0,
            t1,
            mult,
            newDTick;

        // This algorithm should work for *any* nonlinear (but close to linear!)
        // tick spacing. Limit to 10 iterations, for gregorian months it's normally <=3.
        while(cnt < 10) {
            t1 = axes.tickIncrement(t0, dtick, axrev, ax.calendar);
            if((t1 - r0) * (t0 - r0) <= 0) {
                // t1 and t0 are on opposite sides of r0! we've succeeded!
                if(axrev) return Math.min(t0, t1);
                return Math.max(t0, t1);
            }
            mult = (r0 - ((t0 + t1) / 2)) / (t1 - t0);
            newDTick = tType + ((Math.abs(Math.round(mult)) || 1) * dtNum);
            t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar);
            cnt++;
        }
        Lib.error('tickFirst did not converge', ax);
        return t0;
    }

    // Log scales: Linear, Digits
    else if(tType === 'L') {
        return Math.log(sRound(
            (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
    }
    else if(tType === 'D') {
        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1,
            frac = Lib.roundUp(Lib.mod(r0, 1), tickset, axrev);

        return Math.floor(r0) +
            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
    }
    else throw 'unrecognized dtick ' + String(dtick);
};

// draw the text for one tick.
// px,py are the location on gd.paper
// prefix is there so the x axis ticks can be dropped a line
// ax is the axis layout, x is the tick value
// hover is a (truthy) flag for whether to show numbers with a bit
// more precision for hovertext
axes.tickText = function(ax, x, hover) {
    var out = tickTextObj(ax, x),
        hideexp,
        arrayMode = ax.tickmode === 'array',
        extraPrecision = hover || arrayMode,
        i,
        tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l;

    if(arrayMode && Array.isArray(ax.ticktext)) {
        var rng = Lib.simpleMap(ax.range, ax.r2l),
            minDiff = Math.abs(rng[1] - rng[0]) / 10000;
        for(i = 0; i < ax.ticktext.length; i++) {
            if(Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break;
        }
        if(i < ax.ticktext.length) {
            out.text = String(ax.ticktext[i]);
            return out;
        }
    }

    function isHidden(showAttr) {
        var first_or_last;

        if(showAttr === undefined) return true;
        if(hover) return showAttr === 'none';

        first_or_last = {
            first: ax._tmin,
            last: ax._tmax
        }[showAttr];

        return showAttr !== 'all' && x !== first_or_last;
    }

    if(hover) {
        hideexp = 'never';
    } else {
        hideexp = ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : '';
    }

    if(ax.type === 'date') formatDate(ax, out, hover, extraPrecision);
    else if(ax.type === 'log') formatLog(ax, out, hover, extraPrecision, hideexp);
    else if(ax.type === 'category') formatCategory(ax, out);
    else if(ax._id === 'angular') formatAngle(ax, out, hover, extraPrecision, hideexp);
    else formatLinear(ax, out, hover, extraPrecision, hideexp);

    // add prefix and suffix
    if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
    if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;

    return out;
};

/**
 * create text for a hover label on this axis, with special handling of
 * log axes (where negative values can't be displayed but can appear in hover text)
 *
 * @param {object} ax: the axis to format text for
 * @param {number} val: calcdata value to format
 * @param {Optional(number)} val2: a second value to display
 *
 * @returns {string} `val` formatted as a string appropriate to this axis, or
 *     `val` and `val2` as a range (ie '<val> - <val2>') if `val2` is provided and
 *     it's different from `val`.
 */
axes.hoverLabelText = function(ax, val, val2) {
    if(val2 !== BADNUM && val2 !== val) {
        return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2);
    }

    var logOffScale = (ax.type === 'log' && val <= 0);
    var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text;

    if(logOffScale) {
        return val === 0 ? '0' : MINUS_SIGN + tx;
    }

    // TODO: should we do something special if the axis calendar and
    // the data calendar are different? Somehow display both dates with
    // their system names? Right now it will just display in the axis calendar
    // but users could add the other one as text.
    return tx;
};

function tickTextObj(ax, x, text) {
    var tf = ax.tickfont || {};

    return {
        x: x,
        dx: 0,
        dy: 0,
        text: text || '',
        fontSize: tf.size,
        font: tf.family,
        fontColor: tf.color
    };
}

function formatDate(ax, out, hover, extraPrecision) {
    var tr = ax._tickround,
        fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax);

    if(extraPrecision) {
        // second or sub-second precision: extra always shows max digits.
        // for other fields, extra precision just adds one field.
        if(isNumeric(tr)) tr = 4;
        else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr];
    }

    var dateStr = Lib.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat),
        headStr;

    var splitIndex = dateStr.indexOf('\n');
    if(splitIndex !== -1) {
        headStr = dateStr.substr(splitIndex + 1);
        dateStr = dateStr.substr(0, splitIndex);
    }

    if(extraPrecision) {
        // if extraPrecision led to trailing zeros, strip them off
        // actually, this can lead to removing even more zeros than
        // in the original rounding, but that's fine because in these
        // contexts uniformity is not so important (if there's even
        // anything to be uniform with!)

        // can we remove the whole time part?
        if(dateStr === '00:00:00' || dateStr === '00:00') {
            dateStr = headStr;
            headStr = '';
        }
        else if(dateStr.length === 8) {
            // strip off seconds if they're zero (zero fractional seconds
            // are already omitted)
            // but we never remove minutes and leave just hours
            dateStr = dateStr.replace(/:00$/, '');
        }
    }

    if(headStr) {
        if(hover) {
            // hover puts it all on one line, so headPart works best up front
            // except for year headPart: turn this into "Jan 1, 2000" etc.
            if(tr === 'd') dateStr += ', ' + headStr;
            else dateStr = headStr + (dateStr ? ', ' + dateStr : '');
        }
        else if(!ax._inCalcTicks || (headStr !== ax._prevDateHead)) {
            dateStr += '<br>' + headStr;
            ax._prevDateHead = headStr;
        }
    }

    out.text = dateStr;
}

function formatLog(ax, out, hover, extraPrecision, hideexp) {
    var dtick = ax.dtick,
        x = out.x,
        tickformat = ax.tickformat;

    if(hideexp === 'never') {
        // If this is a hover label, then we must *never* hide the exponent
        // for the sake of display, which could give the wrong value by
        // potentially many orders of magnitude. If hideexp was 'never', then
        // it's now succeeded by preventing the other condition from automating
        // this choice. Thus we can unset it so that the axis formatting takes
        // precedence.
        hideexp = '';
    }

    if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0) !== 'L')) dtick = 'L3';

    if(tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) {
        out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
    }
    else if(isNumeric(dtick) || ((dtick.charAt(0) === 'D') && (Lib.mod(x + 0.01, 1) < 0.1))) {
        var p = Math.round(x);
        if(['e', 'E', 'power'].indexOf(ax.exponentformat) !== -1 ||
                (isSIFormat(ax.exponentformat) && beyondSI(p))) {
            if(p === 0) out.text = 1;
            else if(p === 1) out.text = '10';
            else if(p > 1) out.text = '10<sup>' + p + '</sup>';
            else out.text = '10<sup>' + MINUS_SIGN + -p + '</sup>';

            out.fontSize *= 1.25;
        }
        else {
            out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover');
            if(dtick === 'D1' && ax._id.charAt(0) === 'y') {
                out.dy -= out.fontSize / 6;
            }
        }
    }
    else if(dtick.charAt(0) === 'D') {
        out.text = String(Math.round(Math.pow(10, Lib.mod(x, 1))));
        out.fontSize *= 0.75;
    }
    else throw 'unrecognized dtick ' + String(dtick);

    // if 9's are printed on log scale, move the 10's away a bit
    if(ax.dtick === 'D1') {
        var firstChar = String(out.text).charAt(0);
        if(firstChar === '0' || firstChar === '1') {
            if(ax._id.charAt(0) === 'y') {
                out.dx -= out.fontSize / 4;
            }
            else {
                out.dy += out.fontSize / 2;
                out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) *
                    out.fontSize * (x < 0 ? 0.5 : 0.25);
            }
        }
    }
}

function formatCategory(ax, out) {
    var tt = ax._categories[Math.round(out.x)];
    if(tt === undefined) tt = '';
    out.text = String(tt);
}

function formatLinear(ax, out, hover, extraPrecision, hideexp) {
    if(hideexp === 'never') {
        // If this is a hover label, then we must *never* hide the exponent
        // for the sake of display, which could give the wrong value by
        // potentially many orders of magnitude. If hideexp was 'never', then
        // it's now succeeded by preventing the other condition from automating
        // this choice. Thus we can unset it so that the axis formatting takes
        // precedence.
        hideexp = '';
    } else if(ax.showexponent === 'all' && Math.abs(out.x / ax.dtick) < 1e-6) {
        // don't add an exponent to zero if we're showing all exponents
        // so the only reason you'd show an exponent on zero is if it's the
        // ONLY tick to get an exponent (first or last)
        hideexp = 'hide';
    }
    out.text = numFormat(out.x, ax, hideexp, extraPrecision);
}

function formatAngle(ax, out, hover, extraPrecision, hideexp) {
    if(ax.thetaunit === 'radians' && !hover) {
        var num = out.x / 180;

        if(num === 0) {
            out.text = '0';
        } else {
            var frac = num2frac(num);

            if(frac[1] >= 100) {
                out.text = numFormat(Lib.deg2rad(out.x), ax, hideexp, extraPrecision);
            } else {
                var isNeg = out.x < 0;

                if(frac[1] === 1) {
                    if(frac[0] === 1) out.text = 'π';
                    else out.text = frac[0] + 'π';
                } else {
                    out.text = [
                        '<sup>', frac[0], '</sup>',
                        '⁄',
                        '<sub>', frac[1], '</sub>',
                        'π'
                    ].join('');
                }

                if(isNeg) out.text = MINUS_SIGN + out.text;
            }
        }
    } else {
        out.text = numFormat(out.x, ax, hideexp, extraPrecision);
    }
}

// inspired by
// https://github.com/yisibl/num2fraction/blob/master/index.js
function num2frac(num) {
    function almostEq(a, b) {
        return Math.abs(a - b) <= 1e-6;
    }

    function findGCD(a, b) {
        return almostEq(b, 0) ? a : findGCD(b, a % b);
    }

    function findPrecision(n) {
        var e = 1;
        while(!almostEq(Math.round(n * e) / e, n)) {
            e *= 10;
        }
        return e;
    }

    var precision = findPrecision(num);
    var number = num * precision;
    var gcd = Math.abs(findGCD(number, precision));

    return [
        // numerator
        Math.round(number / gcd),
        // denominator
        Math.round(precision / gcd)
    ];
}

// format a number (tick value) according to the axis settings
// new, more reliable procedure than d3.round or similar:
// add half the rounding increment, then stringify and truncate
// also automatically switch to sci. notation
var SIPREFIXES = ['f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T'];

function isSIFormat(exponentFormat) {
    return exponentFormat === 'SI' || exponentFormat === 'B';
}

// are we beyond the range of common SI prefixes?
// 10^-16 -> 1x10^-16
// 10^-15 -> 1f
// ...
// 10^14 -> 100T
// 10^15 -> 1x10^15
// 10^16 -> 1x10^16
function beyondSI(exponent) {
    return exponent > 14 || exponent < -15;
}

function numFormat(v, ax, fmtoverride, hover) {
        // negative?
    var isNeg = v < 0,
        // max number of digits past decimal point to show
        tickRound = ax._tickround,
        exponentFormat = fmtoverride || ax.exponentformat || 'B',
        exponent = ax._tickexponent,
        tickformat = axes.getTickFormat(ax),
        separatethousands = ax.separatethousands;

    // special case for hover: set exponent just for this value, and
    // add a couple more digits of precision over tick labels
    if(hover) {
        // make a dummy axis obj to get the auto rounding and exponent
        var ah = {
            exponentformat: exponentFormat,
            dtick: ax.showexponent === 'none' ? ax.dtick :
                (isNumeric(v) ? Math.abs(v) || 1 : 1),
            // if not showing any exponents, don't change the exponent
            // from what we calculate
            range: ax.showexponent === 'none' ? ax.range.map(ax.r2d) : [0, v || 1]
        };
        autoTickRound(ah);
        tickRound = (Number(ah._tickround) || 0) + 4;
        exponent = ah._tickexponent;
        if(ax.hoverformat) tickformat = ax.hoverformat;
    }

    if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN);

    // 'epsilon' - rounding increment
    var e = Math.pow(10, -tickRound) / 2;

    // exponentFormat codes:
    // 'e' (1.2e+6, default)
    // 'E' (1.2E+6)
    // 'SI' (1.2M)
    // 'B' (same as SI except 10^9=B not G)
    // 'none' (1200000)
    // 'power' (1.2x10^6)
    // 'hide' (1.2, use 3rd argument=='hide' to eg
    //      only show exponent on last tick)
    if(exponentFormat === 'none') exponent = 0;

    // take the sign out, put it back manually at the end
    // - makes cases easier
    v = Math.abs(v);
    if(v < e) {
        // 0 is just 0, but may get exponent if it's the last tick
        v = '0';
        isNeg = false;
    }
    else {
        v += e;
        // take out a common exponent, if any
        if(exponent) {
            v *= Math.pow(10, -exponent);
            tickRound += exponent;
        }
        // round the mantissa
        if(tickRound === 0) v = String(Math.floor(v));
        else if(tickRound < 0) {
            v = String(Math.round(v));
            v = v.substr(0, v.length + tickRound);
            for(var i = tickRound; i < 0; i++) v += '0';
        }
        else {
            v = String(v);
            var dp = v.indexOf('.') + 1;
            if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, '');
        }
        // insert appropriate decimal point and thousands separator
        v = Lib.numSeparate(v, ax._separators, separatethousands);
    }

    // add exponent
    if(exponent && exponentFormat !== 'hide') {
        if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power';

        var signedExponent;
        if(exponent < 0) signedExponent = MINUS_SIGN + -exponent;
        else if(exponentFormat !== 'power') signedExponent = '+' + exponent;
        else signedExponent = String(exponent);

        if(exponentFormat === 'e') {
            v += 'e' + signedExponent;
        }
        else if(exponentFormat === 'E') {
            v += 'E' + signedExponent;
        }
        else if(exponentFormat === 'power') {
            v += '×10<sup>' + signedExponent + '</sup>';
        }
        else if(exponentFormat === 'B' && exponent === 9) {
            v += 'B';
        }
        else if(isSIFormat(exponentFormat)) {
            v += SIPREFIXES[exponent / 3 + 5];
        }
    }

    // put sign back in and return
    // replace standard minus character (which is technically a hyphen)
    // with a true minus sign
    if(isNeg) return MINUS_SIGN + v;
    return v;
}

axes.getTickFormat = function(ax) {
    var i;

    function convertToMs(dtick) {
        return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH;
    }

    function compareLogTicks(left, right) {
        var priority = ['L', 'D'];
        if(typeof left === typeof right) {
            if(typeof left === 'number') {
                return left - right;
            } else {
                var leftPriority = priority.indexOf(left.charAt(0));
                var rightPriority = priority.indexOf(right.charAt(0));
                if(leftPriority === rightPriority) {
                    return Number(left.replace(/(L|D)/g, '')) - Number(right.replace(/(L|D)/g, ''));
                } else {
                    return leftPriority - rightPriority;
                }
            }
        } else {
            return typeof left === 'number' ? 1 : -1;
        }
    }

    function isProperStop(dtick, range, convert) {
        var convertFn = convert || function(x) { return x;};
        var leftDtick = range[0];
        var rightDtick = range[1];
        return ((!leftDtick && typeof leftDtick !== 'number') || convertFn(leftDtick) <= convertFn(dtick)) &&
               ((!rightDtick && typeof rightDtick !== 'number') || convertFn(rightDtick) >= convertFn(dtick));
    }

    function isProperLogStop(dtick, range) {
        var isLeftDtickNull = range[0] === null;
        var isRightDtickNull = range[1] === null;
        var isDtickInRangeLeft = compareLogTicks(dtick, range[0]) >= 0;
        var isDtickInRangeRight = compareLogTicks(dtick, range[1]) <= 0;
        return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight);
    }

    var tickstop;
    if(ax.tickformatstops && ax.tickformatstops.length > 0) {
        switch(ax.type) {
            case 'date':
            case 'linear': {
                for(i = 0; i < ax.tickformatstops.length; i++) {
                    if(isProperStop(ax.dtick, ax.tickformatstops[i].dtickrange, convertToMs)) {
                        tickstop = ax.tickformatstops[i];
                        break;
                    }
                }
                break;
            }
            case 'log': {
                for(i = 0; i < ax.tickformatstops.length; i++) {
                    if(isProperLogStop(ax.dtick, ax.tickformatstops[i].dtickrange)) {
                        tickstop = ax.tickformatstops[i];
                        break;
                    }
                }
                break;
            }
            default:
        }
    }
    return tickstop ? tickstop.value : ax.tickformat;
};

// getSubplots - extract all subplot IDs we need
// as an array of items like 'xy', 'x2y', 'x2y2'...
// sorted by x (x,x2,x3...) then y
// optionally restrict to only subplots containing axis object ax
axes.getSubplots = function(gd, ax) {
    var subplotObj = gd._fullLayout._subplots;
    var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []);

    var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots;

    out.sort(function(a, b) {
        var aParts = a.substr(1).split('y');
        var bParts = b.substr(1).split('y');

        if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1];
        return +aParts[0] - +bParts[0];
    });

    return out;
};

// find all subplots with axis 'ax'
axes.findSubplotsWithAxis = function(subplots, ax) {
    var axMatch = new RegExp(
        (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$')
    );
    var subplotsWithAxis = [];

    for(var i = 0; i < subplots.length; i++) {
        var sp = subplots[i];
        if(axMatch.test(sp)) subplotsWithAxis.push(sp);
    }

    return subplotsWithAxis;
};

// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings
axes.makeClipPaths = function(gd) {
    var fullLayout = gd._fullLayout;
    var fullWidth = {_offset: 0, _length: fullLayout.width, _id: ''};
    var fullHeight = {_offset: 0, _length: fullLayout.height, _id: ''};
    var xaList = axes.list(gd, 'x', true);
    var yaList = axes.list(gd, 'y', true);
    var clipList = [];
    var i, j;

    for(i = 0; i < xaList.length; i++) {
        clipList.push({x: xaList[i], y: fullHeight});
        for(j = 0; j < yaList.length; j++) {
            if(i === 0) clipList.push({x: fullWidth, y: yaList[j]});
            clipList.push({x: xaList[i], y: yaList[j]});
        }
    }

    // selectors don't work right with camelCase tags,
    // have to use class instead
    // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I
    var axClips = fullLayout._clips.selectAll('.axesclip')
        .data(clipList, function(d) { return d.x._id + d.y._id; });

    axClips.enter().append('clipPath')
        .classed('axesclip', true)
        .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; })
      .append('rect');

    axClips.exit().remove();

    axClips.each(function(d) {
        d3.select(this).select('rect').attr({
            x: d.x._offset || 0,
            y: d.y._offset || 0,
            width: d.x._length || 1,
            height: d.y._length || 1
        });
    });
};

// doTicks: draw ticks, grids, and tick labels
// axid: 'x', 'y', 'x2' etc,
//     blank to do all,
//     'redraw' to force full redraw, and reset:
//          ax._r (stored range for use by zoom/pan)
//          ax._rl (stored linearized range for use by zoom/pan)
//     or can pass in an axis object directly
axes.doTicks = function(gd, axid, skipTitle) {
    var fullLayout = gd._fullLayout;
    var ax;
    var independent = false;

    // allow passing an independent axis object instead of id
    if(typeof axid === 'object') {
        ax = axid;
        axid = ax._id;
        independent = true;
    }
    else {
        ax = axes.getFromId(gd, axid);

        if(axid === 'redraw') {
            fullLayout._paper.selectAll('g.subplot').each(function(subplot) {
                var plotinfo = fullLayout._plots[subplot];
                var xa = plotinfo.xaxis;
                var ya = plotinfo.yaxis;

                plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove();
                plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').remove();
                if(plotinfo.gridlayer) plotinfo.gridlayer.selectAll('path').remove();
                if(plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll('path').remove();
                fullLayout._infolayer.select('.g-' + xa._id + 'title').remove();
                fullLayout._infolayer.select('.g-' + ya._id + 'title').remove();
            });
        }

        if(!axid || axid === 'redraw') {
            return Lib.syncOrAsync(axes.list(gd, '', true).map(function(ax) {
                return function() {
                    if(!ax._id) return;
                    var axDone = axes.doTicks(gd, ax._id);
                    ax._r = ax.range.slice();
                    ax._rl = Lib.simpleMap(ax._r, ax.r2l);
                    return axDone;
                };
            }));
        }
    }

    // set scaling to pixels
    ax.setScale();

    var axLetter = axid.charAt(0);
    var counterLetter = axes.counterLetter(axid);
    var vals = ax._vals = axes.calcTicks(ax);
    var datafn = function(d) { return [d.text, d.x, ax.mirror, d.font, d.fontSize, d.fontColor].join('_'); };
    var tcls = axid + 'tick';
    var gcls = axid + 'grid';
    var zcls = axid + 'zl';
    var pad = (ax.linewidth || 1) / 2;
    var labelStandoff = (ax.ticks === 'outside' ? ax.ticklen : 0);
    var labelShift = 0;
    var gridWidth = Drawing.crispRound(gd, ax.gridwidth, 1);
    var zeroLineWidth = Drawing.crispRound(gd, ax.zerolinewidth, gridWidth);
    var tickWidth = Drawing.crispRound(gd, ax.tickwidth, 1);
    var sides, transfn, tickpathfn, subplots;
    var tickLabels;
    var i;

    if(ax._counterangle && ax.ticks === 'outside') {
        var caRad = ax._counterangle * Math.PI / 180;
        labelStandoff = ax.ticklen * Math.cos(caRad) + 1;
        labelShift = ax.ticklen * Math.sin(caRad);
    }

    if(ax.showticklabels && (ax.ticks === 'outside' || ax.showline)) {
        labelStandoff += 0.2 * ax.tickfont.size;
    }

    // positioning arguments for x vs y axes
    if(axLetter === 'x') {
        sides = ['bottom', 'top'];
        transfn = ax._transfn || function(d) {
            return 'translate(' + (ax._offset + ax.l2p(d.x)) + ',0)';
        };
        tickpathfn = function(shift, len) {
            if(ax._counterangle) {
                var caRad = ax._counterangle * Math.PI / 180;
                return 'M0,' + shift + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len);
            }
            else return 'M0,' + shift + 'v' + len;
        };
    }
    else if(axLetter === 'y') {
        sides = ['left', 'right'];
        transfn = ax._transfn || function(d) {
            return 'translate(0,' + (ax._offset + ax.l2p(d.x)) + ')';
        };
        tickpathfn = function(shift, len) {
            if(ax._counterangle) {
                var caRad = ax._counterangle * Math.PI / 180;
                return 'M' + shift + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len);
            }
            else return 'M' + shift + ',0h' + len;
        };
    }
    else if(axid === 'angular') {
        sides = ['left', 'right'];
        transfn = ax._transfn;
        tickpathfn = function(shift, len) {
            return 'M' + shift + ',0h' + len;
        };
    }
    else {
        Lib.warn('Unrecognized doTicks axis:', axid);
        return;
    }

    var axside = ax.side || sides[0];
    // which direction do the side[0], side[1], and free ticks go?
    // then we flip if outside XOR y axis
    var ticksign = [-1, 1, axside === sides[1] ? 1 : -1];
    if((ax.ticks !== 'inside') === (axLetter === 'x')) {
        ticksign = ticksign.map(function(v) { return -v; });
    }

    if(!ax.visible) return;

    if(ax._tickFilter) {
        vals = vals.filter(ax._tickFilter);
    }

    // remove zero lines, grid lines, and inside ticks if they're within
    // 1 pixel of the end
    // The key case here is removing zero lines when the axis bound is zero.
    function clipEnds(d) {
        var p = ax.l2p(d.x);
        return (p > 1 && p < ax._length - 1);
    }
    var valsClipped = vals.filter(clipEnds);

    // don't clip angular values
    if(ax._id === 'angular') {
        valsClipped = vals;
    }

    function drawTicks(container, tickpath) {
        var ticks = container.selectAll('path.' + tcls)
            .data(ax.ticks === 'inside' ? valsClipped : vals, datafn);

        if(tickpath && ax.ticks) {
            ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1)
                .classed('crisp', 1)
                .call(Color.stroke, ax.tickcolor)
                .style('stroke-width', tickWidth + 'px')
                .attr('d', tickpath);
            ticks.attr('transform', transfn);
            ticks.exit().remove();
        }
        else ticks.remove();
    }

    function drawLabels(container, position) {
        // tick labels - for now just the main labels.
        // TODO: mirror labels, esp for subplots
        tickLabels = container.selectAll('g.' + tcls).data(vals, datafn);

        if(!isNumeric(position)) {
            tickLabels.remove();
            drawAxTitle();
            return;
        }
        if(!ax.showticklabels) {
            tickLabels.remove();
            drawAxTitle();
            calcBoundingBox();
            return;
        }

        var labelx, labely, labelanchor, labelpos0, flipit;
        if(axLetter === 'x') {
            flipit = (axside === 'bottom') ? 1 : -1;
            labelx = function(d) { return d.dx + labelShift * flipit; };
            labelpos0 = position + (labelStandoff + pad) * flipit;
            labely = function(d) {
                return d.dy + labelpos0 + d.fontSize *
                    ((axside === 'bottom') ? 1 : -0.2);
            };
            labelanchor = function(angle) {
                if(!isNumeric(angle) || angle === 0 || angle === 180) {
                    return 'middle';
                }
                return (angle * flipit < 0) ? 'end' : 'start';
            };
        }
        else if(axLetter === 'y') {
            flipit = (axside === 'right') ? 1 : -1;
            labely = function(d) {
                return d.dy + d.fontSize * MID_SHIFT - labelShift * flipit;
            };
            labelx = function(d) {
                return d.dx + position + (labelStandoff + pad +
                    ((Math.abs(ax.tickangle) === 90) ? d.fontSize / 2 : 0)) * flipit;
            };
            labelanchor = function(angle) {
                if(isNumeric(angle) && Math.abs(angle) === 90) {
                    return 'middle';
                }
                return axside === 'right' ? 'start' : 'end';
            };
        }
        else if(axid === 'angular') {
            ax._labelShift = labelShift;
            ax._labelStandoff = labelStandoff;
            ax._pad = pad;

            labelx = ax._labelx;
            labely = ax._labely;
            labelanchor = ax._labelanchor;
        }

        var maxFontSize = 0,
            autoangle = 0,
            labelsReady = [];
        tickLabels.enter().append('g').classed(tcls, 1)
            .append('text')
                // only so tex has predictable alignment that we can
                // alter later
                .attr('text-anchor', 'middle')
                .each(function(d) {
                    var thisLabel = d3.select(this),
                        newPromise = gd._promises.length;
                    thisLabel
                        .call(svgTextUtils.positionText, labelx(d), labely(d))
                        .call(Drawing.font, d.font, d.fontSize, d.fontColor)
                        .text(d.text)
                        .call(svgTextUtils.convertToTspans, gd);
                    newPromise = gd._promises[newPromise];
                    if(newPromise) {
                        // if we have an async label, we'll deal with that
                        // all here so take it out of gd._promises and
                        // instead position the label and promise this in
                        // labelsReady
                        labelsReady.push(gd._promises.pop().then(function() {
                            positionLabels(thisLabel, ax.tickangle);
                        }));
                    }
                    else {
                        // sync label: just position it now.
                        positionLabels(thisLabel, ax.tickangle);
                    }
                });
        tickLabels.exit().remove();

        tickLabels.each(function(d) {
            maxFontSize = Math.max(maxFontSize, d.fontSize);
        });

        if(axid === 'angular') {
            tickLabels.each(function(d) {
                d3.select(this).select('text')
                    .call(svgTextUtils.positionText, labelx(d), labely(d));
            });
        }

        // How much to shift a multi-line label to center it vertically.
        function getAnchorHeight(lineCount, lineHeight, angle) {
            var h = (lineCount - 1) * lineHeight;
            if(axLetter === 'x') {
                if(angle < -60 || 60 < angle) {
                    return -0.5 * h;
                } else if(axside === 'top') {
                    return -h;
                }
            } else {
                angle *= axside === 'left' ? 1 : -1;
                if(angle < -30) {
                    return -h;
                } else if(angle < 30) {
                    return -0.5 * h;
                }
            }
            return 0;
        }

        function positionLabels(s, angle) {
            s.each(function(d) {
                var anchor = labelanchor(angle, d);
                var thisLabel = d3.select(this),
                    mathjaxGroup = thisLabel.select('.text-math-group'),
                    transform = transfn.call(thisLabel.node(), d) +
                        ((isNumeric(angle) && +angle !== 0) ?
                        (' rotate(' + angle + ',' + labelx(d) + ',' +
                            (labely(d) - d.fontSize / 2) + ')') :
                        '');
                var anchorHeight = getAnchorHeight(
                    svgTextUtils.lineCount(thisLabel),
                    LINE_SPACING * d.fontSize,
                    isNumeric(angle) ? +angle : 0);
                if(anchorHeight) {
                    transform += ' translate(0, ' + anchorHeight + ')';
                }
                if(mathjaxGroup.empty()) {
                    thisLabel.select('text').attr({
                        transform: transform,
                        'text-anchor': anchor
                    });
                }
                else {
                    var mjShift =
                        Drawing.bBox(mathjaxGroup.node()).width *
                            {end: -0.5, start: 0.5}[anchor];
                    mathjaxGroup.attr('transform', transform +
                        (mjShift ? 'translate(' + mjShift + ',0)' : ''));
                }
            });
        }

        // make sure all labels are correctly positioned at their base angle
        // the positionLabels call above is only for newly drawn labels.
        // do this without waiting, using the last calculated angle to
        // minimize flicker, then do it again when we know all labels are
        // there, putting back the prescribed angle to check for overlaps.
        positionLabels(tickLabels, ax._lastangle || ax.tickangle);

        function allLabelsReady() {
            return labelsReady.length && Promise.all(labelsReady);
        }

        function fixLabelOverlaps() {
            positionLabels(tickLabels, ax.tickangle);

            // check for auto-angling if x labels overlap
            // don't auto-angle at all for log axes with
            // base and digit format
            if(axLetter === 'x' && !isNumeric(ax.tickangle) &&
                    (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')) {
                var lbbArray = [];
                tickLabels.each(function(d) {
                    var s = d3.select(this),
                        thisLabel = s.select('.text-math-group'),
                        x = ax.l2p(d.x);
                    if(thisLabel.empty()) thisLabel = s.select('text');

                    var bb = Drawing.bBox(thisLabel.node());

                    lbbArray.push({
                        // ignore about y, just deal with x overlaps
                        top: 0,
                        bottom: 10,
                        height: 10,
                        left: x - bb.width / 2,
                        // impose a 2px gap
                        right: x + bb.width / 2 + 2,
                        width: bb.width + 2
                    });
                });
                for(i = 0; i < lbbArray.length - 1; i++) {
                    if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) {
                        // any overlap at all - set 30 degrees
                        autoangle = 30;
                        break;
                    }
                }
                if(autoangle) {
                    var tickspacing = Math.abs(
                            (vals[vals.length - 1].x - vals[0].x) * ax._m
                        ) / (vals.length - 1);
                    if(tickspacing < maxFontSize * 2.5) {
                        autoangle = 90;
                    }
                    positionLabels(tickLabels, autoangle);
                }
                ax._lastangle = autoangle;
            }

            // update the axis title
            // (so it can move out of the way if needed)
            // TODO: separate out scoot so we don't need to do
            // a full redraw of the title (mostly relevant for MathJax)
            drawAxTitle();
            return axid + ' done';
        }

        function calcBoundingBox() {
            if(ax.showticklabels) {
                var gdBB = gd.getBoundingClientRect();
                var bBox = container.node().getBoundingClientRect();

                /*
                 * the way we're going to use this, the positioning that matters
                 * is relative to the origin of gd. This is important particularly
                 * if gd is scrollable, and may have been scrolled between the time
                 * we calculate this and the time we use it
                 */

                ax._boundingBox = {
                    width: bBox.width,
                    height: bBox.height,
                    left: bBox.left - gdBB.left,
                    right: bBox.right - gdBB.left,
                    top: bBox.top - gdBB.top,
                    bottom: bBox.bottom - gdBB.top
                };
            } else {
                var gs = fullLayout._size;
                var pos;

                // set dummy bbox for ticklabel-less axes

                if(axLetter === 'x') {
                    pos = ax.anchor === 'free' ?
                        gs.t + gs.h * (1 - ax.position) :
                        gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]);

                    ax._boundingBox = {
                        top: pos,
                        bottom: pos,
                        left: ax._offset,
                        right: ax._offset + ax._length,
                        width: ax._length,
                        height: 0
                    };
                } else {
                    pos = ax.anchor === 'free' ?
                        gs.l + gs.w * ax.position :
                        gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]];

                    ax._boundingBox = {
                        left: pos,
                        right: pos,
                        bottom: ax._offset + ax._length,
                        top: ax._offset,
                        height: ax._length,
                        width: 0
                    };
                }
            }

            /*
             * for spikelines: what's the full domain of positions in the
             * opposite direction that are associated with this axis?
             * This means any axes that we make a subplot with, plus the
             * position of the axis itself if it's free.
             */
            if(subplots) {
                var fullRange = ax._counterSpan = [Infinity, -Infinity];

                for(i = 0; i < subplots.length; i++) {
                    var subplot = fullLayout._plots[subplots[i]];
                    var counterAxis = subplot[(axLetter === 'x') ? 'yaxis' : 'xaxis'];

                    extendRange(fullRange, [
                        counterAxis._offset,
                        counterAxis._offset + counterAxis._length
                    ]);
                }

                if(ax.anchor === 'free') {
                    extendRange(fullRange, (axLetter === 'x') ?
                        [ax._boundingBox.bottom, ax._boundingBox.top] :
                        [ax._boundingBox.right, ax._boundingBox.left]);
                }
            }

            function extendRange(range, newRange) {
                range[0] = Math.min(range[0], newRange[0]);
                range[1] = Math.max(range[1], newRange[1]);
            }
        }

        function doAutoMargins() {
            if(!ax.automargin) { return; }
            if(axLetter !== 'x' && axLetter !== 'y') { return; }

            var s = ax.side[0];
            var push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0};

            if(axLetter === 'x') {
                push.y = (ax.anchor === 'free' ? ax.position :
                        ax._anchorAxis.domain[s === 't' ? 1 : 0]);
                push[s] += ax._boundingBox.height;
            }
            else {
                push.x = (ax.anchor === 'free' ? ax.position :
                        ax._anchorAxis.domain[s === 'r' ? 1 : 0]);
                push[s] += ax._boundingBox.width;
            }

            if(ax.title !== fullLayout._dfltTitle[axLetter]) {
                push[s] += ax.titlefont.size;
            }

            var pushKey = ax._name + '.automargin';
            var prevPush = fullLayout._pushmargin[pushKey];
            if(!prevPush || prevPush[s].size < push[s]) {
                Plots.autoMargin(gd, pushKey, push);
            }
        }

        var done = Lib.syncOrAsync([
            allLabelsReady,
            fixLabelOverlaps,
            calcBoundingBox,
            doAutoMargins
        ]);
        if(done && done.then) gd._promises.push(done);
        return done;
    }

    function drawAxTitle() {
        if(skipTitle) return;

        // now this only applies to regular cartesian axes; colorbars and
        // others ALWAYS call doTicks with skipTitle=true so they can
        // configure their own titles.

        // rangeslider takes over a bottom title so drop it here
        if(ax.rangeslider && ax.rangeslider.visible && ax._boundingBox && ax.side === 'bottom') return;

        var avoid = {
            selection: tickLabels,
            side: ax.side
        };
        var axLetter = axid.charAt(0);
        var gs = gd._fullLayout._size;
        var offsetBase = 1.5;
        var fontSize = ax.titlefont.size;

        var transform, counterAxis, x, y;

        if(tickLabels.size()) {
            var translation = Drawing.getTranslate(tickLabels.node().parentNode);
            avoid.offsetLeft = translation.x;
            avoid.offsetTop = translation.y;
        }

        var titleStandoff = 10 + fontSize * offsetBase +
            (ax.linewidth ? ax.linewidth - 1 : 0);

        if(axLetter === 'x') {
            counterAxis = (ax.anchor === 'free') ?
                {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} :
                axisIds.getFromId(gd, ax.anchor);

            x = ax._offset + ax._length / 2;

            if(ax.side === 'top') {
                y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0);
            }
            else {
                y = counterAxis._length + titleStandoff +
                    fontSize * (ax.showticklabels ? 1.5 : 0.5);
            }
            y += counterAxis._offset;

            if(!avoid.side) avoid.side = 'bottom';
        }
        else {
            counterAxis = (ax.anchor === 'free') ?
                {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} :
                axisIds.getFromId(gd, ax.anchor);

            y = ax._offset + ax._length / 2;
            if(ax.side === 'right') {
                x = counterAxis._length + titleStandoff +
                    fontSize * (ax.showticklabels ? 1 : 0.5);
            }
            else {
                x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0);
            }
            x += counterAxis._offset;

            transform = {rotate: '-90', offset: 0};
            if(!avoid.side) avoid.side = 'left';
        }

        Titles.draw(gd, axid + 'title', {
            propContainer: ax,
            propName: ax._name + '.title',
            placeholder: fullLayout._dfltTitle[axLetter],
            avoid: avoid,
            transform: transform,
            attributes: {x: x, y: y, 'text-anchor': 'middle'}
        });
    }

    function traceHasBarsOrFill(trace, subplot) {
        if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false;
        if(Registry.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter]) return true;
        return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter;
    }

    function drawGrid(plotinfo, counteraxis, subplot) {
        if(fullLayout._hasOnlyLargeSploms) return;

        var gridcontainer = plotinfo.gridlayer.selectAll('.' + axid);
        var zlcontainer = plotinfo.zerolinelayer;
        var gridvals = plotinfo['hidegrid' + axLetter] ? [] : valsClipped;
        var gridpath = ax._gridpath || ((axLetter === 'x' ?
                ('M0,' + counteraxis._offset + 'v') :
                ('M' + counteraxis._offset + ',0h')
            ) + counteraxis._length);
        var grid = gridcontainer.selectAll('path.' + gcls)
            .data((ax.showgrid === false) ? [] : gridvals, datafn);
        grid.enter().append('path').classed(gcls, 1)
            .classed('crisp', 1)
            .attr('d', gridpath)
            .each(function(d) {
                if(ax.zeroline && (ax.type === 'linear' || ax.type === '-') &&
                        Math.abs(d.x) < ax.dtick / 100) {
                    d3.select(this).remove();
                }
            });
        grid.attr('transform', transfn)
            .call(Color.stroke, ax.gridcolor || '#ddd')
            .style('stroke-width', gridWidth + 'px');
        if(typeof gridpath === 'function') grid.attr('d', gridpath);
        grid.exit().remove();

        // zero line
        if(zlcontainer) {
            var hasBarsOrFill = false;
            for(var i = 0; i < gd._fullData.length; i++) {
                if(traceHasBarsOrFill(gd._fullData[i], subplot)) {
                    hasBarsOrFill = true;
                    break;
                }
            }
            var rng = Lib.simpleMap(ax.range, ax.r2l),
                showZl = (rng[0] * rng[1] <= 0) && ax.zeroline &&
                (ax.type === 'linear' || ax.type === '-') && gridvals.length &&
                (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline);
            var zl = zlcontainer.selectAll('path.' + zcls)
                .data(showZl ? [{x: 0, id: axid}] : []);
            zl.enter().append('path').classed(zcls, 1).classed('zl', 1)
                .classed('crisp', 1)
                .attr('d', gridpath)
                .each(function() {
                    // use the fact that only one element can enter to trigger a sort.
                    // If several zerolines enter at the same time we will sort once per,
                    // but generally this should be a minimal overhead.
                    zlcontainer.selectAll('path').sort(function(da, db) {
                        return axisIds.idSort(da.id, db.id);
                    });
                });
            zl.attr('transform', transfn)
                .call(Color.stroke, ax.zerolinecolor || Color.defaultLine)
                .style('stroke-width', zeroLineWidth + 'px');
            zl.exit().remove();
        }
    }

    if(independent) {
        drawTicks(ax._axislayer, tickpathfn(ax._pos + pad * ticksign[2], ticksign[2] * ax.ticklen));
        if(ax._counteraxis) {
            var fictionalPlotinfo = {
                gridlayer: ax._gridlayer,
                zerolinelayer: ax._zerolinelayer
            };
            drawGrid(fictionalPlotinfo, ax._counteraxis);
        }
        return drawLabels(ax._axislayer, ax._pos);
    }
    else if(fullLayout._has('cartesian')) {
        subplots = axes.getSubplots(gd, ax);

        // keep track of which subplots (by main conteraxis) we've already
        // drawn grids for, so we don't overdraw overlaying subplots
        var finishedGrids = {};

        subplots.map(function(subplot) {
            var plotinfo = fullLayout._plots[subplot];
            var counterAxis = plotinfo[counterLetter + 'axis'];

            var mainCounterID = counterAxis._mainAxis._id;
            if(finishedGrids[mainCounterID]) return;
            finishedGrids[mainCounterID] = 1;

            drawGrid(plotinfo, counterAxis, subplot);
        });

        var mainSubplot = ax._mainSubplot;
        var mainPlotinfo = fullLayout._plots[mainSubplot];
        var tickSubplots = [];

        if(ax.ticks) {
            var mainSign = ticksign[2];
            var tickpath = tickpathfn(ax._mainLinePosition + pad * mainSign, mainSign * ax.ticklen);
            if(ax._anchorAxis && ax.mirror && ax.mirror !== true) {
                tickpath += tickpathfn(ax._mainMirrorPosition - pad * mainSign, -mainSign * ax.ticklen);
            }
            drawTicks(mainPlotinfo[axLetter + 'axislayer'], tickpath);

            tickSubplots = Object.keys(ax._linepositions || {});
        }

        tickSubplots.map(function(subplot) {
            var plotinfo = fullLayout._plots[subplot];

            var container = plotinfo[axLetter + 'axislayer'];

            // [bottom or left, top or right]
            // free and main are handled above
            var linepositions = ax._linepositions[subplot] || [];

            function tickPathSide(sidei) {
                var tsign = ticksign[sidei];
                return tickpathfn(linepositions[sidei] + pad * tsign, tsign * ax.ticklen);
            }

            drawTicks(container, tickPathSide(0) + tickPathSide(1));
        });

        var mainContainer = mainPlotinfo[axLetter + 'axislayer'];

        return drawLabels(mainContainer, ax._mainLinePosition);
    }
};

// swap all the presentation attributes of the axes showing these traces
axes.swap = function(gd, traces) {
    var axGroups = makeAxisGroups(gd, traces);

    for(var i = 0; i < axGroups.length; i++) {
        swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
    }
};

function makeAxisGroups(gd, traces) {
    var groups = [],
        i,
        j;

    for(i = 0; i < traces.length; i++) {
        var groupsi = [],
            xi = gd._fullData[traces[i]].xaxis,
            yi = gd._fullData[traces[i]].yaxis;
        if(!xi || !yi) continue; // not a 2D cartesian trace?

        for(j = 0; j < groups.length; j++) {
            if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
                groupsi.push(j);
            }
        }

        if(!groupsi.length) {
            groups.push({x: [xi], y: [yi]});
            continue;
        }

        var group0 = groups[groupsi[0]],
            groupj;

        if(groupsi.length > 1) {
            for(j = 1; j < groupsi.length; j++) {
                groupj = groups[groupsi[j]];
                mergeAxisGroups(group0.x, groupj.x);
                mergeAxisGroups(group0.y, groupj.y);
            }
        }
        mergeAxisGroups(group0.x, [xi]);
        mergeAxisGroups(group0.y, [yi]);
    }

    return groups;
}

function mergeAxisGroups(intoSet, fromSet) {
    for(var i = 0; i < fromSet.length; i++) {
        if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
    }
}

function swapAxisGroup(gd, xIds, yIds) {
    var i,
        j,
        xFullAxes = [],
        yFullAxes = [],
        layout = gd.layout;

    for(i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
    for(i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));

    var allAxKeys = Object.keys(xFullAxes[0]),
        noSwapAttrs = [
            'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle'
        ],
        numericTypes = ['linear', 'log'];

    for(i = 0; i < allAxKeys.length; i++) {
        var keyi = allAxKeys[i],
            xVal = xFullAxes[0][keyi],
            yVal = yFullAxes[0][keyi],
            allEqual = true,
            coerceLinearX = false,
            coerceLinearY = false;
        if(keyi.charAt(0) === '_' || typeof xVal === 'function' ||
                noSwapAttrs.indexOf(keyi) !== -1) {
            continue;
        }
        for(j = 1; j < xFullAxes.length && allEqual; j++) {
            var xVali = xFullAxes[j][keyi];
            if(keyi === 'type' && numericTypes.indexOf(xVal) !== -1 &&
                    numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
                // type is special - if we find a mixture of linear and log,
                // coerce them all to linear on flipping
                coerceLinearX = true;
            }
            else if(xVali !== xVal) allEqual = false;
        }
        for(j = 1; j < yFullAxes.length && allEqual; j++) {
            var yVali = yFullAxes[j][keyi];
            if(keyi === 'type' && numericTypes.indexOf(yVal) !== -1 &&
                    numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
                // type is special - if we find a mixture of linear and log,
                // coerce them all to linear on flipping
                coerceLinearY = true;
            }
            else if(yFullAxes[j][keyi] !== yVal) allEqual = false;
        }
        if(allEqual) {
            if(coerceLinearX) layout[xFullAxes[0]._name].type = 'linear';
            if(coerceLinearY) layout[yFullAxes[0]._name].type = 'linear';
            swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle);
        }
    }

    // now swap x&y for any annotations anchored to these x & y
    for(i = 0; i < gd._fullLayout.annotations.length; i++) {
        var ann = gd._fullLayout.annotations[i];
        if(xIds.indexOf(ann.xref) !== -1 &&
                yIds.indexOf(ann.yref) !== -1) {
            Lib.swapAttrs(layout.annotations[i], ['?']);
        }
    }
}

function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) {
    // in case the value is the default for either axis,
    // look at the first axis in each list and see if
    // this key's value is undefined
    var np = Lib.nestedProperty,
        xVal = np(layout[xFullAxes[0]._name], key).get(),
        yVal = np(layout[yFullAxes[0]._name], key).get(),
        i;
    if(key === 'title') {
        // special handling of placeholder titles
        if(xVal === dfltTitle.x) {
            xVal = dfltTitle.y;
        }
        if(yVal === dfltTitle.y) {
            yVal = dfltTitle.x;
        }
    }

    for(i = 0; i < xFullAxes.length; i++) {
        np(layout, xFullAxes[i]._name + '.' + key).set(yVal);
    }
    for(i = 0; i < yFullAxes.length; i++) {
        np(layout, yFullAxes[i]._name + '.' + key).set(xVal);
    }
}

},{"../../components/color":43,"../../components/drawing":68,"../../components/titles":136,"../../constants/alignment":143,"../../constants/numerical":145,"../../lib":164,"../../lib/svg_text_utils":185,"../../plots/plots":245,"../../registry":254,"./autorange":205,"./axis_autotype":207,"./axis_ids":209,"./set_convert":224,"d3":6,"fast-isnumeric":9}],207:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');
var BADNUM = require('../../constants/numerical').BADNUM;

module.exports = function autoType(array, calendar) {
    if(moreDates(array, calendar)) return 'date';
    if(category(array)) return 'category';
    if(linearOK(array)) return 'linear';
    else return '-';
};

// is there at least one number in array? If not, we should leave
// ax.type empty so it can be autoset later
function linearOK(array) {
    if(!array) return false;

    for(var i = 0; i < array.length; i++) {
        if(isNumeric(array[i])) return true;
    }

    return false;
}

// does the array a have mostly dates rather than numbers?
// note: some values can be neither (such as blanks, text)
// 2- or 4-digit integers can be both, so require twice as many
// dates as non-dates, to exclude cases with mostly 2 & 4 digit
// numbers and a few dates
function moreDates(a, calendar) {
    var dcnt = 0,
        ncnt = 0,
        // test at most 1000 points, evenly spaced
        inc = Math.max(1, (a.length - 1) / 1000),
        ai;

    for(var i = 0; i < a.length; i += inc) {
        ai = a[Math.round(i)];
        if(Lib.isDateTime(ai, calendar)) dcnt += 1;
        if(isNumeric(ai)) ncnt += 1;
    }

    return (dcnt > ncnt * 2);
}

// are the (x,y)-values in gd.data mostly text?
// require twice as many categories as numbers
function category(a) {
    // test at most 1000 points
    var inc = Math.max(1, (a.length - 1) / 1000),
        curvenums = 0,
        curvecats = 0,
        ai;

    for(var i = 0; i < a.length; i += inc) {
        ai = a[Math.round(i)];
        if(Lib.cleanNumber(ai) !== BADNUM) curvenums++;
        else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++;
    }

    return curvecats > curvenums * 2;
}

},{"../../constants/numerical":145,"../../lib":164,"fast-isnumeric":9}],208:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');

var layoutAttributes = require('./layout_attributes');
var handleTickValueDefaults = require('./tick_value_defaults');
var handleTickMarkDefaults = require('./tick_mark_defaults');
var handleTickLabelDefaults = require('./tick_label_defaults');
var handleCategoryOrderDefaults = require('./category_order_defaults');
var handleLineGridDefaults = require('./line_grid_defaults');
var setConvert = require('./set_convert');

/**
 * options: object containing:
 *
 *  letter: 'x' or 'y'
 *  title: name of the axis (ie 'Colorbar') to go in default title
 *  font: the default font to inherit
 *  outerTicks: boolean, should ticks default to outside?
 *  showGrid: boolean, should gridlines be shown by default?
 *  noHover: boolean, this axis doesn't support hover effects?
 *  data: the plot data, used to manage categories
 *  bgColor: the plot background color, to calculate default gridline colors
 */
module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
    var letter = options.letter;
    var id = containerOut._id;
    var font = options.font || {};

    var visible = coerce('visible', !options.cheateronly);

    var axType = containerOut.type;

    if(axType === 'date') {
        var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
        handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
    }

    setConvert(containerOut, layoutOut);

    var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));

    // both x and y axes may need autorange done just for the range slider's purposes
    // the logic is complicated to figure this out later, particularly for y axes since
    // the settings can be spread out in the x axes... so instead we'll collect them
    // during supplyDefaults
    containerOut._rangesliderAutorange = false;

    if(autoRange) coerce('rangemode');

    coerce('range');
    containerOut.cleanRange();

    handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);

    if(axType !== 'category' && !options.noHover) coerce('hoverformat');

    if(!visible) return containerOut;

    var dfltColor = coerce('color');
    // if axis.color was provided, use it for fonts too; otherwise,
    // inherit from global font color in case that was provided.
    var dfltFontColor = (dfltColor === containerIn.color) ? dfltColor : font.color;
    // try to get default title from splom trace, fallback to graph-wide value
    var dfltTitle = ((layoutOut._splomAxes || {})[letter] || {})[id] || layoutOut._dfltTitle[letter];

    coerce('title', dfltTitle);
    Lib.coerceFont(coerce, 'titlefont', {
        family: font.family,
        size: Math.round(font.size * 1.2),
        color: dfltFontColor
    });

    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
    handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
    handleTickMarkDefaults(containerIn, containerOut, coerce, options);
    handleLineGridDefaults(containerIn, containerOut, coerce, {
        dfltColor: dfltColor,
        bgColor: options.bgColor,
        showGrid: options.showGrid,
        attributes: layoutAttributes
    });

    if(containerOut.showline || containerOut.ticks) coerce('mirror');

    if(options.automargin) coerce('automargin');

    return containerOut;
};

},{"../../lib":164,"../../registry":254,"./category_order_defaults":210,"./layout_attributes":218,"./line_grid_defaults":220,"./set_convert":224,"./tick_label_defaults":225,"./tick_mark_defaults":226,"./tick_value_defaults":227}],209:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../../registry');

var constants = require('./constants');


// convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
// and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
// completely in favor of just 'x' if it weren't ingrained in the API etc.
exports.id2name = function id2name(id) {
    if(typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
    var axNum = id.substr(1);
    if(axNum === '1') axNum = '';
    return id.charAt(0) + 'axis' + axNum;
};

exports.name2id = function name2id(name) {
    if(!name.match(constants.AX_NAME_PATTERN)) return;
    var axNum = name.substr(5);
    if(axNum === '1') axNum = '';
    return name.charAt(0) + axNum;
};

exports.cleanId = function cleanId(id, axLetter) {
    if(!id.match(constants.AX_ID_PATTERN)) return;
    if(axLetter && id.charAt(0) !== axLetter) return;

    var axNum = id.substr(1).replace(/^0+/, '');
    if(axNum === '1') axNum = '';
    return id.charAt(0) + axNum;
};

// get all axis objects, as restricted in listNames
exports.list = function(gd, axLetter, only2d) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var idList = exports.listIds(gd, axLetter);
    var out = new Array(idList.length);
    var i;

    for(i = 0; i < idList.length; i++) {
        var idi = idList[i];
        out[i] = fullLayout[idi.charAt(0) + 'axis' + idi.substr(1)];
    }

    if(!only2d) {
        var sceneIds3D = fullLayout._subplots.gl3d || [];

        for(i = 0; i < sceneIds3D.length; i++) {
            var scene = fullLayout[sceneIds3D[i]];

            if(axLetter) out.push(scene[axLetter + 'axis']);
            else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
        }
    }

    return out;
};

// get all axis ids, optionally restricted by letter
// this only makes sense for 2d axes
exports.listIds = function(gd, axLetter) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout) return [];

    var subplotLists = fullLayout._subplots;
    if(axLetter) return subplotLists[axLetter + 'axis'];
    return subplotLists.xaxis.concat(subplotLists.yaxis);
};

// get an axis object from its id 'x','x2' etc
// optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
exports.getFromId = function(gd, id, type) {
    var fullLayout = gd._fullLayout;

    if(type === 'x') id = id.replace(/y[0-9]*/, '');
    else if(type === 'y') id = id.replace(/x[0-9]*/, '');

    return fullLayout[exports.id2name(id)];
};

// get an axis object of specified type from the containing trace
exports.getFromTrace = function(gd, fullTrace, type) {
    var fullLayout = gd._fullLayout;
    var ax = null;

    if(Registry.traceIs(fullTrace, 'gl3d')) {
        var scene = fullTrace.scene;
        if(scene.substr(0, 5) === 'scene') {
            ax = fullLayout[scene][type + 'axis'];
        }
    }
    else {
        ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
    }

    return ax;
};

// sort x, x2, x10, y, y2, y10...
exports.idSort = function(id1, id2) {
    var letter1 = id1.charAt(0);
    var letter2 = id2.charAt(0);
    if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
    return +(id1.substr(1) || 1) - +(id2.substr(1) || 1);
};

},{"../../registry":254,"./constants":211}],210:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

function findCategories(ax, opts) {
    var dataAttr = opts.dataAttr || ax._id.charAt(0);
    var lookup = {};
    var axData;
    var i, j;

    if(opts.axData) {
        // non-x/y case
        axData = opts.axData;
    } else {
        // x/y case
        axData = [];
        for(i = 0; i < opts.data.length; i++) {
            var trace = opts.data[i];
            if(trace[dataAttr + 'axis'] === ax._id) {
                axData.push(trace);
            }
        }
    }

    for(i = 0; i < axData.length; i++) {
        var vals = axData[i][dataAttr];
        for(j = 0; j < vals.length; j++) {
            var v = vals[j];
            if(v !== null && v !== undefined) {
                lookup[v] = 1;
            }
        }
    }

    return Object.keys(lookup);
}

/**
 * Fills in category* default and initial categories.
 *
 * @param {object} containerIn : input axis object
 * @param {object} containerOut : full axis object
 * @param {function} coerce : Lib.coerce fn wrapper
 * @param {object} opts :
 *   - data {array} : (full) data trace
 * OR
 *   - axData {array} : (full) data associated with axis being coerced here
 *   - dataAttr {string} : attribute name corresponding to coordinate array
 */
module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) {
    if(containerOut.type !== 'category') return;

    var arrayIn = containerIn.categoryarray;
    var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0);

    // override default 'categoryorder' value when non-empty array is supplied
    var orderDefault;
    if(isValidArray) orderDefault = 'array';

    var order = coerce('categoryorder', orderDefault);
    var array;

    // coerce 'categoryarray' only in array order case
    if(order === 'array') {
        array = coerce('categoryarray');
    }

    // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
    if(!isValidArray && order === 'array') {
        order = containerOut.categoryorder = 'trace';
    }

    // set up things for makeCalcdata
    if(order === 'trace') {
        containerOut._initialCategories = [];
    } else if(order === 'array') {
        containerOut._initialCategories = array.slice();
    } else {
        array = findCategories(containerOut, opts).sort();
        if(order === 'category ascending') {
            containerOut._initialCategories = array;
        } else if(order === 'category descending') {
            containerOut._initialCategories = array.reverse();
        }
    }
};

},{}],211:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';
var counterRegex = require('../../lib/regex').counter;


module.exports = {

    idRegex: {
        x: counterRegex('x'),
        y: counterRegex('y')
    },

    attrRegex: counterRegex('[xy]axis'),

    // axis match regular expression
    xAxisMatch: counterRegex('xaxis'),
    yAxisMatch: counterRegex('yaxis'),

    // pattern matching axis ids and names
    // note that this is more permissive than counterRegex, as
    // id2name, name2id, and cleanId accept "x1" etc
    AX_ID_PATTERN: /^[xyz][0-9]*$/,
    AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,

    // and for 2D subplots
    SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,

    // pixels to move mouse before you stop clamping to starting point
    MINDRAG: 8,

    // smallest dimension allowed for a select box
    MINSELECT: 12,

    // smallest dimension allowed for a zoombox
    MINZOOM: 20,

    // width of axis drag regions
    DRAGGERSIZE: 20,

    // max pixels off straight before a lasso select line counts as bent
    BENDPX: 1.5,

    // delay before a redraw (relayout) after smooth panning and zooming
    REDRAWDELAY: 50,

    // throttling limit (ms) for selectPoints calls
    SELECTDELAY: 100,

    // cache ID suffix for throttle
    SELECTID: '-select',

    // last resort axis ranges for x and y axes if we have no data
    DFLTRANGEX: [-1, 6],
    DFLTRANGEY: [-1, 4],

    // Layers to keep trace types in the right order
    // N.B. each  'unique' plot method must have its own layer
    traceLayerClasses: [
        'heatmaplayer',
        'contourcarpetlayer', 'contourlayer',
        'barlayer',
        'carpetlayer',
        'violinlayer',
        'boxlayer',
        'ohlclayer',
        'scattercarpetlayer', 'scatterlayer'
    ],

    layerValue2layerClass: {
        'above traces': 'above',
        'below traces': 'below'
    }
};

},{"../../lib/regex":179}],212:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var id2name = require('./axis_ids').id2name;


module.exports = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) {
    var constraintGroups = layoutOut._axisConstraintGroups;
    var thisID = containerOut._id;
    var letter = thisID.charAt(0);

    if(containerOut.fixedrange) return;

    // coerce the constraint mechanics even if this axis has no scaleanchor
    // because it may be the anchor of another axis.
    coerce('constrain');
    Lib.coerce(containerIn, containerOut, {
        constraintoward: {
            valType: 'enumerated',
            values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'],
            dflt: letter === 'x' ? 'center' : 'middle'
        }
    }, 'constraintoward');

    if(!containerIn.scaleanchor) return;

    var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut);

    var scaleanchor = Lib.coerce(containerIn, containerOut, {
        scaleanchor: {
            valType: 'enumerated',
            values: constraintOpts.linkableAxes
        }
    }, 'scaleanchor');

    if(scaleanchor) {
        var scaleratio = coerce('scaleratio');
        // TODO: I suppose I could do attribute.min: Number.MIN_VALUE to avoid zero,
        // but that seems hacky. Better way to say "must be a positive number"?
        // Of course if you use several super-tiny values you could eventually
        // force a product of these to zero and all hell would break loose...
        // Likewise with super-huge values.
        if(!scaleratio) scaleratio = containerOut.scaleratio = 1;

        updateConstraintGroups(constraintGroups, constraintOpts.thisGroup,
            thisID, scaleanchor, scaleratio);
    }
    else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) {
        Lib.warn('ignored ' + containerOut._name + '.scaleanchor: "' +
            containerIn.scaleanchor + '" to avoid either an infinite loop ' +
            'and possibly inconsistent scaleratios, or because the target' +
            'axis has fixed range.');
    }
};

function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) {
    // If this axis is already part of a constraint group, we can't
    // scaleanchor any other axis in that group, or we'd make a loop.
    // Filter allAxisIds to enforce this, also matching axis types.

    var thisType = layoutOut[id2name(thisID)].type;

    var i, j, idj, axj;

    var linkableAxes = [];
    for(j = 0; j < allAxisIds.length; j++) {
        idj = allAxisIds[j];
        if(idj === thisID) continue;

        axj = layoutOut[id2name(idj)];
        if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj);
    }

    for(i = 0; i < constraintGroups.length; i++) {
        if(constraintGroups[i][thisID]) {
            var thisGroup = constraintGroups[i];

            var linkableAxesNoLoops = [];
            for(j = 0; j < linkableAxes.length; j++) {
                idj = linkableAxes[j];
                if(!thisGroup[idj]) linkableAxesNoLoops.push(idj);
            }
            return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup};
        }
    }

    return {linkableAxes: linkableAxes, thisGroup: null};
}


/*
 * Add this axis to the axis constraint groups, which is the collection
 * of axes that are all constrained together on scale.
 *
 * constraintGroups: a list of objects. each object is
 * {axis_id: scale_within_group}, where scale_within_group is
 * only important relative to the rest of the group, and defines
 * the relative scales between all axes in the group
 *
 * thisGroup: the group the current axis is already in
 * thisID: the id if the current axis
 * scaleanchor: the id of the axis to scale it with
 * scaleratio: the ratio of this axis to the scaleanchor axis
 */
function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor, scaleratio) {
    var i, j, groupi, keyj, thisGroupIndex;

    if(thisGroup === null) {
        thisGroup = {};
        thisGroup[thisID] = 1;
        thisGroupIndex = constraintGroups.length;
        constraintGroups.push(thisGroup);
    }
    else {
        thisGroupIndex = constraintGroups.indexOf(thisGroup);
    }

    var thisGroupKeys = Object.keys(thisGroup);

    // we know that this axis isn't in any other groups, but we don't know
    // about the scaleanchor axis. If it is, we need to merge the groups.
    for(i = 0; i < constraintGroups.length; i++) {
        groupi = constraintGroups[i];
        if(i !== thisGroupIndex && groupi[scaleanchor]) {
            var baseScale = groupi[scaleanchor];
            for(j = 0; j < thisGroupKeys.length; j++) {
                keyj = thisGroupKeys[j];
                groupi[keyj] = baseScale * scaleratio * thisGroup[keyj];
            }
            constraintGroups.splice(thisGroupIndex, 1);
            return;
        }
    }

    // otherwise, we insert the new scaleanchor axis as the base scale (1)
    // in its group, and scale the rest of the group to it
    if(scaleratio !== 1) {
        for(j = 0; j < thisGroupKeys.length; j++) {
            thisGroup[thisGroupKeys[j]] *= scaleratio;
        }
    }
    thisGroup[scaleanchor] = 1;
}

},{"../../lib":164,"./axis_ids":209}],213:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var id2name = require('./axis_ids').id2name;
var scaleZoom = require('./scale_zoom');
var makePadFn = require('./autorange').makePadFn;

var ALMOST_EQUAL = require('../../constants/numerical').ALMOST_EQUAL;

var FROM_BL = require('../../constants/alignment').FROM_BL;


exports.enforce = function enforceAxisConstraints(gd) {
    var fullLayout = gd._fullLayout;
    var constraintGroups = fullLayout._axisConstraintGroups || [];

    var i, j, axisID, ax, normScale, mode, factor;

    for(i = 0; i < constraintGroups.length; i++) {
        var group = constraintGroups[i];
        var axisIDs = Object.keys(group);

        var minScale = Infinity;
        var maxScale = 0;
        // mostly matchScale will be the same as minScale
        // ie we expand axis ranges to encompass *everything*
        // that's currently in any of their ranges, but during
        // autorange of a subset of axes we will ignore other
        // axes for this purpose.
        var matchScale = Infinity;
        var normScales = {};
        var axes = {};
        var hasAnyDomainConstraint = false;

        // find the (normalized) scale of each axis in the group
        for(j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            axes[axisID] = ax = fullLayout[id2name(axisID)];

            if(ax._inputDomain) ax.domain = ax._inputDomain.slice();
            else ax._inputDomain = ax.domain.slice();

            if(!ax._inputRange) ax._inputRange = ax.range.slice();

            // set axis scale here so we can use _m rather than
            // having to calculate it from length and range
            ax.setScale();

            // abs: inverted scales still satisfy the constraint
            normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID];
            minScale = Math.min(minScale, normScale);
            if(ax.constrain === 'domain' || !ax._constraintShrinkable) {
                matchScale = Math.min(matchScale, normScale);
            }

            // this has served its purpose, so remove it
            delete ax._constraintShrinkable;
            maxScale = Math.max(maxScale, normScale);

            if(ax.constrain === 'domain') hasAnyDomainConstraint = true;
        }

        // Do we have a constraint mismatch? Give a small buffer for rounding errors
        if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue;

        // now increase any ranges we need to until all normalized scales are equal
        for(j = 0; j < axisIDs.length; j++) {
            axisID = axisIDs[j];
            normScale = normScales[axisID];
            ax = axes[axisID];
            mode = ax.constrain;

            // even if the scale didn't change, if we're shrinking domain
            // we need to recalculate in case `constraintoward` changed
            if(normScale !== matchScale || mode === 'domain') {
                factor = normScale / matchScale;

                if(mode === 'range') {
                    scaleZoom(ax, factor);
                }
                else {
                    // mode === 'domain'

                    var inputDomain = ax._inputDomain;
                    var domainShrunk = (ax.domain[1] - ax.domain[0]) /
                        (inputDomain[1] - inputDomain[0]);
                    var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) /
                        (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0]));

                    factor /= domainShrunk;

                    if(factor * rangeShrunk < 1) {
                        // we've asked to magnify the axis more than we can just by
                        // enlarging the domain - so we need to constrict range
                        ax.domain = ax._input.domain = inputDomain.slice();
                        scaleZoom(ax, factor);
                        continue;
                    }

                    if(rangeShrunk < 1) {
                        // the range has previously been constricted by ^^, but we've
                        // switched to the domain-constricted regime, so reset range
                        ax.range = ax._input.range = ax._inputRange.slice();
                        factor *= rangeShrunk;
                    }

                    if(ax.autorange && ax._min.length && ax._max.length) {
                        /*
                         * range & factor may need to change because range was
                         * calculated for the larger scaling, so some pixel
                         * paddings may get cut off when we reduce the domain.
                         *
                         * This is easier than the regular autorange calculation
                         * because we already know the scaling `m`, but we still
                         * need to cut out impossible constraints (like
                         * annotations with super-long arrows). That's what
                         * outerMin/Max are for - if the expansion was going to
                         * go beyond the original domain, it must be impossible
                         */
                        var rl0 = ax.r2l(ax.range[0]);
                        var rl1 = ax.r2l(ax.range[1]);
                        var rangeCenter = (rl0 + rl1) / 2;
                        var rangeMin = rangeCenter;
                        var rangeMax = rangeCenter;
                        var halfRange = Math.abs(rl1 - rangeCenter);
                        // extra tiny bit for rounding errors, in case we actually
                        // *are* expanding to the full domain
                        var outerMin = rangeCenter - halfRange * factor * 1.0001;
                        var outerMax = rangeCenter + halfRange * factor * 1.0001;
                        var getPad = makePadFn(ax);

                        updateDomain(ax, factor);
                        ax.setScale();
                        var m = Math.abs(ax._m);
                        var newVal;
                        var k;

                        for(k = 0; k < ax._min.length; k++) {
                            newVal = ax._min[k].val - getPad(ax._min[k]) / m;
                            if(newVal > outerMin && newVal < rangeMin) {
                                rangeMin = newVal;
                            }
                        }

                        for(k = 0; k < ax._max.length; k++) {
                            newVal = ax._max[k].val + getPad(ax._max[k]) / m;
                            if(newVal < outerMax && newVal > rangeMax) {
                                rangeMax = newVal;
                            }
                        }

                        var domainExpand = (rangeMax - rangeMin) / (2 * halfRange);
                        factor /= domainExpand;

                        rangeMin = ax.l2r(rangeMin);
                        rangeMax = ax.l2r(rangeMax);
                        ax.range = ax._input.range = (rl0 < rl1) ?
                            [rangeMin, rangeMax] : [rangeMax, rangeMin];
                    }

                    updateDomain(ax, factor);
                }
            }
        }
    }
};

// For use before autoranging, check if this axis was previously constrained
// by domain but no longer is
exports.clean = function cleanConstraints(gd, ax) {
    if(ax._inputDomain) {
        var isConstrained = false;
        var axId = ax._id;
        var constraintGroups = gd._fullLayout._axisConstraintGroups;
        for(var j = 0; j < constraintGroups.length; j++) {
            if(constraintGroups[j][axId]) {
                isConstrained = true;
                break;
            }
        }
        if(!isConstrained || ax.constrain !== 'domain') {
            ax._input.domain = ax.domain = ax._inputDomain;
            delete ax._inputDomain;
        }
    }
};

function updateDomain(ax, factor) {
    var inputDomain = ax._inputDomain;
    var centerFraction = FROM_BL[ax.constraintoward];
    var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction;

    ax.domain = ax._input.domain = [
        center + (inputDomain[0] - center) / factor,
        center + (inputDomain[1] - center) / factor
    ];
}

},{"../../constants/alignment":143,"../../constants/numerical":145,"./autorange":205,"./axis_ids":209,"./scale_zoom":222}],214:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var tinycolor = require('tinycolor2');
var supportsPassive = require('has-passive-events');

var Registry = require('../../registry');
var Lib = require('../../lib');
var svgTextUtils = require('../../lib/svg_text_utils');
var clearGlCanvases = require('../../lib/clear_gl_canvases');
var Color = require('../../components/color');
var Drawing = require('../../components/drawing');
var Fx = require('../../components/fx');
var setCursor = require('../../lib/setcursor');
var dragElement = require('../../components/dragelement');
var FROM_TL = require('../../constants/alignment').FROM_TL;

var Plots = require('../plots');

var doTicks = require('./axes').doTicks;
var getFromId = require('./axis_ids').getFromId;
var prepSelect = require('./select').prepSelect;
var clearSelect = require('./select').clearSelect;
var scaleZoom = require('./scale_zoom');

var constants = require('./constants');
var MINDRAG = constants.MINDRAG;
var MINZOOM = constants.MINZOOM;


// flag for showing "doubleclick to zoom out" only at the beginning
var SHOWZOOMOUTTIP = true;

// dragBox: create an element to drag one or more axis ends
// inputs:
//      plotinfo - which subplot are we making dragboxes on?
//      x,y,w,h - left, top, width, height of the box
//      ns - how does this drag the vertical axis?
//          'n' - top only
//          's' - bottom only
//          'ns' - top and bottom together, difference unchanged
//      ew - same for horizontal axis
function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) {
    // mouseDown stores ms of first mousedown event in the last
    // DBLCLICKDELAY ms on the drag bars
    // numClicks stores how many mousedowns have been seen
    // within DBLCLICKDELAY so we can check for click or doubleclick events
    // dragged stores whether a drag has occurred, so we don't have to
    // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px
    var zoomlayer = gd._fullLayout._zoomlayer;
    var isMainDrag = (ns + ew === 'nsew');
    var singleEnd = (ns + ew).length === 1;

    // main subplot x and y (i.e. found in plotinfo - the main ones)
    var xa0, ya0;
    // {ax._id: ax} hash objects
    var xaHash, yaHash;
    // xaHash/yaHash values (arrays)
    var xaxes, yaxes;
    // main axis offsets
    var xs, ys;
    // main axis lengths
    var pw, ph;
    // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes'
    // which are the x/y {ax._id: ax} hash objects and their values
    // for linked axis relative to this subplot
    var links;
    // set to ew/ns val when active, set to '' when inactive
    var xActive, yActive;
    // are all axes in this subplot are fixed?
    var allFixedRanges;
    // is subplot constrained?
    var isSubplotConstrained;
    // do we need to edit x/y ranges?
    var editX, editY;

    function recomputeAxisLists() {
        xa0 = plotinfo.xaxis;
        ya0 = plotinfo.yaxis;
        pw = xa0._length;
        ph = ya0._length;
        xs = xa0._offset;
        ys = ya0._offset;

        xaHash = {};
        xaHash[xa0._id] = xa0;
        yaHash = {};
        yaHash[ya0._id] = ya0;

        // if we're dragging two axes at once, also drag overlays
        if(ns && ew) {
            var overlays = plotinfo.overlays;
            for(var i = 0; i < overlays.length; i++) {
                var xa = overlays[i].xaxis;
                xaHash[xa._id] = xa;
                var ya = overlays[i].yaxis;
                yaHash[ya._id] = ya;
            }
        }

        xaxes = hashValues(xaHash);
        yaxes = hashValues(yaHash);
        xActive = isDirectionActive(xaxes, ew);
        yActive = isDirectionActive(yaxes, ns);
        allFixedRanges = !yActive && !xActive;

        links = calcLinks(gd, xaHash, yaHash);
        isSubplotConstrained = links.isSubplotConstrained;
        editX = ew || isSubplotConstrained;
        editY = ns || isSubplotConstrained;
    }

    recomputeAxisLists();

    var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag);
    var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h);

    // still need to make the element if the axes are disabled
    // but nuke its events (except for maindrag which needs them for hover)
    // and stop there
    if(allFixedRanges && !isMainDrag) {
        dragger.onmousedown = null;
        dragger.style.pointerEvents = 'none';
        return dragger;
    }

    var dragOptions = {
        element: dragger,
        gd: gd,
        plotinfo: plotinfo,
        prepFn: function(e, startX, startY) {
            var dragModeNow = gd._fullLayout.dragmode;

            recomputeAxisLists();

            if(!allFixedRanges) {
                if(isMainDrag) {
                    // main dragger handles all drag modes, and changes
                    // to pan (or to zoom if it already is pan) on shift
                    if(e.shiftKey) {
                        if(dragModeNow === 'pan') dragModeNow = 'zoom';
                        else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan';
                    }
                    else if(e.ctrlKey) {
                        dragModeNow = 'pan';
                    }
                }
                // all other draggers just pan
                else dragModeNow = 'pan';
            }

            if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
            else dragOptions.minDrag = undefined;

            if(isSelectOrLasso(dragModeNow)) {
                dragOptions.xaxes = xaxes;
                dragOptions.yaxes = yaxes;
                prepSelect(e, startX, startY, dragOptions, dragModeNow);
            }
            else if(allFixedRanges) {
                clearSelect(zoomlayer);
            }
            else if(dragModeNow === 'zoom') {
                dragOptions.moveFn = zoomMove;
                dragOptions.doneFn = zoomDone;

                // zoomMove takes care of the threshold, but we need to
                // minimize this so that constrained zoom boxes will flip
                // orientation at the right place
                dragOptions.minDrag = 1;

                zoomPrep(e, startX, startY);
            }
            else if(dragModeNow === 'pan') {
                dragOptions.moveFn = plotDrag;
                dragOptions.doneFn = dragTail;
                clearSelect(zoomlayer);
            }
        },
        clickFn: function(numClicks, evt) {
            removeZoombox(gd);

            if(numClicks === 2 && !singleEnd) doubleClick();

            if(isMainDrag) {
                Fx.click(gd, evt, plotinfo.id);
            }
            else if(numClicks === 1 && singleEnd) {
                var ax = ns ? ya0 : xa0,
                    end = (ns === 's' || ew === 'w') ? 0 : 1,
                    attrStr = ax._name + '.range[' + end + ']',
                    initialText = getEndText(ax, end),
                    hAlign = 'left',
                    vAlign = 'middle';

                if(ax.fixedrange) return;

                if(ns) {
                    vAlign = (ns === 'n') ? 'top' : 'bottom';
                    if(ax.side === 'right') hAlign = 'right';
                }
                else if(ew === 'e') hAlign = 'right';

                if(gd._context.showAxisRangeEntryBoxes) {
                    d3.select(dragger)
                        .call(svgTextUtils.makeEditable, {
                            gd: gd,
                            immediate: true,
                            background: gd._fullLayout.paper_bgcolor,
                            text: String(initialText),
                            fill: ax.tickfont ? ax.tickfont.color : '#444',
                            horizontalAlign: hAlign,
                            verticalAlign: vAlign
                        })
                        .on('edit', function(text) {
                            var v = ax.d2r(text);
                            if(v !== undefined) {
                                Registry.call('relayout', gd, attrStr, v);
                            }
                        });
                }
            }
        }
    };

    dragElement.init(dragOptions);

    var x0,
        y0,
        box,
        lum,
        path0,
        dimmed,
        zoomMode,
        zb,
        corners;

    // collected changes to be made to the plot by relayout at the end
    var updates = {};

    function zoomPrep(e, startX, startY) {
        var dragBBox = dragger.getBoundingClientRect();
        x0 = startX - dragBBox.left;
        y0 = startY - dragBBox.top;
        box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0};
        lum = gd._hmpixcount ?
            (gd._hmlumcount / gd._hmpixcount) :
            tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
        path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0';
        dimmed = false;
        zoomMode = 'xy';

        zb = makeZoombox(zoomlayer, lum, xs, ys, path0);

        corners = makeCorners(zoomlayer, xs, ys);

        clearSelect(zoomlayer);
    }

    function zoomMove(dx0, dy0) {
        if(gd._transitioningWithDuration) {
            return false;
        }

        var x1 = Math.max(0, Math.min(pw, dx0 + x0)),
            y1 = Math.max(0, Math.min(ph, dy0 + y0)),
            dx = Math.abs(x1 - x0),
            dy = Math.abs(y1 - y0);

        box.l = Math.min(x0, x1);
        box.r = Math.max(x0, x1);
        box.t = Math.min(y0, y1);
        box.b = Math.max(y0, y1);

        function noZoom() {
            zoomMode = '';
            box.r = box.l;
            box.t = box.b;
            corners.attr('d', 'M0,0Z');
        }

        if(isSubplotConstrained) {
            if(dx > MINZOOM || dy > MINZOOM) {
                zoomMode = 'xy';
                if(dx / pw > dy / ph) {
                    dy = dx * ph / pw;
                    if(y0 > y1) box.t = y0 - dy;
                    else box.b = y0 + dy;
                }
                else {
                    dx = dy * pw / ph;
                    if(x0 > x1) box.l = x0 - dx;
                    else box.r = x0 + dx;
                }
                corners.attr('d', xyCorners(box));
            }
            else {
                noZoom();
            }
        }
        // look for small drags in one direction or the other,
        // and only drag the other axis
        else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
            if(dx < MINDRAG) {
                noZoom();
            }
            else {
                box.t = 0;
                box.b = ph;
                zoomMode = 'x';
                corners.attr('d', xCorners(box, y0));
            }
        }
        else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
            box.l = 0;
            box.r = pw;
            zoomMode = 'y';
            corners.attr('d', yCorners(box, x0));
        }
        else {
            zoomMode = 'xy';
            corners.attr('d', xyCorners(box));
        }
        box.w = box.r - box.l;
        box.h = box.b - box.t;

        updateZoombox(zb, corners, box, path0, dimmed, lum);
        dimmed = true;
    }

    function zoomDone() {
        // more strict than dragged, which allows you to come back to where you started
        // and still count as dragged
        if(Math.min(box.h, box.w) < MINDRAG * 2) {
            return removeZoombox(gd);
        }

        // TODO: edit linked axes in zoomAxRanges and in dragTail
        if(zoomMode === 'xy' || zoomMode === 'x') {
            zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes);
        }
        if(zoomMode === 'xy' || zoomMode === 'y') {
            zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes);
        }

        removeZoombox(gd);
        dragTail();
        showDoubleClickNotifier(gd);
    }

    // scroll zoom, on all draggers except corners
    var scrollViewBox = [0, 0, pw, ph];
    // wait a little after scrolling before redrawing
    var redrawTimer = null;
    var REDRAWDELAY = constants.REDRAWDELAY;
    var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo;

    function zoomWheel(e) {
        // deactivate mousewheel scrolling on embedded graphs
        // devs can override this with layout._enablescrollzoom,
        // but _ ensures this setting won't leave their page
        if(!gd._context.scrollZoom && !gd._fullLayout._enablescrollzoom) {
            return;
        }

        if(redrawTimer === null) {
            clearSelect(zoomlayer);
        }

        // If a transition is in progress, then disable any behavior:
        if(gd._transitioningWithDuration) {
            e.preventDefault();
            e.stopPropagation();
            return;
        }

        var pc = gd.querySelector('.plotly');

        recomputeAxisLists();

        // if the plot has scrollbars (more than a tiny excess)
        // disable scrollzoom too.
        if(pc.scrollHeight - pc.clientHeight > 10 ||
                pc.scrollWidth - pc.clientWidth > 10) {
            return;
        }

        clearTimeout(redrawTimer);

        var wheelDelta = -e.deltaY;
        if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
        if(!isFinite(wheelDelta)) {
            Lib.log('Did not find wheel motion attributes: ', e);
            return;
        }

        var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200),
            gbb = mainplot.draglayer.select('.nsewdrag')
                .node().getBoundingClientRect(),
            xfrac = (e.clientX - gbb.left) / gbb.width,
            yfrac = (gbb.bottom - e.clientY) / gbb.height,
            i;

        function zoomWheelOneAxis(ax, centerFraction, zoom) {
            if(ax.fixedrange) return;

            var axRange = Lib.simpleMap(ax.range, ax.r2l),
                v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
            function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); }
            ax.range = axRange.map(doZoom);
        }

        if(editX) {
            // if we're only zooming this axis because of constraints,
            // zoom it about the center
            if(!ew) xfrac = 0.5;

            for(i = 0; i < xaxes.length; i++) {
                zoomWheelOneAxis(xaxes[i], xfrac, zoom);
            }

            scrollViewBox[2] *= zoom;
            scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1);
        }
        if(editY) {
            if(!ns) yfrac = 0.5;

            for(i = 0; i < yaxes.length; i++) {
                zoomWheelOneAxis(yaxes[i], yfrac, zoom);
            }

            scrollViewBox[3] *= zoom;
            scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1);
        }

        // viewbox redraw at first
        updateSubplots(scrollViewBox);
        ticksAndAnnotations(ns, ew);

        // then replot after a delay to make sure
        // no more scrolling is coming
        redrawTimer = setTimeout(function() {
            scrollViewBox = [0, 0, pw, ph];

            var zoomMode;
            if(isSubplotConstrained) zoomMode = 'xy';
            else zoomMode = (ew ? 'x' : '') + (ns ? 'y' : '');

            dragTail(zoomMode);
        }, REDRAWDELAY);

        e.preventDefault();
        return;
    }

    // everything but the corners gets wheel zoom
    if(ns.length * ew.length !== 1) {
        attachWheelEventHandler(dragger, zoomWheel);
    }

    // plotDrag: move the plot in response to a drag
    function plotDrag(dx, dy) {
        // If a transition is in progress, then disable any behavior:
        if(gd._transitioningWithDuration) {
            return;
        }

        if(xActive === 'ew' || yActive === 'ns') {
            if(xActive) dragAxList(xaxes, dx);
            if(yActive) dragAxList(yaxes, dy);
            updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]);
            ticksAndAnnotations(yActive, xActive);
            return;
        }

        // dz: set a new value for one end (0 or 1) of an axis array axArray,
        // and return a pixel shift for that end for the viewbox
        // based on pixel drag distance d
        // TODO: this makes (generally non-fatal) errors when you get
        // near floating point limits
        function dz(axArray, end, d) {
            var otherEnd = 1 - end,
                movedAx,
                newLinearizedEnd;
            for(var i = 0; i < axArray.length; i++) {
                var axi = axArray[i];
                if(axi.fixedrange) continue;
                movedAx = axi;
                newLinearizedEnd = axi._rl[otherEnd] +
                    (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length);
                var newEnd = axi.l2r(newLinearizedEnd);

                // if l2r comes back false or undefined, it means we've dragged off
                // the end of valid ranges - so stop.
                if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd;
            }
            return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) /
                (movedAx._rl[end] - movedAx._rl[otherEnd]);
        }

        if(isSubplotConstrained && xActive && yActive) {
            // dragging a corner of a constrained subplot:
            // respect the fixed corner, but harmonize dx and dy
            var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1;
            var dxyFraction = (dx / pw + dxySign * dy / ph) / 2;
            dx = dxyFraction * pw;
            dy = dxySign * dxyFraction * ph;
        }

        if(xActive === 'w') dx = dz(xaxes, 0, dx);
        else if(xActive === 'e') dx = dz(xaxes, 1, -dx);
        else if(!xActive) dx = 0;

        if(yActive === 'n') dy = dz(yaxes, 1, dy);
        else if(yActive === 's') dy = dz(yaxes, 0, -dy);
        else if(!yActive) dy = 0;

        var x0 = (xActive === 'w') ? dx : 0;
        var y0 = (yActive === 'n') ? dy : 0;

        if(isSubplotConstrained) {
            var i;
            if(!xActive && yActive.length === 1) {
                // dragging one end of the y axis of a constrained subplot
                // scale the other axis the same about its middle
                for(i = 0; i < xaxes.length; i++) {
                    xaxes[i].range = xaxes[i]._r.slice();
                    scaleZoom(xaxes[i], 1 - dy / ph);
                }
                dx = dy * pw / ph;
                x0 = dx / 2;
            }
            if(!yActive && xActive.length === 1) {
                for(i = 0; i < yaxes.length; i++) {
                    yaxes[i].range = yaxes[i]._r.slice();
                    scaleZoom(yaxes[i], 1 - dx / pw);
                }
                dy = dx * ph / pw;
                y0 = dy / 2;
            }
        }

        updateSubplots([x0, y0, pw - dx, ph - dy]);
        ticksAndAnnotations(yActive, xActive);
    }

    // Draw ticks and annotations (and other components) when ranges change.
    // Also records the ranges that have changed for use by update at the end.
    function ticksAndAnnotations(ns, ew) {
        var activeAxIds = [],
            i;

        function pushActiveAxIds(axList) {
            for(i = 0; i < axList.length; i++) {
                if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
            }
        }

        if(editX) {
            pushActiveAxIds(xaxes);
            pushActiveAxIds(links.xaxes);
        }
        if(editY) {
            pushActiveAxIds(yaxes);
            pushActiveAxIds(links.yaxes);
        }

        updates = {};
        for(i = 0; i < activeAxIds.length; i++) {
            var axId = activeAxIds[i];
            doTicks(gd, axId, true);
            var ax = getFromId(gd, axId);
            updates[ax._name + '.range[0]'] = ax.range[0];
            updates[ax._name + '.range[1]'] = ax.range[1];
        }

        function redrawObjs(objArray, method, shortCircuit) {
            for(i = 0; i < objArray.length; i++) {
                var obji = objArray[i];

                if((ew && activeAxIds.indexOf(obji.xref) !== -1) ||
                    (ns && activeAxIds.indexOf(obji.yref) !== -1)) {
                    method(gd, i);
                    // once is enough for images (which doesn't use the `i` arg anyway)
                    if(shortCircuit) return;
                }
            }
        }

        // annotations and shapes 'draw' method is slow,
        // use the finer-grained 'drawOne' method instead

        redrawObjs(gd._fullLayout.annotations || [], Registry.getComponentMethod('annotations', 'drawOne'));
        redrawObjs(gd._fullLayout.shapes || [], Registry.getComponentMethod('shapes', 'drawOne'));
        redrawObjs(gd._fullLayout.images || [], Registry.getComponentMethod('images', 'draw'), true);
    }

    function doubleClick() {
        if(gd._transitioningWithDuration) return;

        var doubleClickConfig = gd._context.doubleClick,
            axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []),
            attrs = {};

        var ax, i, rangeInitial;

        // For reset+autosize mode:
        // If *any* of the main axes is not at its initial range
        // (or autoranged, if we have no initial range, to match the logic in
        // doubleClickConfig === 'reset' below), we reset.
        // If they are *all* at their initial ranges, then we autosize.
        if(doubleClickConfig === 'reset+autosize') {

            doubleClickConfig = 'autosize';

            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if((ax._rangeInitial && (
                        ax.range[0] !== ax._rangeInitial[0] ||
                        ax.range[1] !== ax._rangeInitial[1]
                    )) ||
                    (!ax._rangeInitial && !ax.autorange)
                ) {
                    doubleClickConfig = 'reset';
                    break;
                }
            }
        }

        if(doubleClickConfig === 'autosize') {
            // don't set the linked axes here, so relayout marks them as shrinkable
            // and we autosize just to the requested axis/axes
            for(i = 0; i < axList.length; i++) {
                ax = axList[i];
                if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true;
            }
        }
        else if(doubleClickConfig === 'reset') {
            // when we're resetting, reset all linked axes too, so we get back
            // to the fully-auto-with-constraints situation
            if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes);
            if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes);

            if(isSubplotConstrained) {
                if(!xActive) axList = axList.concat(xaxes);
                else if(!yActive) axList = axList.concat(yaxes);
            }

            for(i = 0; i < axList.length; i++) {
                ax = axList[i];

                if(!ax._rangeInitial) {
                    attrs[ax._name + '.autorange'] = true;
                }
                else {
                    rangeInitial = ax._rangeInitial;
                    attrs[ax._name + '.range[0]'] = rangeInitial[0];
                    attrs[ax._name + '.range[1]'] = rangeInitial[1];
                }
            }
        }

        gd.emit('plotly_doubleclick', null);
        Registry.call('relayout', gd, attrs);
    }

    // dragTail - finish a drag event with a redraw
    function dragTail() {
        // put the subplot viewboxes back to default (Because we're going to)
        // be repositioning the data in the relayout. But DON'T call
        // ticksAndAnnotations again - it's unnecessary and would overwrite `updates`
        updateSubplots([0, 0, pw, ph]);

        // since we may have been redrawing some things during the drag, we may have
        // accumulated MathJax promises - wait for them before we relayout.
        Lib.syncOrAsync([
            Plots.previousPromises,
            function() { Registry.call('relayout', gd, updates); }
        ], gd);
    }

    // updateSubplots - find all plot viewboxes that should be
    // affected by this drag, and update them. look for all plots
    // sharing an affected axis (including the one being dragged),
    // includes also scattergl and splom logic.
    function updateSubplots(viewBox) {
        var fullLayout = gd._fullLayout;
        var plotinfos = fullLayout._plots;
        var subplots = fullLayout._subplots.cartesian;

        // TODO can we move these to outer scope?
        var hasScatterGl = fullLayout._has('scattergl');
        var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms;
        var hasSplom = hasOnlyLargeSploms || fullLayout._has('splom');
        var hasSVG = fullLayout._has('svg');
        var hasDraggedPts = fullLayout._has('draggedPts');

        var i, sp, xa, ya;

        if(hasSplom || hasScatterGl) {
            clearGlCanvases(gd);
        }

        if(hasSplom) {
            Registry.subplotsRegistry.splom.drag(gd);
            if(hasOnlyLargeSploms) return;
        }

        if(hasScatterGl) {
            // loop over all subplots (w/o exceptions) here,
            // as we cleared the gl canvases above
            for(i = 0; i < subplots.length; i++) {
                sp = plotinfos[subplots[i]];
                xa = sp.xaxis;
                ya = sp.yaxis;

                var scene = sp._scene;
                if(scene) {
                    // FIXME: possibly we could update axis internal _r and _rl here
                    var xrng = Lib.simpleMap(xa.range, xa.r2l);
                    var yrng = Lib.simpleMap(ya.range, ya.r2l);
                    scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]});
                }
            }
        }

        if(hasSVG) {
            var xScaleFactor = viewBox[2] / xa0._length;
            var yScaleFactor = viewBox[3] / ya0._length;

            for(i = 0; i < subplots.length; i++) {
                sp = plotinfos[subplots[i]];
                xa = sp.xaxis;
                ya = sp.yaxis;

                var editX2 = editX && !xa.fixedrange && xaHash[xa._id];
                var editY2 = editY && !ya.fixedrange && yaHash[ya._id];

                var xScaleFactor2, yScaleFactor2;
                var clipDx, clipDy;

                if(editX2) {
                    xScaleFactor2 = xScaleFactor;
                    clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2);
                } else {
                    xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor);
                    clipDx = scaleAndGetShift(xa, xScaleFactor2);
                }

                if(editY2) {
                    yScaleFactor2 = yScaleFactor;
                    clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2);
                } else {
                    yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor);
                    clipDy = scaleAndGetShift(ya, yScaleFactor2);
                }

                // don't scale at all if neither axis is scalable here
                if(!xScaleFactor2 && !yScaleFactor2) {
                    continue;
                }

                // but if only one is, reset the other axis scaling
                if(!xScaleFactor2) xScaleFactor2 = 1;
                if(!yScaleFactor2) yScaleFactor2 = 1;

                var plotDx = xa._offset - clipDx / xScaleFactor2;
                var plotDy = ya._offset - clipDy / yScaleFactor2;

                // TODO could be more efficient here:
                // setTranslate and setScale do a lot of extra work
                // when working independently, should perhaps combine
                // them into a single routine.
                sp.clipRect
                    .call(Drawing.setTranslate, clipDx, clipDy)
                    .call(Drawing.setScale, xScaleFactor2, yScaleFactor2);

                sp.plot
                    .call(Drawing.setTranslate, plotDx, plotDy)
                    .call(Drawing.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2);

                // TODO move these selectAll calls out of here
                // and stash them somewhere nice, see:
                // https://github.com/plotly/plotly.js/issues/2548
                if(hasDraggedPts) {
                    var traceGroups = sp.plot
                        .selectAll('.scatterlayer .trace, .boxlayer .trace, .violinlayer .trace');

                    // This is specifically directed at marker points in scatter, box and violin traces,
                    // applying an inverse scale to individual points to counteract
                    // the scale of the trace as a whole:
                    traceGroups.selectAll('.point')
                        .call(Drawing.setPointGroupScale, xScaleFactor2, yScaleFactor2);
                    traceGroups.selectAll('.textpoint')
                        .call(Drawing.setTextPointsScale, xScaleFactor2, yScaleFactor2);
                    traceGroups
                        .call(Drawing.hideOutsideRangePoints, sp);

                    sp.plot.selectAll('.barlayer .trace')
                        .call(Drawing.hideOutsideRangePoints, sp, '.bartext');
                }
            }
        }
    }

    // Find the appropriate scaling for this axis, if it's linked to the
    // dragged axes by constraints. 0 is special, it means this axis shouldn't
    // ever be scaled (will be converted to 1 if the other axis is scaled)
    function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) {
        if(ax.fixedrange) return 0;

        if(editX && links.xaHash[ax._id]) {
            return xScaleFactor;
        }
        if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) {
            return yScaleFactor;
        }
        return 0;
    }

    function scaleAndGetShift(ax, scaleFactor) {
        if(scaleFactor) {
            ax.range = ax._r.slice();
            scaleZoom(ax, scaleFactor);
            return getShift(ax, scaleFactor);
        }
        return 0;
    }

    function getShift(ax, scaleFactor) {
        return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle'];
    }

    return dragger;
}

function makeDragger(plotinfo, nodeName, dragClass, cursor) {
    var dragger3 = Lib.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) {
        s.classed('drag', true)
            .style({fill: 'transparent', 'stroke-width': 0})
            .attr('data-subplot', plotinfo.id);
    });

    dragger3.call(setCursor, cursor);

    return dragger3.node();
}

function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) {
    var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor);
    d3.select(dragger).call(Drawing.setRect, x, y, w, h);
    return dragger;
}

function isDirectionActive(axList, activeVal) {
    for(var i = 0; i < axList.length; i++) {
        if(!axList[i].fixedrange) return activeVal;
    }
    return '';
}

function getEndText(ax, end) {
    var initialVal = ax.range[end],
        diff = Math.abs(initialVal - ax.range[1 - end]),
        dig;

    // TODO: this should basically be ax.r2d but we're doing extra
    // rounding here... can we clean up at all?
    if(ax.type === 'date') {
        return initialVal;
    }
    else if(ax.type === 'log') {
        dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
        return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
    }
    else { // linear numeric (or category... but just show numbers here)
        dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
            Math.floor(Math.log(diff) / Math.LN10) + 4;
        return d3.format('.' + String(dig) + 'g')(initialVal);
    }
}

function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) {
    var i,
        axi,
        axRangeLinear0,
        axRangeLinearSpan;

    for(i = 0; i < axList.length; i++) {
        axi = axList[i];
        if(axi.fixedrange) continue;

        axRangeLinear0 = axi._rl[0];
        axRangeLinearSpan = axi._rl[1] - axRangeLinear0;
        axi.range = [
            axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction),
            axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction)
        ];
        updates[axi._name + '.range[0]'] = axi.range[0];
        updates[axi._name + '.range[1]'] = axi.range[1];
    }

    // zoom linked axes about their centers
    if(linkedAxes && linkedAxes.length) {
        var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2;

        zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates);
    }
}

function dragAxList(axList, pix) {
    for(var i = 0; i < axList.length; i++) {
        var axi = axList[i];
        if(!axi.fixedrange) {
            axi.range = [
                axi.l2r(axi._rl[0] - pix / axi._m),
                axi.l2r(axi._rl[1] - pix / axi._m)
            ];
        }
    }
}

// common transform for dragging one end of an axis
// d>0 is compressing scale (cursor is over the plot,
//  the axis end should move with the cursor)
// d<0 is expanding (cursor is off the plot, axis end moves
//  nonlinearly so you can expand far)
function dZoom(d) {
    return 1 - ((d >= 0) ? Math.min(d, 0.9) :
        1 / (1 / Math.max(d, -0.3) + 3.222));
}

function getDragCursor(nsew, dragmode, isMainDrag) {
    if(!nsew) return 'pointer';
    if(nsew === 'nsew') {
        // in this case here, clear cursor and
        // use the cursor style set on <g .draglayer>
        if(isMainDrag) return '';
        if(dragmode === 'pan') return 'move';
        return 'crosshair';
    }
    return nsew.toLowerCase() + '-resize';
}

function makeZoombox(zoomlayer, lum, xs, ys, path0) {
    return zoomlayer.append('path')
        .attr('class', 'zoombox')
        .style({
            'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
            'stroke-width': 0
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', path0 + 'Z');
}

function makeCorners(zoomlayer, xs, ys) {
    return zoomlayer.append('path')
        .attr('class', 'zoombox-corners')
        .style({
            fill: Color.background,
            stroke: Color.defaultLine,
            'stroke-width': 1,
            opacity: 0
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', 'M0,0Z');
}

function updateZoombox(zb, corners, box, path0, dimmed, lum) {
    zb.attr('d',
        path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) +
        'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z');
    transitionZoombox(zb, corners, dimmed, lum);
}

function transitionZoombox(zb, corners, dimmed, lum) {
    if(!dimmed) {
        zb.transition()
            .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
                'rgba(255,255,255,0.3)')
            .duration(200);
        corners.transition()
            .style('opacity', 1)
            .duration(200);
    }
}

function removeZoombox(gd) {
    d3.select(gd)
        .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
        .remove();
}

function showDoubleClickNotifier(gd) {
    if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
        Lib.notifier(Lib._(gd, 'Double-click to zoom back out'), 'long');
        SHOWZOOMOUTTIP = false;
    }
}

function isSelectOrLasso(dragmode) {
    return dragmode === 'lasso' || dragmode === 'select';
}

function xCorners(box, y0) {
    return 'M' +
        (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) +
        'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' +
        (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) +
        'h3v' + (2 * MINZOOM + 1) + 'h-3Z';
}

function yCorners(box, x0) {
    return 'M' +
        (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) +
        'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' +
        (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) +
        'v3h' + (2 * MINZOOM + 1) + 'v-3Z';
}

function xyCorners(box) {
    var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2);
    return 'M' +
        (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) +
            'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' +
        (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) +
            'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' +
        (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen +
            'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' +
        (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen +
            'h' + clen + 'v3h-' + (clen + 3) + 'Z';
}

function calcLinks(gd, xaHash, yaHash) {
    var constraintGroups = gd._fullLayout._axisConstraintGroups;
    var isSubplotConstrained = false;
    var xLinks = {};
    var yLinks = {};
    var xID, yID, xLinkID, yLinkID;

    for(var i = 0; i < constraintGroups.length; i++) {
        var group = constraintGroups[i];
        // check if any of the x axes we're dragging is in this constraint group
        for(xID in xaHash) {
            if(group[xID]) {
                // put the rest of these axes into xLinks, if we're not already
                // dragging them, so we know to scale these axes automatically too
                // to match the changes in the dragged x axes
                for(xLinkID in group) {
                    if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) {
                        xLinks[xLinkID] = 1;
                    }
                }

                // check if the x and y axes of THIS drag are linked
                for(yID in yaHash) {
                    if(group[yID]) isSubplotConstrained = true;
                }
            }
        }

        // now check if any of the y axes we're dragging is in this constraint group
        // only look for outside links, as we've already checked for links within the dragger
        for(yID in yaHash) {
            if(group[yID]) {
                for(yLinkID in group) {
                    if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) {
                        yLinks[yLinkID] = 1;
                    }
                }
            }
        }
    }

    if(isSubplotConstrained) {
        // merge xLinks and yLinks if the subplot is constrained,
        // since we'll always apply both anyway and the two will contain
        // duplicates
        Lib.extendFlat(xLinks, yLinks);
        yLinks = {};
    }

    var xaHashLinked = {};
    var xaxesLinked = [];
    for(xLinkID in xLinks) {
        var xa = getFromId(gd, xLinkID);
        xaxesLinked.push(xa);
        xaHashLinked[xa._id] = xa;
    }

    var yaHashLinked = {};
    var yaxesLinked = [];
    for(yLinkID in yLinks) {
        var ya = getFromId(gd, yLinkID);
        yaxesLinked.push(ya);
        yaHashLinked[ya._id] = ya;
    }

    return {
        xaHash: xaHashLinked,
        yaHash: yaHashLinked,
        xaxes: xaxesLinked,
        yaxes: yaxesLinked,
        isSubplotConstrained: isSubplotConstrained
    };
}

// still seems to be some confusion about onwheel vs onmousewheel...
function attachWheelEventHandler(element, handler) {
    if(!supportsPassive) {
        if(element.onwheel !== undefined) element.onwheel = handler;
        else if(element.onmousewheel !== undefined) element.onmousewheel = handler;
    }
    else {
        var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel';

        if(element._onwheel) {
            element.removeEventListener(wheelEventName, element._onwheel);
        }
        element._onwheel = handler;

        element.addEventListener(wheelEventName, handler, {passive: false});
    }
}

function hashValues(hash) {
    var out = [];
    for(var k in hash) out.push(hash[k]);
    return out;
}

module.exports = {
    makeDragBox: makeDragBox,

    makeDragger: makeDragger,
    makeRectDragger: makeRectDragger,
    makeZoombox: makeZoombox,
    makeCorners: makeCorners,

    updateZoombox: updateZoombox,
    xyCorners: xyCorners,
    transitionZoombox: transitionZoombox,
    removeZoombox: removeZoombox,
    showDoubleClickNotifier: showDoubleClickNotifier,

    attachWheelEventHandler: attachWheelEventHandler
};

},{"../../components/color":43,"../../components/dragelement":65,"../../components/drawing":68,"../../components/fx":85,"../../constants/alignment":143,"../../lib":164,"../../lib/clear_gl_canvases":152,"../../lib/setcursor":183,"../../lib/svg_text_utils":185,"../../registry":254,"../plots":245,"./axes":206,"./axis_ids":209,"./constants":211,"./scale_zoom":222,"./select":223,"d3":6,"has-passive-events":12,"tinycolor2":25}],215:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Fx = require('../../components/fx');
var dragElement = require('../../components/dragelement');
var setCursor = require('../../lib/setcursor');

var makeDragBox = require('./dragbox').makeDragBox;
var DRAGGERSIZE = require('./constants').DRAGGERSIZE;

exports.initInteractions = function initInteractions(gd) {
    var fullLayout = gd._fullLayout;

    if(gd._context.staticPlot) {
        // this sweeps up more than just cartesian drag elements...
        d3.select(gd).selectAll('.drag').remove();
        return;
    }

    if(!fullLayout._has('cartesian') && !fullLayout._has('gl2d') && !fullLayout._has('splom')) return;

    var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
        // sort overlays last, then by x axis number, then y axis number
        if((fullLayout._plots[a].mainplot && true) ===
            (fullLayout._plots[b].mainplot && true)) {
            var aParts = a.split('y'),
                bParts = b.split('y');
            return (aParts[0] === bParts[0]) ?
                (Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
                (Number(aParts[0] || 1) - Number(bParts[0] || 1));
        }
        return fullLayout._plots[a].mainplot ? 1 : -1;
    });

    subplots.forEach(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];
        var xa = plotinfo.xaxis;
        var ya = plotinfo.yaxis;

        // main and corner draggers need not be repeated for
        // overlaid subplots - these draggers drag them all
        if(!plotinfo.mainplot) {
            // main dragger goes over the grids and data, so we use its
            // mousemove events for all data hover effects
            var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset,
                xa._length, ya._length, 'ns', 'ew');

            maindrag.onmousemove = function(evt) {
                // This is on `gd._fullLayout`, *not* fullLayout because the reference
                // changes by the time this is called again.
                gd._fullLayout._rehover = function() {
                    if(gd._fullLayout._hoversubplot === subplot) {
                        Fx.hover(gd, evt, subplot);
                    }
                };

                Fx.hover(gd, evt, subplot);

                // Note that we have *not* used the cached fullLayout variable here
                // since that may be outdated when this is called as a callback later on
                gd._fullLayout._lasthover = maindrag;
                gd._fullLayout._hoversubplot = subplot;
            };

            /*
             * IMPORTANT:
             * We must check for the presence of the drag cover here.
             * If we don't, a 'mouseout' event is triggered on the
             * maindrag before each 'click' event, which has the effect
             * of clearing the hoverdata; thus, cancelling the click event.
             */
            maindrag.onmouseout = function(evt) {
                if(gd._dragging) return;

                // When the mouse leaves this maindrag, unset the hovered subplot.
                // This may cause problems if it leaves the subplot directly *onto*
                // another subplot, but that's a tiny corner case at the moment.
                gd._fullLayout._hoversubplot = null;

                dragElement.unhover(gd, evt);
            };

            // corner draggers
            if(gd._context.showAxisDragHandles) {
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE,
                    DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
                makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length,
                    DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
            }
        }
        if(gd._context.showAxisDragHandles) {
            // x axis draggers - if you have overlaid plots,
            // these drag each axis separately
            if(subplot === xa._mainSubplot) {
                // the y position of the main x axis line
                var y0 = xa._mainLinePosition;
                if(xa.side === 'top') y0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0,
                    xa._length * 0.8, DRAGGERSIZE, '', 'ew');
                makeDragBox(gd, plotinfo, xa._offset, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'w');
                makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0,
                    xa._length * 0.1, DRAGGERSIZE, '', 'e');
            }
            // y axis draggers
            if(subplot === ya._mainSubplot) {
                // the x position of the main y axis line
                var x0 = ya._mainLinePosition;
                if(ya.side !== 'right') x0 -= DRAGGERSIZE;
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1,
                    DRAGGERSIZE, ya._length * 0.8, 'ns', '');
                makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9,
                    DRAGGERSIZE, ya._length * 0.1, 's', '');
                makeDragBox(gd, plotinfo, x0, ya._offset,
                    DRAGGERSIZE, ya._length * 0.1, 'n', '');
            }
        }
    });

    // In case you mousemove over some hovertext, send it to Fx.hover too
    // we do this so that we can put the hover text in front of everything,
    // but still be able to interact with everything as if it isn't there
    var hoverLayer = fullLayout._hoverlayer.node();

    hoverLayer.onmousemove = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.hover(gd, evt, fullLayout._hoversubplot);
    };

    hoverLayer.onclick = function(evt) {
        evt.target = gd._fullLayout._lasthover;
        Fx.click(gd, evt);
    };

    // also delegate mousedowns... TODO: does this actually work?
    hoverLayer.onmousedown = function(evt) {
        gd._fullLayout._lasthover.onmousedown(evt);
    };

    exports.updateFx(fullLayout);
};

// Minimal set of update needed on 'modebar' edits.
// We only need to update the <g .draglayer> cursor style.
//
// Note that changing the axis configuration and/or the fixedrange attribute
// should trigger a full initInteractions.
exports.updateFx = function(fullLayout) {
    var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
    setCursor(fullLayout._draggers, cursor);
};

},{"../../components/dragelement":65,"../../components/fx":85,"../../lib/setcursor":183,"./constants":211,"./dragbox":214,"d3":6}],216:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');

/**
 * Factory function for checking component arrays for subplot references.
 *
 * @param {string} containerArrayName: the top-level array in gd.layout to check
 *   If an item in this container is found that references a cartesian x and/or y axis,
 *   ensure cartesian is marked as a base plot module and record the axes (and subplot
 *   if both refs are axes) in gd._fullLayout
 *
 * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout)
 * as expected of a component includeBasePlot method
 */
module.exports = function makeIncludeComponents(containerArrayName) {
    return function includeComponents(layoutIn, layoutOut) {
        var array = layoutIn[containerArrayName];
        if(!Array.isArray(array)) return;

        var Cartesian = Registry.subplotsRegistry.cartesian;
        var idRegex = Cartesian.idRegex;
        var subplots = layoutOut._subplots;
        var xaList = subplots.xaxis;
        var yaList = subplots.yaxis;
        var cartesianList = subplots.cartesian;
        var hasCartesianOrGL2D = layoutOut._has('cartesian') || layoutOut._has('gl2d');

        for(var i = 0; i < array.length; i++) {
            var itemi = array[i];
            if(!Lib.isPlainObject(itemi)) continue;

            var xref = itemi.xref;
            var yref = itemi.yref;

            var hasXref = idRegex.x.test(xref);
            var hasYref = idRegex.y.test(yref);
            if(hasXref || hasYref) {
                if(!hasCartesianOrGL2D) Lib.pushUnique(layoutOut._basePlotModules, Cartesian);

                var newAxis = false;
                if(hasXref && xaList.indexOf(xref) === -1) {
                    xaList.push(xref);
                    newAxis = true;
                }
                if(hasYref && yaList.indexOf(yref) === -1) {
                    yaList.push(yref);
                    newAxis = true;
                }

                /*
                 * Notice the logic here: only add a subplot for a component if
                 * it's referencing both x and y axes AND it's creating a new axis
                 * so for example if your plot already has xy and x2y2, an annotation
                 * on x2y or xy2 will not create a new subplot.
                 */
                if(newAxis && hasXref && hasYref) {
                    cartesianList.push(xref + yref);
                }
            }
        }
    };
};

},{"../../lib":164,"../../registry":254}],217:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Lib = require('../../lib');
var Plots = require('../plots');
var Drawing = require('../../components/drawing');

var getModuleCalcData = require('../get_data').getModuleCalcData;
var axisIds = require('./axis_ids');
var constants = require('./constants');
var xmlnsNamespaces = require('../../constants/xmlns_namespaces');

var ensureSingle = Lib.ensureSingle;

function ensureSingleAndAddDatum(parent, nodeType, className) {
    return Lib.ensureSingle(parent, nodeType, className, function(s) {
        s.datum(className);
    });
}

exports.name = 'cartesian';

exports.attr = ['xaxis', 'yaxis'];

exports.idRoot = ['x', 'y'];

exports.idRegex = constants.idRegex;

exports.attrRegex = constants.attrRegex;

exports.attributes = require('./attributes');

exports.layoutAttributes = require('./layout_attributes');

exports.supplyLayoutDefaults = require('./layout_defaults');

exports.transitionAxes = require('./transition_axes');

exports.finalizeSubplots = function(layoutIn, layoutOut) {
    var subplots = layoutOut._subplots;
    var xList = subplots.xaxis;
    var yList = subplots.yaxis;
    var spSVG = subplots.cartesian;
    var spAll = spSVG.concat(subplots.gl2d || []);
    var allX = {};
    var allY = {};
    var i, xi, yi;

    for(i = 0; i < spAll.length; i++) {
        var parts = spAll[i].split('y');
        allX[parts[0]] = 1;
        allY['y' + parts[1]] = 1;
    }

    // check for x axes with no subplot, and make one from the anchor of that x axis
    for(i = 0; i < xList.length; i++) {
        xi = xList[i];
        if(!allX[xi]) {
            yi = (layoutIn[axisIds.id2name(xi)] || {}).anchor;
            if(!constants.idRegex.y.test(yi)) yi = 'y';
            spSVG.push(xi + yi);
            spAll.push(xi + yi);

            if(!allY[yi]) {
                allY[yi] = 1;
                Lib.pushUnique(yList, yi);
            }
        }
    }

    // same for y axes with no subplot
    for(i = 0; i < yList.length; i++) {
        yi = yList[i];
        if(!allY[yi]) {
            xi = (layoutIn[axisIds.id2name(yi)] || {}).anchor;
            if(!constants.idRegex.x.test(xi)) xi = 'x';
            spSVG.push(xi + yi);
            spAll.push(xi + yi);

            if(!allX[xi]) {
                allX[xi] = 1;
                Lib.pushUnique(xList, xi);
            }
        }
    }

    // finally, if we've gotten here we're supposed to show cartesian...
    // so if there are NO subplots at all, make one from the first
    // x & y axes in the input layout
    if(!spAll.length) {
        xi = '';
        yi = '';
        for(var ki in layoutIn) {
            if(constants.attrRegex.test(ki)) {
                var axLetter = ki.charAt(0);
                if(axLetter === 'x') {
                    if(!xi || (+ki.substr(5) < +xi.substr(5))) {
                        xi = ki;
                    }
                }
                else if(!yi || (+ki.substr(5) < +yi.substr(5))) {
                    yi = ki;
                }
            }
        }
        xi = xi ? axisIds.name2id(xi) : 'x';
        yi = yi ? axisIds.name2id(yi) : 'y';
        xList.push(xi);
        yList.push(yi);
        spSVG.push(xi + yi);
    }
};

exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = gd._fullLayout;
    var subplots = fullLayout._subplots.cartesian;
    var calcdata = gd.calcdata;
    var i;

    // If traces is not provided, then it's a complete replot and missing
    // traces are removed
    if(!Array.isArray(traces)) {
        traces = [];
        for(i = 0; i < calcdata.length; i++) traces.push(i);
    }

    for(i = 0; i < subplots.length; i++) {
        var subplot = subplots[i];
        var subplotInfo = fullLayout._plots[subplot];

        // Get all calcdata for this subplot:
        var cdSubplot = [];
        var pcd;

        for(var j = 0; j < calcdata.length; j++) {
            var cd = calcdata[j];
            var trace = cd[0].trace;

            // Skip trace if whitelist provided and it's not whitelisted:
            // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue;
            if(trace.xaxis + trace.yaxis === subplot) {
                // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet
                // axis has actually changed:
                //
                // If this trace is specifically requested, add it to the list:
                if(traces.indexOf(trace.index) !== -1 || trace.carpet) {
                    // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate
                    // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill
                    // is outdated. So this retroactively adds the previous trace if the
                    // traces are interdependent.
                    if(
                        pcd &&
                        pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot &&
                        ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 &&
                        cdSubplot.indexOf(pcd) === -1
                    ) {
                        cdSubplot.push(pcd);
                    }

                    cdSubplot.push(cd);
                }

                // Track the previous trace on this subplot for the retroactive-add step
                // above:
                pcd = cd;
            }
        }

        plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback);
    }
};

function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) {
    var traceLayerClasses = constants.traceLayerClasses;
    var fullLayout = gd._fullLayout;
    var modules = fullLayout._modules;
    var _module, cdModuleAndOthers, cdModule;

    var layerData = [];

    for(var i = 0; i < modules.length; i++) {
        _module = modules[i];
        var name = _module.name;

        if(Registry.modules[name].categories.svg) {
            var className = (_module.layerName || name + 'layer');
            var plotMethod = _module.plot;

            // plot all traces of this type on this subplot at once
            cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod);
            cdModule = cdModuleAndOthers[0];
            // don't need to search the found traces again - in fact we need to NOT
            // so that if two modules share the same plotter we don't double-plot
            cdSubplot = cdModuleAndOthers[1];

            if(cdModule.length) {
                layerData.push({
                    i: traceLayerClasses.indexOf(className),
                    className: className,
                    plotMethod: plotMethod,
                    cdModule: cdModule
                });
            }
        }
    }

    layerData.sort(function(a, b) { return a.i - b.i; });

    var layers = plotinfo.plot.selectAll('g.mlayer')
        .data(layerData, function(d) { return d.className; });

    layers.enter().append('g')
        .attr('class', function(d) { return d.className; })
        .classed('mlayer', true);

    layers.exit().remove();

    layers.order();

    layers.each(function(d) {
        var sel = d3.select(this);
        var className = d.className;

        d.plotMethod(
            gd, plotinfo, d.cdModule, sel,
            transitionOpts, makeOnCompleteCallback
        );

        // layers that allow `cliponaxis: false`
        if(className !== 'scatterlayer' && className !== 'barlayer') {
            Drawing.setClipUrl(sel, plotinfo.layerClipId);
        }
    });

    // call Scattergl.plot separately
    if(fullLayout._has('scattergl')) {
        _module = Registry.getModule('scattergl');
        cdModule = getModuleCalcData(cdSubplot, _module)[0];
        _module.plot(gd, plotinfo, cdModule);
    }
}

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldPlots = oldFullLayout._plots || {};
    var newPlots = newFullLayout._plots || {};
    var oldSubplotList = oldFullLayout._subplots || {};
    var plotinfo;
    var i, k;

    // when going from a large splom graph to something else,
    // we need to clear <g subplot> so that the new cartesian subplot
    // can have the correct layer ordering
    if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) {
        for(k in oldPlots) {
            plotinfo = oldPlots[k];
            if(plotinfo.plotgroup) plotinfo.plotgroup.remove();
        }
    }

    var hadGl = (oldFullLayout._has && oldFullLayout._has('gl'));
    var hasGl = (newFullLayout._has && newFullLayout._has('gl'));

    if(hadGl && !hasGl) {
        for(k in oldPlots) {
            plotinfo = oldPlots[k];
            if(plotinfo._scene) plotinfo._scene.destroy();
        }
    }

    // delete any titles we don't need anymore
    // check if axis list has changed, and if so clear old titles
    if(oldSubplotList.xaxis && oldSubplotList.yaxis) {
        var oldAxIDs = axisIds.listIds({_fullLayout: oldFullLayout});
        for(i = 0; i < oldAxIDs.length; i++) {
            var oldAxId = oldAxIDs[i];
            if(!newFullLayout[axisIds.id2name(oldAxId)]) {
                oldFullLayout._infolayer.selectAll('.g-' + oldAxId + 'title').remove();
            }
        }
    }

    // if we've gotten rid of all cartesian traces, remove all the subplot svg items
    var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian'));
    var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian'));

    if(hadCartesian && !hasCartesian) {
        purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout);
        oldFullLayout._defs.selectAll('.axesclip').remove();
        delete oldFullLayout._axisConstraintGroups;
    }
    // otherwise look for subplots we need to remove
    else if(oldSubplotList.cartesian) {
        for(i = 0; i < oldSubplotList.cartesian.length; i++) {
            var oldSubplotId = oldSubplotList.cartesian[i];
            if(!newPlots[oldSubplotId]) {
                var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y';
                oldFullLayout._cartesianlayer.selectAll(selector).remove();
                removeSubplotExtras(oldSubplotId, oldFullLayout);
            }
        }
    }
};

exports.drawFramework = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotData = makeSubplotData(gd);

    var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot')
        .data(subplotData, Lib.identity);

    subplotLayers.enter().append('g')
        .attr('class', function(name) { return 'subplot ' + name; });

    subplotLayers.order();

    subplotLayers.exit()
        .call(purgeSubplotLayers, fullLayout);

    subplotLayers.each(function(name) {
        var plotinfo = fullLayout._plots[name];

        // keep ref to plot group
        plotinfo.plotgroup = d3.select(this);

        // initialize list of overlay subplots
        plotinfo.overlays = [];

        makeSubplotLayer(gd, plotinfo);

        // fill in list of overlay subplots
        if(plotinfo.mainplot) {
            var mainplot = fullLayout._plots[plotinfo.mainplot];
            mainplot.overlays.push(plotinfo);
        }

        // make separate drag layers for each subplot,
        // but append them to paper rather than the plot groups,
        // so they end up on top of the rest
        plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', name);
    });
};

exports.rangePlot = function(gd, plotinfo, cdSubplot) {
    makeSubplotLayer(gd, plotinfo);
    plotOne(gd, plotinfo, cdSubplot);
    Plots.style(gd);
};

function makeSubplotData(gd) {
    var fullLayout = gd._fullLayout;
    var subplotData = [];
    var overlays = [];

    for(var k in fullLayout._plots) {
        var plotinfo = fullLayout._plots[k];
        var xa2 = plotinfo.xaxis._mainAxis;
        var ya2 = plotinfo.yaxis._mainAxis;
        var mainplot = xa2._id + ya2._id;

        if(mainplot !== k && fullLayout._plots[mainplot]) {
            plotinfo.mainplot = mainplot;
            plotinfo.mainplotinfo = fullLayout._plots[mainplot];
            overlays.push(k);
        } else {
            subplotData.push(k);
            plotinfo.mainplot = undefined;
        }
    }

    // main subplots before overlays
    subplotData = subplotData.concat(overlays);

    return subplotData;
}

function makeSubplotLayer(gd, plotinfo) {
    var plotgroup = plotinfo.plotgroup;
    var id = plotinfo.id;
    var xLayer = constants.layerValue2layerClass[plotinfo.xaxis.layer];
    var yLayer = constants.layerValue2layerClass[plotinfo.yaxis.layer];
    var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms;

    if(!plotinfo.mainplot) {
        if(hasOnlyLargeSploms) {
            // TODO could do even better
            // - we don't need plot (but we would have to mock it in lsInner
            //   and other places
            // - we don't (x|y)lines and (x|y)axislayer for most subplots
            //   usually just the bottom x and left y axes.
            plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot');
            plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
            plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
            plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above');
            plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above');
        }
        else {
            var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot');
            plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer');
            plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer');

            plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer');
            plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer');

            ensureSingle(plotgroup, 'path', 'xlines-below');
            ensureSingle(plotgroup, 'path', 'ylines-below');
            plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below');

            ensureSingle(plotgroup, 'g', 'xaxislayer-below');
            ensureSingle(plotgroup, 'g', 'yaxislayer-below');
            plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below');

            plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot');
            plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot');

            plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
            plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
            plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above');

            ensureSingle(plotgroup, 'g', 'xaxislayer-above');
            ensureSingle(plotgroup, 'g', 'yaxislayer-above');
            plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above');

            // set refs to correct layers as determined by 'axis.layer'
            plotinfo.xlines = plotgroup.select('.xlines-' + xLayer);
            plotinfo.ylines = plotgroup.select('.ylines-' + yLayer);
            plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer);
            plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer);
        }
    }
    else {
        var mainplotinfo = plotinfo.mainplotinfo;
        var mainplotgroup = mainplotinfo.plotgroup;
        var xId = id + '-x';
        var yId = id + '-y';

        // now make the components of overlaid subplots
        // overlays don't have backgrounds, and append all
        // their other components to the corresponding
        // extra groups of their main plots.

        plotinfo.gridlayer = mainplotinfo.gridlayer;
        plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;

        ensureSingle(mainplotinfo.overlinesBelow, 'path', xId);
        ensureSingle(mainplotinfo.overlinesBelow, 'path', yId);
        ensureSingle(mainplotinfo.overaxesBelow, 'g', xId);
        ensureSingle(mainplotinfo.overaxesBelow, 'g', yId);

        plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id);

        ensureSingle(mainplotinfo.overlinesAbove, 'path', xId);
        ensureSingle(mainplotinfo.overlinesAbove, 'path', yId);
        ensureSingle(mainplotinfo.overaxesAbove, 'g', xId);
        ensureSingle(mainplotinfo.overaxesAbove, 'g', yId);

        // set refs to correct layers as determined by 'abovetraces'
        plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId);
        plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId);
        plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId);
        plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId);
    }

    // common attributes for all subplots, overlays or not

    if(!hasOnlyLargeSploms) {
        ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id);
        ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id);
        plotinfo.gridlayer.selectAll('g').sort(axisIds.idSort);
    }

    plotinfo.xlines
        .style('fill', 'none')
        .classed('crisp', true);

    plotinfo.ylines
        .style('fill', 'none')
        .classed('crisp', true);
}

function purgeSubplotLayers(layers, fullLayout) {
    if(!layers) return;

    var overlayIdsToRemove = {};

    layers.each(function(subplotId) {
        var plotgroup = d3.select(this);

        plotgroup.remove();
        removeSubplotExtras(subplotId, fullLayout);

        overlayIdsToRemove[subplotId] = true;

        // do not remove individual axis <clipPath>s here
        // as other subplots may need them
    });

    // must remove overlaid subplot trace layers 'manually'

    for(var k in fullLayout._plots) {
        var subplotInfo = fullLayout._plots[k];
        var overlays = subplotInfo.overlays || [];

        for(var j = 0; j < overlays.length; j++) {
            var overlayInfo = overlays[j];

            if(overlayIdsToRemove[overlayInfo.id]) {
                overlayInfo.plot.selectAll('.trace').remove();
            }
        }
    }
}

function removeSubplotExtras(subplotId, fullLayout) {
    fullLayout._draggers.selectAll('g.' + subplotId).remove();
    fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove();
}

exports.toSVG = function(gd) {
    var imageRoot = gd._fullLayout._glimages;
    var root = d3.select(gd).selectAll('.svg-container');
    var canvases = root.filter(function(d, i) {return i === root.size() - 1;})
        .selectAll('.gl-canvas-context, .gl-canvas-focus');

    function canvasToImage() {
        var canvas = this;
        var imageData = canvas.toDataURL('image/png');
        var image = imageRoot.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            preserveAspectRatio: 'none',
            x: 0,
            y: 0,
            width: canvas.width,
            height: canvas.height
        });
    }

    canvases.each(canvasToImage);
};

exports.updateFx = require('./graph_interact').updateFx;

},{"../../components/drawing":68,"../../constants/xmlns_namespaces":147,"../../lib":164,"../../registry":254,"../get_data":234,"../plots":245,"./attributes":204,"./axis_ids":209,"./constants":211,"./graph_interact":215,"./layout_attributes":218,"./layout_defaults":219,"./transition_axes":228,"d3":6}],218:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('../font_attributes');
var colorAttrs = require('../../components/color/attributes');
var dash = require('../../components/drawing/attributes').dash;
var extendFlat = require('../../lib/extend').extendFlat;

var constants = require('./constants');


module.exports = {
    visible: {
        valType: 'boolean',
        
        editType: 'plot',
        
    },
    color: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    title: {
        valType: 'string',
        
        editType: 'ticks+margins',
        
    },
    titlefont: fontAttrs({
        editType: 'ticks+margins',
        
    }),
    type: {
        valType: 'enumerated',
        // '-' means we haven't yet run autotype or couldn't find any data
        // it gets turned into linear in gd._fullLayout but not copied back
        // to gd.data like the others are.
        values: ['-', 'linear', 'log', 'date', 'category'],
        dflt: '-',
        
        editType: 'calc',
        
    },
    autorange: {
        valType: 'enumerated',
        values: [true, false, 'reversed'],
        dflt: true,
        
        editType: 'calc',
        impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
        
    },
    rangemode: {
        valType: 'enumerated',
        values: ['normal', 'tozero', 'nonnegative'],
        dflt: 'normal',
        
        editType: 'plot',
        
    },
    range: {
        valType: 'info_array',
        
        items: [
            {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}},
            {valType: 'any', editType: 'axrange+margins', impliedEdits: {'^autorange': false}}
        ],
        editType: 'axrange+margins',
        impliedEdits: {'autorange': false},
        
    },
    fixedrange: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    // scaleanchor: not used directly, just put here for reference
    // values are any opposite-letter axis id
    scaleanchor: {
        valType: 'enumerated',
        values: [
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    scaleratio: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'plot',
        
    },
    constrain: {
        valType: 'enumerated',
        values: ['range', 'domain'],
        dflt: 'range',
        
        editType: 'plot',
        
    },
    // constraintoward: not used directly, just put here for reference
    constraintoward: {
        valType: 'enumerated',
        values: ['left', 'center', 'right', 'top', 'middle', 'bottom'],
        
        editType: 'plot',
        
    },
    // ticks
    tickmode: {
        valType: 'enumerated',
        values: ['auto', 'linear', 'array'],
        
        editType: 'ticks+margins',
        impliedEdits: {tick0: undefined, dtick: undefined},
        
    },
    nticks: {
        valType: 'integer',
        min: 0,
        dflt: 0,
        
        editType: 'ticks+margins',
        
    },
    tick0: {
        valType: 'any',
        
        editType: 'ticks+margins',
        impliedEdits: {tickmode: 'linear'},
        
    },
    dtick: {
        valType: 'any',
        
        editType: 'ticks+margins',
        impliedEdits: {tickmode: 'linear'},
        
    },
    tickvals: {
        valType: 'data_array',
        editType: 'ticks+margins',
        
    },
    ticktext: {
        valType: 'data_array',
        editType: 'ticks+margins',
        
    },
    ticks: {
        valType: 'enumerated',
        values: ['outside', 'inside', ''],
        
        editType: 'ticks+margins',
        
    },
    mirror: {
        valType: 'enumerated',
        values: [true, 'ticks', false, 'all', 'allticks'],
        dflt: false,
        
        editType: 'ticks+layoutstyle',
        
    },
    ticklen: {
        valType: 'number',
        min: 0,
        dflt: 5,
        
        editType: 'ticks',
        
    },
    tickwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks',
        
    },
    tickcolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    showticklabels: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'ticks+margins',
        
    },
    automargin: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks+margins',
        
    },
    showspikes: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'modebar',
        
    },
    spikecolor: {
        valType: 'color',
        dflt: null,
        
        editType: 'none',
        
    },
    spikethickness: {
        valType: 'number',
        dflt: 3,
        
        editType: 'none',
        
    },
    spikedash: extendFlat({}, dash, {dflt: 'dash', editType: 'none'}),
    spikemode: {
        valType: 'flaglist',
        flags: ['toaxis', 'across', 'marker'],
        
        dflt: 'toaxis',
        editType: 'none',
        
    },
    spikesnap: {
        valType: 'enumerated',
        values: ['data', 'cursor'],
        dflt: 'data',
        
        editType: 'none',
        
    },
    tickfont: fontAttrs({
        editType: 'ticks+margins',
        
    }),
    tickangle: {
        valType: 'angle',
        dflt: 'auto',
        
        editType: 'ticks+margins',
        
    },
    tickprefix: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks+margins',
        
    },
    showtickprefix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks+margins',
        
    },
    ticksuffix: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks+margins',
        
    },
    showticksuffix: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks+margins',
        
    },
    showexponent: {
        valType: 'enumerated',
        values: ['all', 'first', 'last', 'none'],
        dflt: 'all',
        
        editType: 'ticks+margins',
        
    },
    exponentformat: {
        valType: 'enumerated',
        values: ['none', 'e', 'E', 'power', 'SI', 'B'],
        dflt: 'B',
        
        editType: 'ticks+margins',
        
    },
    separatethousands: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'ticks+margins',
        
    },
    tickformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'ticks+margins',
        
    },
    tickformatstops: {
        _isLinkedToArray: 'tickformatstop',

        dtickrange: {
            valType: 'info_array',
            
            items: [
                {valType: 'any', editType: 'ticks+margins'},
                {valType: 'any', editType: 'ticks+margins'}
            ],
            editType: 'ticks+margins',
            
        },
        value: {
            valType: 'string',
            dflt: '',
            
            editType: 'ticks+margins',
            
        },
        editType: 'ticks+margins'
    },
    hoverformat: {
        valType: 'string',
        dflt: '',
        
        editType: 'none',
        
    },
    // lines and grids
    showline: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'layoutstyle',
        
    },
    linecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'layoutstyle',
        
    },
    linewidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks+layoutstyle',
        
    },
    showgrid: {
        valType: 'boolean',
        
        editType: 'ticks',
        
    },
    gridcolor: {
        valType: 'color',
        dflt: colorAttrs.lightLine,
        
        editType: 'ticks',
        
    },
    gridwidth: {
        valType: 'number',
        min: 0,
        dflt: 1,
        
        editType: 'ticks',
        
    },
    zeroline: {
        valType: 'boolean',
        
        editType: 'ticks',
        
    },
    zerolinecolor: {
        valType: 'color',
        dflt: colorAttrs.defaultLine,
        
        editType: 'ticks',
        
    },
    zerolinewidth: {
        valType: 'number',
        dflt: 1,
        
        editType: 'ticks',
        
    },
    // positioning attributes
    // anchor: not used directly, just put here for reference
    // values are any opposite-letter axis id
    anchor: {
        valType: 'enumerated',
        values: [
            'free',
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot+margins',
        
    },
    // side: not used directly, as values depend on direction
    // values are top, bottom for x axes, and left, right for y
    side: {
        valType: 'enumerated',
        values: ['top', 'bottom', 'left', 'right'],
        
        editType: 'plot+margins',
        
    },
    // overlaying: not used directly, just put here for reference
    // values are false and any other same-letter axis id that's not
    // itself overlaying anything
    overlaying: {
        valType: 'enumerated',
        values: [
            'free',
            constants.idRegex.x.toString(),
            constants.idRegex.y.toString()
        ],
        
        editType: 'plot',
        
    },
    layer: {
        valType: 'enumerated',
        values: ['above traces', 'below traces'],
        dflt: 'above traces',
        
        editType: 'plot',
        
    },
    domain: {
        valType: 'info_array',
        
        items: [
            {valType: 'number', min: 0, max: 1, editType: 'plot+margins'},
            {valType: 'number', min: 0, max: 1, editType: 'plot+margins'}
        ],
        dflt: [0, 1],
        editType: 'plot+margins',
        
    },
    position: {
        valType: 'number',
        min: 0,
        max: 1,
        dflt: 0,
        
        editType: 'plot+margins',
        
    },
    categoryorder: {
        valType: 'enumerated',
        values: [
            'trace', 'category ascending', 'category descending', 'array'
            /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
        ],
        dflt: 'trace',
        
        editType: 'calc',
        
    },
    categoryarray: {
        valType: 'data_array',
        
        editType: 'calc',
        
    },
    editType: 'calc',

    _deprecated: {
        autotick: {
            valType: 'boolean',
            
            editType: 'ticks+margins',
            
        }
    }
};

},{"../../components/color/attributes":42,"../../components/drawing/attributes":67,"../../lib/extend":157,"../font_attributes":232,"./constants":211}],219:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var Lib = require('../../lib');
var Color = require('../../components/color');
var basePlotLayoutAttributes = require('../layout_attributes');

var layoutAttributes = require('./layout_attributes');
var handleTypeDefaults = require('./type_defaults');
var handleAxisDefaults = require('./axis_defaults');
var handleConstraintDefaults = require('./constraint_defaults');
var handlePositionDefaults = require('./position_defaults');
var axisIds = require('./axis_ids');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    var xaCheater = {};
    var xaNonCheater = {};
    var outerTicks = {};
    var noGrids = {};
    var i;

    // look for axes in the data
    for(i = 0; i < fullData.length; i++) {
        var trace = fullData[i];

        if(!Registry.traceIs(trace, 'cartesian') && !Registry.traceIs(trace, 'gl2d')) {
            continue;
        }

        var xaName = axisIds.id2name(trace.xaxis);
        var yaName = axisIds.id2name(trace.yaxis);

        // Two things trigger axis visibility:
        // 1. is not carpet
        // 2. carpet that's not cheater
        if(!Registry.traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) {
            if(xaName) xaNonCheater[xaName] = 1;
        }

        // The above check for definitely-not-cheater is not adequate. This
        // second list tracks which axes *could* be a cheater so that the
        // full condition triggering hiding is:
        //   *could* be a cheater and *is not definitely visible*
        if(trace.type === 'carpet' && trace._cheater) {
            if(xaName) xaCheater[xaName] = 1;
        }

        // check for default formatting tweaks
        if(Registry.traceIs(trace, '2dMap')) {
            outerTicks[xaName] = true;
            outerTicks[yaName] = true;
        }

        if(Registry.traceIs(trace, 'oriented')) {
            var positionAxis = trace.orientation === 'h' ? yaName : xaName;
            noGrids[positionAxis] = true;
        }
    }

    var subplots = layoutOut._subplots;
    var xIds = subplots.xaxis;
    var yIds = subplots.yaxis;
    var xNames = Lib.simpleMap(xIds, axisIds.id2name);
    var yNames = Lib.simpleMap(yIds, axisIds.id2name);
    var axNames = xNames.concat(yNames);

    // plot_bgcolor only makes sense if there's a (2D) plot!
    // TODO: bgcolor for each subplot, to inherit from the main one
    var plot_bgcolor = Color.background;
    if(xIds.length && yIds.length) {
        plot_bgcolor = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, 'plot_bgcolor');
    }

    var bgColor = Color.combine(plot_bgcolor, layoutOut.paper_bgcolor);

    var axName, axLetter, axLayoutIn, axLayoutOut;

    function coerce(attr, dflt) {
        return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
    }

    function coerce2(attr, dflt) {
        return Lib.coerce2(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
    }

    function getCounterAxes(axLetter) {
        return (axLetter === 'x') ? yIds : xIds;
    }

    var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')};

    function getOverlayableAxes(axLetter, axName) {
        var list = (axLetter === 'x') ? xNames : yNames;
        var out = [];

        for(var j = 0; j < list.length; j++) {
            var axName2 = list[j];

            if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) {
                out.push(axisIds.name2id(axName2));
            }
        }

        return out;
    }

    // first pass creates the containers, determines types, and handles most of the settings
    for(i = 0; i < axNames.length; i++) {
        axName = axNames[i];

        if(!Lib.isPlainObject(layoutIn[axName])) {
            layoutIn[axName] = {};
        }

        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName] = {};

        handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, fullData, axName);

        axLetter = axName.charAt(0);
        var overlayableAxes = getOverlayableAxes(axLetter, axName);

        var defaultOptions = {
            letter: axLetter,
            font: layoutOut.font,
            outerTicks: outerTicks[axName],
            showGrid: !noGrids[axName],
            data: fullData,
            bgColor: bgColor,
            calendar: layoutOut.calendar,
            automargin: true,
            cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName]
        };

        handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut);

        var spikecolor = coerce2('spikecolor'),
            spikethickness = coerce2('spikethickness'),
            spikedash = coerce2('spikedash'),
            spikemode = coerce2('spikemode'),
            spikesnap = coerce2('spikesnap'),
            showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap);

        if(!showSpikes) {
            delete axLayoutOut.spikecolor;
            delete axLayoutOut.spikethickness;
            delete axLayoutOut.spikedash;
            delete axLayoutOut.spikemode;
            delete axLayoutOut.spikesnap;
        }

        var positioningOptions = {
            letter: axLetter,
            counterAxes: counterAxes[axLetter],
            overlayableAxes: overlayableAxes,
            grid: layoutOut.grid
        };

        handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, positioningOptions);

        axLayoutOut._input = axLayoutIn;
    }

    // quick second pass for range slider and selector defaults
    var rangeSliderDefaults = Registry.getComponentMethod('rangeslider', 'handleDefaults');
    var rangeSelectorDefaults = Registry.getComponentMethod('rangeselector', 'handleDefaults');

    for(i = 0; i < xNames.length; i++) {
        axName = xNames[i];
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        rangeSliderDefaults(layoutIn, layoutOut, axName);

        if(axLayoutOut.type === 'date') {
            rangeSelectorDefaults(
                axLayoutIn,
                axLayoutOut,
                layoutOut,
                yNames,
                axLayoutOut.calendar
            );
        }

        coerce('fixedrange');
    }

    for(i = 0; i < yNames.length; i++) {
        axName = yNames[i];
        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        var anchoredAxis = layoutOut[axisIds.id2name(axLayoutOut.anchor)];

        var fixedRangeDflt = (
            anchoredAxis &&
            anchoredAxis.rangeslider &&
            anchoredAxis.rangeslider.visible
        );

        coerce('fixedrange', fixedRangeDflt);
    }

    // Finally, handle scale constraints. We need to do this after all axes have
    // coerced both `type` (so we link only axes of the same type) and
    // `fixedrange` (so we can avoid linking from OR TO a fixed axis).

    // sets of axes linked by `scaleanchor` along with the scaleratios compounded
    // together, populated in handleConstraintDefaults
    layoutOut._axisConstraintGroups = [];
    var allAxisIds = counterAxes.x.concat(counterAxes.y);

    for(i = 0; i < axNames.length; i++) {
        axName = axNames[i];
        axLetter = axName.charAt(0);

        axLayoutIn = layoutIn[axName];
        axLayoutOut = layoutOut[axName];

        handleConstraintDefaults(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut);
    }
};

},{"../../components/color":43,"../../lib":164,"../../registry":254,"../layout_attributes":236,"./axis_defaults":208,"./axis_ids":209,"./constraint_defaults":212,"./layout_attributes":218,"./position_defaults":221,"./type_defaults":229}],220:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorMix = require('tinycolor2').mix;
var lightFraction = require('../../components/color/attributes').lightFraction;
var Lib = require('../../lib');

/**
 * @param {object} opts :
 *   - dfltColor {string} : default axis color
 *   - bgColor {string} : combined subplot bg color
 *   - blend {number, optional} : blend percentage (to compute dflt grid color)
 *   - showLine {boolean} : show line by default
 *   - showGrid {boolean} : show grid by default
 *   - noZeroLine {boolean} : don't coerce zeroline* attributes
 *   - attributes {object} : attribute object associated with input containers
 */
module.exports = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) {
    opts = opts || {};

    var dfltColor = opts.dfltColor;

    function coerce2(attr, dflt) {
        return Lib.coerce2(containerIn, containerOut, opts.attributes, attr, dflt);
    }

    var lineColor = coerce2('linecolor', dfltColor);
    var lineWidth = coerce2('linewidth');
    var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth);

    if(!showLine) {
        delete containerOut.linecolor;
        delete containerOut.linewidth;
    }

    var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || lightFraction).toRgbString();
    var gridColor = coerce2('gridcolor', gridColorDflt);
    var gridWidth = coerce2('gridwidth');
    var showGridLines = coerce('showgrid', opts.showGrid || !!gridColor || !!gridWidth);

    if(!showGridLines) {
        delete containerOut.gridcolor;
        delete containerOut.gridwidth;
    }

    if(!opts.noZeroLine) {
        var zeroLineColor = coerce2('zerolinecolor', dfltColor);
        var zeroLineWidth = coerce2('zerolinewidth');
        var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth);

        if(!showZeroLine) {
            delete containerOut.zerolinecolor;
            delete containerOut.zerolinewidth;
        }
    }
};

},{"../../components/color/attributes":42,"../../lib":164,"tinycolor2":25}],221:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');


module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
    var counterAxes = options.counterAxes || [];
    var overlayableAxes = options.overlayableAxes || [];
    var letter = options.letter;
    var grid = options.grid;

    var dfltAnchor, dfltDomain, dfltSide, dfltPosition;

    if(grid) {
        dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]];
        dfltAnchor = grid._anchors[containerOut._id];
        if(dfltDomain) {
            dfltSide = grid[letter + 'side'].split(' ')[0];
            dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0];
        }
    }

    // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults
    dfltDomain = dfltDomain || [0, 1];
    dfltAnchor = dfltAnchor || (isNumeric(containerIn.position) ? 'free' : (counterAxes[0] || 'free'));
    dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left');
    dfltPosition = dfltPosition || 0;

    var anchor = Lib.coerce(containerIn, containerOut, {
        anchor: {
            valType: 'enumerated',
            values: ['free'].concat(counterAxes),
            dflt: dfltAnchor
        }
    }, 'anchor');

    if(anchor === 'free') coerce('position', dfltPosition);

    Lib.coerce(containerIn, containerOut, {
        side: {
            valType: 'enumerated',
            values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'],
            dflt: dfltSide
        }
    }, 'side');

    var overlaying = false;
    if(overlayableAxes.length) {
        overlaying = Lib.coerce(containerIn, containerOut, {
            overlaying: {
                valType: 'enumerated',
                values: [false].concat(overlayableAxes),
                dflt: false
            }
        }, 'overlaying');
    }

    if(!overlaying) {
        // TODO: right now I'm copying this domain over to overlaying axes
        // in ax.setscale()... but this means we still need (imperfect) logic
        // in the axes popover to hide domain for the overlaying axis.
        // perhaps I should make a private version _domain that all axes get???
        var domain = coerce('domain', dfltDomain);
        if(domain[0] > domain[1] - 0.01) containerOut.domain = dfltDomain;
        Lib.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain);
    }

    coerce('layer');

    return containerOut;
};

},{"../../lib":164,"fast-isnumeric":9}],222:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var FROM_BL = require('../../constants/alignment').FROM_BL;

module.exports = function scaleZoom(ax, factor, centerFraction) {
    if(centerFraction === undefined) {
        centerFraction = FROM_BL[ax.constraintoward || 'center'];
    }

    var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
    var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction;

    ax.range = ax._input.range = [
        ax.l2r(center + (rangeLinear[0] - center) * factor),
        ax.l2r(center + (rangeLinear[1] - center) * factor)
    ];
};

},{"../../constants/alignment":143}],223:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var polybool = require('polybooljs');

var Registry = require('../../registry');
var Color = require('../../components/color');
var Fx = require('../../components/fx');

var polygon = require('../../lib/polygon');
var throttle = require('../../lib/throttle');
var makeEventData = require('../../components/fx/helpers').makeEventData;
var getFromId = require('./axis_ids').getFromId;
var sortModules = require('../sort_modules').sortModules;

var constants = require('./constants');
var MINSELECT = constants.MINSELECT;

var filteredPolygon = polygon.filter;
var polygonTester = polygon.tester;
var multipolygonTester = polygon.multitester;

function getAxId(ax) { return ax._id; }

function prepSelect(e, startX, startY, dragOptions, mode) {
    var gd = dragOptions.gd;
    var fullLayout = gd._fullLayout;
    var zoomLayer = fullLayout._zoomlayer;
    var dragBBox = dragOptions.element.getBoundingClientRect();
    var plotinfo = dragOptions.plotinfo;
    var xs = plotinfo.xaxis._offset;
    var ys = plotinfo.yaxis._offset;
    var x0 = startX - dragBBox.left;
    var y0 = startY - dragBBox.top;
    var x1 = x0;
    var y1 = y0;
    var path0 = 'M' + x0 + ',' + y0;
    var pw = dragOptions.xaxes[0]._length;
    var ph = dragOptions.yaxes[0]._length;
    var xAxisIds = dragOptions.xaxes.map(getAxId);
    var yAxisIds = dragOptions.yaxes.map(getAxId);
    var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes);
    var subtract = e.altKey;

    var filterPoly, testPoly, mergedPolygons, currentPolygon;
    var i, cd, trace, searchInfo, eventData;

    var selectingOnSameSubplot = (
        fullLayout._lastSelectedSubplot &&
        fullLayout._lastSelectedSubplot === plotinfo.id
    );

    if(
        selectingOnSameSubplot &&
        (e.shiftKey || e.altKey) &&
        (plotinfo.selection && plotinfo.selection.polygons) &&
        !dragOptions.polygons
    ) {
        // take over selection polygons from prev mode, if any
        dragOptions.polygons = plotinfo.selection.polygons;
        dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons;
    } else if(
        (!e.shiftKey && !e.altKey) ||
        ((e.shiftKey || e.altKey) && !plotinfo.selection)
    ) {
        // create new polygons, if shift mode or selecting across different subplots
        plotinfo.selection = {};
        plotinfo.selection.polygons = dragOptions.polygons = [];
        plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = [];
    }

    // clear selection outline when selecting a different subplot
    if(!selectingOnSameSubplot) {
        clearSelect(zoomLayer);
        fullLayout._lastSelectedSubplot = plotinfo.id;
    }

    if(mode === 'lasso') {
        filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX);
    }

    var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]);

    outlines.enter()
        .append('path')
        .attr('class', function(d) { return 'select-outline select-outline-' + d + ' select-outline-' + plotinfo.id; })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', path0 + 'Z');

    var corners = zoomLayer.append('path')
        .attr('class', 'zoombox-corners')
        .style({
            fill: Color.background,
            stroke: Color.defaultLine,
            'stroke-width': 1
        })
        .attr('transform', 'translate(' + xs + ', ' + ys + ')')
        .attr('d', 'M0,0Z');


    // find the traces to search for selection points
    var searchTraces = [];
    var throttleID = fullLayout._uid + constants.SELECTID;
    var selection = [];

    for(i = 0; i < gd.calcdata.length; i++) {
        cd = gd.calcdata[i];
        trace = cd[0].trace;

        if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue;

        if(dragOptions.subplot) {
            if(
                trace.subplot === dragOptions.subplot ||
                trace.geo === dragOptions.subplot
            ) {
                searchTraces.push({
                    _module: trace._module,
                    cd: cd,
                    xaxis: dragOptions.xaxes[0],
                    yaxis: dragOptions.yaxes[0]
                });
            }
        } else if(
            trace.type === 'splom' &&
            // FIXME: make sure we don't have more than single axis for splom
            trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]
        ) {
            searchTraces.push({
                _module: trace._module,
                cd: cd,
                xaxis: dragOptions.xaxes[0],
                yaxis: dragOptions.yaxes[0]
            });
        } else {
            if(xAxisIds.indexOf(trace.xaxis) === -1) continue;
            if(yAxisIds.indexOf(trace.yaxis) === -1) continue;

            searchTraces.push({
                _module: trace._module,
                cd: cd,
                xaxis: getFromId(gd, trace.xaxis),
                yaxis: getFromId(gd, trace.yaxis)
            });
        }
    }

    function axValue(ax) {
        var index = (ax._id.charAt(0) === 'y') ? 1 : 0;
        return function(v) { return ax.p2d(v[index]); };
    }

    function ascending(a, b) { return a - b; }

    // allow subplots to override fillRangeItems routine
    var fillRangeItems;

    if(plotinfo.fillRangeItems) {
        fillRangeItems = plotinfo.fillRangeItems;
    } else {
        if(mode === 'select') {
            fillRangeItems = function(eventData, poly) {
                var ranges = eventData.range = {};

                for(i = 0; i < allAxes.length; i++) {
                    var ax = allAxes[i];
                    var axLetter = ax._id.charAt(0);

                    ranges[ax._id] = [
                        ax.p2d(poly[axLetter + 'min']),
                        ax.p2d(poly[axLetter + 'max'])
                    ].sort(ascending);
                }
            };
        } else {
            fillRangeItems = function(eventData, poly, filterPoly) {
                var dataPts = eventData.lassoPoints = {};

                for(i = 0; i < allAxes.length; i++) {
                    var ax = allAxes[i];
                    dataPts[ax._id] = filterPoly.filtered.map(axValue(ax));
                }
            };
        }
    }

    dragOptions.moveFn = function(dx0, dy0) {
        x1 = Math.max(0, Math.min(pw, dx0 + x0));
        y1 = Math.max(0, Math.min(ph, dy0 + y0));

        var dx = Math.abs(x1 - x0),
            dy = Math.abs(y1 - y0);

        if(mode === 'select') {
            var direction = fullLayout.selectdirection;

            if(fullLayout.selectdirection === 'any') {
                if(dy < Math.min(dx * 0.6, MINSELECT)) direction = 'h';
                else if(dx < Math.min(dy * 0.6, MINSELECT)) direction = 'v';
                else direction = 'd';
            }
            else {
                direction = fullLayout.selectdirection;
            }

            if(direction === 'h') {
                // horizontal motion: make a vertical box
                currentPolygon = [[x0, 0], [x0, ph], [x1, ph], [x1, 0]];
                currentPolygon.xmin = Math.min(x0, x1);
                currentPolygon.xmax = Math.max(x0, x1);
                currentPolygon.ymin = Math.min(0, ph);
                currentPolygon.ymax = Math.max(0, ph);
                // extras to guide users in keeping a straight selection
                corners.attr('d', 'M' + currentPolygon.xmin + ',' + (y0 - MINSELECT) +
                    'h-4v' + (2 * MINSELECT) + 'h4Z' +
                    'M' + (currentPolygon.xmax - 1) + ',' + (y0 - MINSELECT) +
                    'h4v' + (2 * MINSELECT) + 'h-4Z');

            }
            else if(direction === 'v') {
                // vertical motion: make a horizontal box
                currentPolygon = [[0, y0], [0, y1], [pw, y1], [pw, y0]];
                currentPolygon.xmin = Math.min(0, pw);
                currentPolygon.xmax = Math.max(0, pw);
                currentPolygon.ymin = Math.min(y0, y1);
                currentPolygon.ymax = Math.max(y0, y1);
                corners.attr('d', 'M' + (x0 - MINSELECT) + ',' + currentPolygon.ymin +
                    'v-4h' + (2 * MINSELECT) + 'v4Z' +
                    'M' + (x0 - MINSELECT) + ',' + (currentPolygon.ymax - 1) +
                    'v4h' + (2 * MINSELECT) + 'v-4Z');
            }
            else if(direction === 'd') {
                // diagonal motion
                currentPolygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
                currentPolygon.xmin = Math.min(x0, x1);
                currentPolygon.xmax = Math.max(x0, x1);
                currentPolygon.ymin = Math.min(y0, y1);
                currentPolygon.ymax = Math.max(y0, y1);
                corners.attr('d', 'M0,0Z');
            }
        }
        else if(mode === 'lasso') {
            filterPoly.addPt([x1, y1]);
            currentPolygon = filterPoly.filtered;
        }

        // create outline & tester
        if(dragOptions.polygons && dragOptions.polygons.length) {
            mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract);
            currentPolygon.subtract = subtract;
            testPoly = multipolygonTester(dragOptions.polygons.concat([currentPolygon]));
        }
        else {
            mergedPolygons = [currentPolygon];
            testPoly = polygonTester(currentPolygon);
        }

        // draw selection
        var paths = [];
        for(i = 0; i < mergedPolygons.length; i++) {
            var ppts = mergedPolygons[i];
            paths.push(ppts.join('L') + 'L' + ppts[0]);
        }
        outlines
            .attr('d', 'M' + paths.join('M') + 'Z');

        throttle.throttle(
            throttleID,
            constants.SELECTDELAY,
            function() {
                selection = [];

                var thisSelection, traceSelections = [], traceSelection;
                for(i = 0; i < searchTraces.length; i++) {
                    searchInfo = searchTraces[i];

                    traceSelection = searchInfo._module.selectPoints(searchInfo, testPoly);
                    traceSelections.push(traceSelection);

                    thisSelection = fillSelectionItem(traceSelection, searchInfo);

                    if(selection.length) {
                        for(var j = 0; j < thisSelection.length; j++) {
                            selection.push(thisSelection[j]);
                        }
                    }
                    else selection = thisSelection;
                }

                eventData = {points: selection};
                updateSelectedState(gd, searchTraces, eventData);
                fillRangeItems(eventData, currentPolygon, filterPoly);
                dragOptions.gd.emit('plotly_selecting', eventData);
            }
        );
    };

    dragOptions.clickFn = function(numClicks, evt) {
        corners.remove();

        throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            if(numClicks === 2) {
                // clear selection on doubleclick
                outlines.remove();
                for(i = 0; i < searchTraces.length; i++) {
                    searchInfo = searchTraces[i];
                    searchInfo._module.selectPoints(searchInfo, false);
                }

                updateSelectedState(gd, searchTraces);
                gd.emit('plotly_deselect', null);
            }
            else {
                // TODO: remove in v2 - this was probably never intended to work as it does,
                // but in case anyone depends on it we don't want to break it now.
                gd.emit('plotly_selected', undefined);
            }

            Fx.click(gd, evt);
        });
    };

    dragOptions.doneFn = function() {
        corners.remove();

        throttle.done(throttleID).then(function() {
            throttle.clear(throttleID);
            dragOptions.gd.emit('plotly_selected', eventData);

            if(currentPolygon && dragOptions.polygons) {
                // save last polygons
                currentPolygon.subtract = subtract;
                dragOptions.polygons.push(currentPolygon);

                // we have to keep reference to arrays container
                dragOptions.mergedPolygons.length = 0;
                [].push.apply(dragOptions.mergedPolygons, mergedPolygons);
            }
        });
    };
}

function updateSelectedState(gd, searchTraces, eventData) {
    var i, j, searchInfo, trace;

    if(eventData) {
        var pts = eventData.points || [];

        for(i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            trace.selectedpoints = [];
            trace._input.selectedpoints = [];
        }

        for(i = 0; i < pts.length; i++) {
            var pt = pts[i];
            var data = pt.data;
            var fullData = pt.fullData;

            if(pt.pointIndices) {
                [].push.apply(data.selectedpoints, pt.pointIndices);
                [].push.apply(fullData.selectedpoints, pt.pointIndices);
            } else {
                data.selectedpoints.push(pt.pointIndex);
                fullData.selectedpoints.push(pt.pointIndex);
            }
        }
    }
    else {
        for(i = 0; i < searchTraces.length; i++) {
            trace = searchTraces[i].cd[0].trace;
            delete trace.selectedpoints;
            delete trace._input.selectedpoints;
        }
    }

    // group searchInfo traces by trace modules
    var lookup = {};

    for(i = 0; i < searchTraces.length; i++) {
        searchInfo = searchTraces[i];

        var name = searchInfo._module.name;
        if(lookup[name]) {
            lookup[name].push(searchInfo);
        } else {
            lookup[name] = [searchInfo];
        }
    }

    var keys = Object.keys(lookup).sort(sortModules);

    for(i = 0; i < keys.length; i++) {
        var items = lookup[keys[i]];
        var len = items.length;
        var item0 = items[0];
        var trace0 = item0.cd[0].trace;
        var _module = item0._module;
        var styleSelection = _module.styleOnSelect || _module.style;

        if(Registry.traceIs(trace0, 'regl')) {
            // plot regl traces per module
            var cds = new Array(len);
            for(j = 0; j < len; j++) {
                cds[j] = items[j].cd;
            }
            styleSelection(gd, cds);
        } else {
            // plot svg trace per trace
            for(j = 0; j < len; j++) {
                styleSelection(gd, items[j].cd);
            }
        }
    }
}

function mergePolygons(list, poly, subtract) {
    var res;

    if(subtract) {
        res = polybool.difference({
            regions: list,
            inverted: false
        }, {
            regions: [poly],
            inverted: false
        });

        return res.regions;
    }

    res = polybool.union({
        regions: list,
        inverted: false
    }, {
        regions: [poly],
        inverted: false
    });

    return res.regions;
}

function fillSelectionItem(selection, searchInfo) {
    if(Array.isArray(selection)) {
        var cd = searchInfo.cd;
        var trace = searchInfo.cd[0].trace;

        for(var i = 0; i < selection.length; i++) {
            selection[i] = makeEventData(selection[i], trace, cd);
        }
    }

    return selection;
}

function clearSelect(zoomlayer) {
    // until we get around to persistent selections, remove the outline
    // here. The selection itself will be removed when the plot redraws
    // at the end.
    zoomlayer.selectAll('.select-outline').remove();
}

module.exports = {
    prepSelect: prepSelect,
    clearSelect: clearSelect
};

},{"../../components/color":43,"../../components/fx":85,"../../components/fx/helpers":82,"../../lib/polygon":176,"../../lib/throttle":186,"../../registry":254,"../sort_modules":252,"./axis_ids":209,"./constants":211,"polybooljs":16}],224:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');
var cleanNumber = Lib.cleanNumber;
var ms2DateTime = Lib.ms2DateTime;
var dateTime2ms = Lib.dateTime2ms;
var ensureNumber = Lib.ensureNumber;

var numConstants = require('../../constants/numerical');
var FP_SAFE = numConstants.FP_SAFE;
var BADNUM = numConstants.BADNUM;

var constants = require('./constants');
var axisIds = require('./axis_ids');

function fromLog(v) {
    return Math.pow(10, v);
}

/**
 * Define the conversion functions for an axis data is used in 5 ways:
 *
 *  d: data, in whatever form it's provided
 *  c: calcdata: turned into numbers, but not linearized
 *  l: linearized - same as c except for log axes (and other nonlinear
 *      mappings later?) this is used when we need to know if it's
 *      *possible* to show some data on this axis, without caring about
 *      the current range
 *  p: pixel value - mapped to the screen with current size and zoom
 *  r: ranges, tick0, and annotation positions match one of the above
 *     but are handled differently for different types:
 *     - linear and date: data format (d)
 *     - category: calcdata format (c), and will stay that way because
 *       the data format has no continuous mapping
 *     - log: linearized (l) format
 *       TODO: in v2.0 we plan to change it to data format. At that point
 *       shapes will work the same way as ranges, tick0, and annotations
 *       so they can use this conversion too.
 *
 * Creates/updates these conversion functions, and a few more utilities
 * like cleanRange, and makeCalcdata
 *
 * also clears the autorange bounds ._min and ._max
 * and the autotick constraints ._minDtick, ._forceTick0
 */
module.exports = function setConvert(ax, fullLayout) {
    fullLayout = fullLayout || {};

    var axLetter = (ax._id || 'x').charAt(0);

    // clipMult: how many axis lengths past the edge do we render?
    // for panning, 1-2 would suffice, but for zooming more is nice.
    // also, clipping can affect the direction of lines off the edge...
    var clipMult = 10;

    function toLog(v, clip) {
        if(v > 0) return Math.log(v) / Math.LN10;

        else if(v <= 0 && clip && ax.range && ax.range.length === 2) {
            // clip NaN (ie past negative infinity) to clipMult axis
            // length past the negative edge
            var r0 = ax.range[0],
                r1 = ax.range[1];
            return 0.5 * (r0 + r1 - 3 * clipMult * Math.abs(r0 - r1));
        }

        else return BADNUM;
    }

    /*
     * wrapped dateTime2ms that:
     * - accepts ms numbers for backward compatibility
     * - inserts a dummy arg so calendar is the 3rd arg (see notes below).
     * - defaults to ax.calendar
     */
    function dt2ms(v, _, calendar) {
        // NOTE: Changed this behavior: previously we took any numeric value
        // to be a ms, even if it was a string that could be a bare year.
        // Now we convert it as a date if at all possible, and only try
        // as (local) ms if that fails.
        var ms = dateTime2ms(v, calendar || ax.calendar);
        if(ms === BADNUM) {
            if(isNumeric(v)) ms = dateTime2ms(new Date(+v));
            else return BADNUM;
        }
        return ms;
    }

    // wrapped ms2DateTime to insert default ax.calendar
    function ms2dt(v, r, calendar) {
        return ms2DateTime(v, r, calendar || ax.calendar);
    }

    function getCategoryName(v) {
        return ax._categories[Math.round(v)];
    }

    /*
     * setCategoryIndex: return the index of category v,
     * inserting it in the list if it's not already there
     *
     * this will enter the categories in the order it
     * encounters them, ie all the categories from the
     * first data set, then all the ones from the second
     * that aren't in the first etc.
     *
     * it is assumed that this function is being invoked in the
     * already sorted category order; otherwise there would be
     * a disconnect between the array and the index returned
     */
    function setCategoryIndex(v) {
        if(v !== null && v !== undefined) {
            if(ax._categoriesMap === undefined) {
                ax._categoriesMap = {};
            }

            if(ax._categoriesMap[v] !== undefined) {
                return ax._categoriesMap[v];
            } else {
                ax._categories.push(v);

                var curLength = ax._categories.length - 1;
                ax._categoriesMap[v] = curLength;

                return curLength;
            }
        }
        return BADNUM;
    }

    function getCategoryIndex(v) {
        // d2l/d2c variant that that won't add categories but will also
        // allow numbers to be mapped to the linearized axis positions
        if(ax._categoriesMap) {
            var index = ax._categoriesMap[v];
            if(index !== undefined) return index;
        }

        if(isNumeric(v)) return +v;
    }

    function l2p(v) {
        if(!isNumeric(v)) return BADNUM;

        // include 2 fractional digits on pixel, for PDF zooming etc
        return d3.round(ax._b + ax._m * v, 2);
    }

    function p2l(px) { return (px - ax._b) / ax._m; }

    // conversions among c/l/p are fairly simple - do them together for all axis types
    ax.c2l = (ax.type === 'log') ? toLog : ensureNumber;
    ax.l2c = (ax.type === 'log') ? fromLog : ensureNumber;

    ax.l2p = l2p;
    ax.p2l = p2l;

    ax.c2p = (ax.type === 'log') ? function(v, clip) { return l2p(toLog(v, clip)); } : l2p;
    ax.p2c = (ax.type === 'log') ? function(px) { return fromLog(p2l(px)); } : p2l;

    /*
     * now type-specific conversions for **ALL** other combinations
     * they're all written out, instead of being combinations of each other, for
     * both clarity and speed.
     */
    if(['linear', '-'].indexOf(ax.type) !== -1) {
        // all are data vals, but d and r need cleaning
        ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber;
        ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber;

        ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
        ax.p2d = ax.p2r = p2l;

        ax.cleanPos = ensureNumber;
    }
    else if(ax.type === 'log') {
        // d and c are data vals, r and l are logged (but d and r need cleaning)
        ax.d2r = ax.d2l = function(v, clip) { return toLog(cleanNumber(v), clip); };
        ax.r2d = ax.r2c = function(v) { return fromLog(cleanNumber(v)); };

        ax.d2c = ax.r2l = cleanNumber;
        ax.c2d = ax.l2r = ensureNumber;

        ax.c2r = toLog;
        ax.l2d = fromLog;

        ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); };
        ax.p2d = function(px) { return fromLog(p2l(px)); };

        ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
        ax.p2r = p2l;

        ax.cleanPos = ensureNumber;
    }
    else if(ax.type === 'date') {
        // r and d are date strings, l and c are ms

        /*
         * Any of these functions with r and d on either side, calendar is the
         * **3rd** argument. log has reserved the second argument.
         *
         * Unless you need the special behavior of the second arg (ms2DateTime
         * uses this to limit precision, toLog uses true to clip negatives
         * to offscreen low rather than undefined), it's safe to pass 0.
         */
        ax.d2r = ax.r2d = Lib.identity;

        ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms;
        ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt;

        ax.d2p = ax.r2p = function(v, _, calendar) { return ax.l2p(dt2ms(v, 0, calendar)); };
        ax.p2d = ax.p2r = function(px, r, calendar) { return ms2dt(p2l(px), r, calendar); };

        ax.cleanPos = function(v) { return Lib.cleanDate(v, BADNUM, ax.calendar); };
    }
    else if(ax.type === 'category') {
        // d is categories (string)
        // c and l are indices (numbers)
        // r is categories or numbers

        ax.d2c = ax.d2l = setCategoryIndex;
        ax.r2d = ax.c2d = ax.l2d = getCategoryName;

        ax.d2r = ax.d2l_noadd = getCategoryIndex;

        ax.r2c = function(v) {
            var index = getCategoryIndex(v);
            return index !== undefined ? index : ax.fraction2r(0.5);
        };

        ax.l2r = ax.c2r = ensureNumber;
        ax.r2l = getCategoryIndex;

        ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
        ax.p2d = function(px) { return getCategoryName(p2l(px)); };
        ax.r2p = ax.d2p;
        ax.p2r = p2l;

        ax.cleanPos = function(v) {
            if(typeof v === 'string' && v !== '') return v;
            return ensureNumber(v);
        };
    }

    // find the range value at the specified (linear) fraction of the axis
    ax.fraction2r = function(v) {
        var rl0 = ax.r2l(ax.range[0]),
            rl1 = ax.r2l(ax.range[1]);
        return ax.l2r(rl0 + v * (rl1 - rl0));
    };

    // find the fraction of the range at the specified range value
    ax.r2fraction = function(v) {
        var rl0 = ax.r2l(ax.range[0]),
            rl1 = ax.r2l(ax.range[1]);
        return (ax.r2l(v) - rl0) / (rl1 - rl0);
    };

    /*
     * cleanRange: make sure range is a couplet of valid & distinct values
     * keep numbers away from the limits of floating point numbers,
     * and dates away from the ends of our date system (+/- 9999 years)
     *
     * optional param rangeAttr: operate on a different attribute, like
     * ax._r, rather than ax.range
     */
    ax.cleanRange = function(rangeAttr, opts) {
        if(!opts) opts = {};
        if(!rangeAttr) rangeAttr = 'range';

        var range = Lib.nestedProperty(ax, rangeAttr).get();
        var i, dflt;

        if(ax.type === 'date') dflt = Lib.dfltRange(ax.calendar);
        else if(axLetter === 'y') dflt = constants.DFLTRANGEY;
        else dflt = opts.dfltRange || constants.DFLTRANGEX;

        // make sure we don't later mutate the defaults
        dflt = dflt.slice();

        if(!range || range.length !== 2) {
            Lib.nestedProperty(ax, rangeAttr).set(dflt);
            return;
        }

        if(ax.type === 'date') {
            // check if milliseconds or js date objects are provided for range
            // and convert to date strings
            range[0] = Lib.cleanDate(range[0], BADNUM, ax.calendar);
            range[1] = Lib.cleanDate(range[1], BADNUM, ax.calendar);
        }

        for(i = 0; i < 2; i++) {
            if(ax.type === 'date') {
                if(!Lib.isDateTime(range[i], ax.calendar)) {
                    ax[rangeAttr] = dflt;
                    break;
                }

                if(ax.r2l(range[0]) === ax.r2l(range[1])) {
                    // split by +/- 1 second
                    var linCenter = Lib.constrain(ax.r2l(range[0]),
                        Lib.MIN_MS + 1000, Lib.MAX_MS - 1000);
                    range[0] = ax.l2r(linCenter - 1000);
                    range[1] = ax.l2r(linCenter + 1000);
                    break;
                }
            }
            else {
                if(!isNumeric(range[i])) {
                    if(isNumeric(range[1 - i])) {
                        range[i] = range[1 - i] * (i ? 10 : 0.1);
                    }
                    else {
                        ax[rangeAttr] = dflt;
                        break;
                    }
                }

                if(range[i] < -FP_SAFE) range[i] = -FP_SAFE;
                else if(range[i] > FP_SAFE) range[i] = FP_SAFE;

                if(range[0] === range[1]) {
                    // somewhat arbitrary: split by 1 or 1ppm, whichever is bigger
                    var inc = Math.max(1, Math.abs(range[0] * 1e-6));
                    range[0] -= inc;
                    range[1] += inc;
                }
            }
        }
    };

    // set scaling to pixels
    ax.setScale = function(usePrivateRange) {
        var gs = fullLayout._size;

        // TODO cleaner way to handle this case
        if(!ax._categories) ax._categories = [];
        // Add a map to optimize the performance of category collection
        if(!ax._categoriesMap) ax._categoriesMap = {};

        // make sure we have a domain (pull it in from the axis
        // this one is overlaying if necessary)
        if(ax.overlaying) {
            var ax2 = axisIds.getFromId({ _fullLayout: fullLayout }, ax.overlaying);
            ax.domain = ax2.domain;
        }

        // While transitions are occuring, occurring, we get a double-transform
        // issue if we transform the drawn layer *and* use the new axis range to
        // draw the data. This allows us to construct setConvert using the pre-
        // interaction values of the range:
        var rangeAttr = (usePrivateRange && ax._r) ? '_r' : 'range',
            calendar = ax.calendar;
        ax.cleanRange(rangeAttr);

        var rl0 = ax.r2l(ax[rangeAttr][0], calendar),
            rl1 = ax.r2l(ax[rangeAttr][1], calendar);

        if(axLetter === 'y') {
            ax._offset = gs.t + (1 - ax.domain[1]) * gs.h;
            ax._length = gs.h * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl0 - rl1);
            ax._b = -ax._m * rl1;
        }
        else {
            ax._offset = gs.l + ax.domain[0] * gs.w;
            ax._length = gs.w * (ax.domain[1] - ax.domain[0]);
            ax._m = ax._length / (rl1 - rl0);
            ax._b = -ax._m * rl0;
        }

        if(!isFinite(ax._m) || !isFinite(ax._b)) {
            fullLayout._replotting = false;
            throw new Error('Something went wrong with axis scaling');
        }
    };

    // makeCalcdata: takes an x or y array and converts it
    // to a position on the axis object "ax"
    // inputs:
    //      trace - a data object from gd.data
    //      axLetter - a string, either 'x' or 'y', for which item
    //          to convert (TODO: is this now always the same as
    //          the first letter of ax._id?)
    // in case the expected data isn't there, make a list of
    // integers based on the opposite data
    ax.makeCalcdata = function(trace, axLetter) {
        var arrayIn, arrayOut, i, len;

        var axType = ax.type;
        var cal = axType === 'date' && trace[axLetter + 'calendar'];

        if(axLetter in trace) {
            arrayIn = trace[axLetter];
            len = trace._length || arrayIn.length;

            if(Lib.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) {
                if(len === arrayIn.length) {
                    return arrayIn;
                } else if(arrayIn.subarray) {
                    return arrayIn.subarray(0, len);
                }
            }

            arrayOut = new Array(len);
            for(i = 0; i < len; i++) {
                arrayOut[i] = ax.d2c(arrayIn[i], 0, cal);
            }
        }
        else {
            var v0 = ((axLetter + '0') in trace) ? ax.d2c(trace[axLetter + '0'], 0, cal) : 0;
            var dv = (trace['d' + axLetter]) ? Number(trace['d' + axLetter]) : 1;

            // the opposing data, for size if we have x and dx etc
            arrayIn = trace[{x: 'y', y: 'x'}[axLetter]];
            len = trace._length || arrayIn.length;
            arrayOut = new Array(len);

            for(i = 0; i < len; i++) {
                arrayOut[i] = v0 + i * dv;
            }
        }

        return arrayOut;
    };

    ax.isValidRange = function(range) {
        return (
            Array.isArray(range) &&
            range.length === 2 &&
            isNumeric(ax.r2l(range[0])) &&
            isNumeric(ax.r2l(range[1]))
        );
    };

    ax.isPtWithinRange = function(d, calendar) {
        var coord = ax.c2l(d[axLetter], null, calendar);
        var r0 = ax.r2l(ax.range[0]);
        var r1 = ax.r2l(ax.range[1]);

        if(r0 < r1) {
            return r0 <= coord && coord <= r1;
        } else {
            // Reversed axis case.
            return r1 <= coord && coord <= r0;
        }
    };

    ax.clearCalc = function() {
        // for autoranging: arrays of objects:
        // {
        //     val: axis value,
        //     pad: pixel padding,
        //     extrapad: boolean, should this val get 5% additional padding
        // }
        ax._min = [];
        ax._max = [];

        // initialize the category list, if there is one, so we start over
        // to be filled in later by ax.d2c
        ax._categories = (ax._initialCategories || []).slice();

        // Build the lookup map for initialized categories
        ax._categoriesMap = {};
        for(var j = 0; j < ax._categories.length; j++) {
            ax._categoriesMap[ax._categories[j]] = j;
        }
    };

    // Propagate localization into the axis so that
    // methods in Axes can use it w/o having to pass fullLayout
    // Default (non-d3) number formatting uses separators directly
    // dates and d3-formatted numbers use the d3 locale
    // Fall back on default format for dummy axes that don't care about formatting
    var locale = fullLayout._d3locale;
    if(ax.type === 'date') {
        ax._dateFormat = locale ? locale.timeFormat.utc : d3.time.format.utc;
        ax._extraFormat = fullLayout._extraFormat;
    }
    // occasionally we need _numFormat to pass through
    // even though it won't be needed by this axis
    ax._separators = fullLayout.separators;
    ax._numFormat = locale ? locale.numberFormat : d3.format;

    // and for bar charts and box plots: reset forced minimum tick spacing
    delete ax._minDtick;
    delete ax._forceTick0;
};

},{"../../constants/numerical":145,"../../lib":164,"./axis_ids":209,"./constants":211,"d3":6,"fast-isnumeric":9}],225:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var layoutAttributes = require('./layout_attributes');

module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
    var showAttrDflt = getShowAttrDflt(containerIn);

    var tickPrefix = coerce('tickprefix');
    if(tickPrefix) coerce('showtickprefix', showAttrDflt);

    var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt);
    if(tickSuffix) coerce('showticksuffix', showAttrDflt);

    var showTickLabels = coerce('showticklabels');
    if(showTickLabels) {
        var font = options.font || {};
        // as with titlefont.color, inherit axis.color only if one was
        // explicitly provided
        var dfltFontColor = (containerOut.color === containerIn.color) ?
            containerOut.color : font.color;
        Lib.coerceFont(coerce, 'tickfont', {
            family: font.family,
            size: font.size,
            color: dfltFontColor
        });
        coerce('tickangle');

        if(axType !== 'category') {
            var tickFormat = coerce('tickformat');
            tickformatstopsDefaults(containerIn, containerOut);
            if(!tickFormat && axType !== 'date') {
                coerce('showexponent', showAttrDflt);
                coerce('exponentformat');
                coerce('separatethousands');
            }
        }
    }
};

/*
 * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
 * share values.
 *
 * If only 1 attribute is set,
 * the remaining attributes inherit that value.
 *
 * If 2 attributes are set to the same value,
 * the remaining attribute inherits that value.
 *
 * If 2 attributes are set to different values,
 * the remaining is set to its dflt value.
 *
 */
function getShowAttrDflt(containerIn) {
    var showAttrsAll = ['showexponent',
            'showtickprefix',
            'showticksuffix'],
        showAttrs = showAttrsAll.filter(function(a) {
            return containerIn[a] !== undefined;
        }),
        sameVal = function(a) {
            return containerIn[a] === containerIn[showAttrs[0]];
        };

    if(showAttrs.every(sameVal) || showAttrs.length === 1) {
        return containerIn[showAttrs[0]];
    }
}

function tickformatstopsDefaults(tickformatIn, tickformatOut) {
    var valuesIn = tickformatIn.tickformatstops;
    var valuesOut = tickformatOut.tickformatstops = [];

    if(!Array.isArray(valuesIn)) return;

    var valueIn, valueOut;

    function coerce(attr, dflt) {
        return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
    }

    for(var i = 0; i < valuesIn.length; i++) {
        valueIn = valuesIn[i];
        valueOut = {};

        coerce('dtickrange');
        coerce('value');

        valuesOut.push(valueOut);
    }
}

},{"../../lib":164,"./layout_attributes":218}],226:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');

var layoutAttributes = require('./layout_attributes');


/**
 * options: inherits outerTicks from axes.handleAxisDefaults
 */
module.exports = function handleTickDefaults(containerIn, containerOut, coerce, options) {
    var tickLen = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'ticklen'),
        tickWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickwidth'),
        tickColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickcolor', containerOut.color),
        showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : '');

    if(!showTicks) {
        delete containerOut.ticklen;
        delete containerOut.tickwidth;
        delete containerOut.tickcolor;
    }
};

},{"../../lib":164,"./layout_attributes":218}],227:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var Lib = require('../../lib');
var ONEDAY = require('../../constants/numerical').ONEDAY;


module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) {
    var tickmodeDefault = 'auto';

    if(containerIn.tickmode === 'array' &&
            (axType === 'log' || axType === 'date')) {
        containerIn.tickmode = 'auto';
    }

    if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array';
    else if(containerIn.dtick) {
        tickmodeDefault = 'linear';
    }
    var tickmode = coerce('tickmode', tickmodeDefault);

    if(tickmode === 'auto') coerce('nticks');
    else if(tickmode === 'linear') {
        // dtick is usually a positive number, but there are some
        // special strings available for log or date axes
        // default is 1 day for dates, otherwise 1
        var dtickDflt = (axType === 'date') ? ONEDAY : 1;
        var dtick = coerce('dtick', dtickDflt);
        if(isNumeric(dtick)) {
            containerOut.dtick = (dtick > 0) ? Number(dtick) : dtickDflt;
        }
        else if(typeof dtick !== 'string') {
            containerOut.dtick = dtickDflt;
        }
        else {
            // date and log special cases are all one character plus a number
            var prefix = dtick.charAt(0),
                dtickNum = dtick.substr(1);

            dtickNum = isNumeric(dtickNum) ? Number(dtickNum) : 0;
            if((dtickNum <= 0) || !(
                    // "M<n>" gives ticks every (integer) n months
                    (axType === 'date' && prefix === 'M' && dtickNum === Math.round(dtickNum)) ||
                    // "L<f>" gives ticks linearly spaced in data (not in position) every (float) f
                    (axType === 'log' && prefix === 'L') ||
                    // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5
                    (axType === 'log' && prefix === 'D' && (dtickNum === 1 || dtickNum === 2))
                )) {
                containerOut.dtick = dtickDflt;
            }
        }

        // tick0 can have different valType for different axis types, so
        // validate that now. Also for dates, change milliseconds to date strings
        var tick0Dflt = (axType === 'date') ? Lib.dateTick0(containerOut.calendar) : 0;
        var tick0 = coerce('tick0', tick0Dflt);
        if(axType === 'date') {
            containerOut.tick0 = Lib.cleanDate(tick0, tick0Dflt);
        }
        // Aside from date axes, dtick must be numeric; D1 and D2 modes ignore tick0 entirely
        else if(isNumeric(tick0) && dtick !== 'D1' && dtick !== 'D2') {
            containerOut.tick0 = Number(tick0);
        }
        else {
            containerOut.tick0 = tick0Dflt;
        }
    }
    else {
        var tickvals = coerce('tickvals');
        if(tickvals === undefined) containerOut.tickmode = 'auto';
        else coerce('ticktext');
    }
};

},{"../../constants/numerical":145,"../../lib":164,"fast-isnumeric":9}],228:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Drawing = require('../../components/drawing');
var Axes = require('./axes');
var axisRegex = require('./constants').attrRegex;

module.exports = function transitionAxes(gd, newLayout, transitionOpts, makeOnCompleteCallback) {
    var fullLayout = gd._fullLayout;
    var axes = [];

    function computeUpdates(layout) {
        var ai, attrList, match, axis, update;
        var updates = {};

        for(ai in layout) {
            attrList = ai.split('.');
            match = attrList[0].match(axisRegex);
            if(match) {
                var axisLetter = ai.charAt(0);
                var axisName = attrList[0];
                axis = fullLayout[axisName];
                update = {};

                if(Array.isArray(layout[ai])) {
                    update.to = layout[ai].slice(0);
                } else {
                    if(Array.isArray(layout[ai].range)) {
                        update.to = layout[ai].range.slice(0);
                    }
                }
                if(!update.to) continue;

                update.axisName = axisName;
                update.length = axis._length;

                axes.push(axisLetter);

                updates[axisLetter] = update;
            }
        }

        return updates;
    }

    function computeAffectedSubplots(fullLayout, updatedAxisIds, updates) {
        var plotName;
        var plotinfos = fullLayout._plots;
        var affectedSubplots = [];
        var toX, toY;

        for(plotName in plotinfos) {
            var plotinfo = plotinfos[plotName];

            if(affectedSubplots.indexOf(plotinfo) !== -1) continue;

            var x = plotinfo.xaxis._id;
            var y = plotinfo.yaxis._id;
            var fromX = plotinfo.xaxis.range;
            var fromY = plotinfo.yaxis.range;

            // Store the initial range at the beginning of this transition:
            plotinfo.xaxis._r = plotinfo.xaxis.range.slice();
            plotinfo.yaxis._r = plotinfo.yaxis.range.slice();

            if(updates[x]) {
                toX = updates[x].to;
            } else {
                toX = fromX;
            }
            if(updates[y]) {
                toY = updates[y].to;
            } else {
                toY = fromY;
            }

            if(fromX[0] === toX[0] && fromX[1] === toX[1] && fromY[0] === toY[0] && fromY[1] === toY[1]) continue;

            if(updatedAxisIds.indexOf(x) !== -1 || updatedAxisIds.indexOf(y) !== -1) {
                affectedSubplots.push(plotinfo);
            }
        }

        return affectedSubplots;
    }

    var updates = computeUpdates(newLayout);
    var updatedAxisIds = Object.keys(updates);
    var affectedSubplots = computeAffectedSubplots(fullLayout, updatedAxisIds, updates);

    function updateLayoutObjs() {
        function redrawObjs(objArray, method, shortCircuit) {
            for(var i = 0; i < objArray.length; i++) {
                method(gd, i);

                // once is enough for images (which doesn't use the `i` arg anyway)
                if(shortCircuit) return;
            }
        }

        redrawObjs(fullLayout.annotations || [], Registry.getComponentMethod('annotations', 'drawOne'));
        redrawObjs(fullLayout.shapes || [], Registry.getComponentMethod('shapes', 'drawOne'));
        redrawObjs(fullLayout.images || [], Registry.getComponentMethod('images', 'draw'), true);
    }

    if(!affectedSubplots.length) {
        updateLayoutObjs();
        return false;
    }

    function ticksAndAnnotations(xa, ya) {
        var activeAxIds = [],
            i;

        activeAxIds = [xa._id, ya._id];

        for(i = 0; i < activeAxIds.length; i++) {
            Axes.doTicks(gd, activeAxIds[i], true);
        }

        function redrawObjs(objArray, method, shortCircuit) {
            for(i = 0; i < objArray.length; i++) {
                var obji = objArray[i];

                if((activeAxIds.indexOf(obji.xref) !== -1) ||
                    (activeAxIds.indexOf(obji.yref) !== -1)) {
                    method(gd, i);
                }

                // once is enough for images (which doesn't use the `i` arg anyway)
                if(shortCircuit) return;
            }
        }

        redrawObjs(fullLayout.annotations || [], Registry.getComponentMethod('annotations', 'drawOne'));
        redrawObjs(fullLayout.shapes || [], Registry.getComponentMethod('shapes', 'drawOne'));
        redrawObjs(fullLayout.images || [], Registry.getComponentMethod('images', 'draw'), true);
    }

    function unsetSubplotTransform(subplot) {
        var xa2 = subplot.xaxis;
        var ya2 = subplot.yaxis;

        fullLayout._defs.select('#' + subplot.clipId + '> rect')
            .call(Drawing.setTranslate, 0, 0)
            .call(Drawing.setScale, 1, 1);

        subplot.plot
            .call(Drawing.setTranslate, xa2._offset, ya2._offset)
            .call(Drawing.setScale, 1, 1);

        var traceGroups = subplot.plot.selectAll('.scatterlayer .trace');

        // This is specifically directed at scatter traces, applying an inverse
        // scale to individual points to counteract the scale of the trace
        // as a whole:
        traceGroups.selectAll('.point')
            .call(Drawing.setPointGroupScale, 1, 1);
        traceGroups.selectAll('.textpoint')
            .call(Drawing.setTextPointsScale, 1, 1);
        traceGroups
            .call(Drawing.hideOutsideRangePoints, subplot);
    }

    function updateSubplot(subplot, progress) {
        var axis, r0, r1;
        var xUpdate = updates[subplot.xaxis._id];
        var yUpdate = updates[subplot.yaxis._id];

        var viewBox = [];

        if(xUpdate) {
            axis = gd._fullLayout[xUpdate.axisName];
            r0 = axis._r;
            r1 = xUpdate.to;
            viewBox[0] = (r0[0] * (1 - progress) + progress * r1[0] - r0[0]) / (r0[1] - r0[0]) * subplot.xaxis._length;
            var dx1 = r0[1] - r0[0];
            var dx2 = r1[1] - r1[0];

            axis.range[0] = r0[0] * (1 - progress) + progress * r1[0];
            axis.range[1] = r0[1] * (1 - progress) + progress * r1[1];

            viewBox[2] = subplot.xaxis._length * ((1 - progress) + progress * dx2 / dx1);
        } else {
            viewBox[0] = 0;
            viewBox[2] = subplot.xaxis._length;
        }

        if(yUpdate) {
            axis = gd._fullLayout[yUpdate.axisName];
            r0 = axis._r;
            r1 = yUpdate.to;
            viewBox[1] = (r0[1] * (1 - progress) + progress * r1[1] - r0[1]) / (r0[0] - r0[1]) * subplot.yaxis._length;
            var dy1 = r0[1] - r0[0];
            var dy2 = r1[1] - r1[0];

            axis.range[0] = r0[0] * (1 - progress) + progress * r1[0];
            axis.range[1] = r0[1] * (1 - progress) + progress * r1[1];

            viewBox[3] = subplot.yaxis._length * ((1 - progress) + progress * dy2 / dy1);
        } else {
            viewBox[1] = 0;
            viewBox[3] = subplot.yaxis._length;
        }

        ticksAndAnnotations(subplot.xaxis, subplot.yaxis);

        var xa2 = subplot.xaxis;
        var ya2 = subplot.yaxis;

        var editX = !!xUpdate;
        var editY = !!yUpdate;

        var xScaleFactor = editX ? xa2._length / viewBox[2] : 1,
            yScaleFactor = editY ? ya2._length / viewBox[3] : 1;

        var clipDx = editX ? viewBox[0] : 0,
            clipDy = editY ? viewBox[1] : 0;

        var fracDx = editX ? (viewBox[0] / viewBox[2] * xa2._length) : 0,
            fracDy = editY ? (viewBox[1] / viewBox[3] * ya2._length) : 0;

        var plotDx = xa2._offset - fracDx,
            plotDy = ya2._offset - fracDy;

        subplot.clipRect
            .call(Drawing.setTranslate, clipDx, clipDy)
            .call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);

        subplot.plot
            .call(Drawing.setTranslate, plotDx, plotDy)
            .call(Drawing.setScale, xScaleFactor, yScaleFactor)

            // This is specifically directed at scatter traces, applying an inverse
            // scale to individual points to counteract the scale of the trace
            // as a whole:
            .selectAll('.points').selectAll('.point')
                .call(Drawing.setPointGroupScale, 1 / xScaleFactor, 1 / yScaleFactor);

        subplot.plot.selectAll('.points').selectAll('.textpoint')
            .call(Drawing.setTextPointsScale, 1 / xScaleFactor, 1 / yScaleFactor);
    }

    var onComplete;
    if(makeOnCompleteCallback) {
        // This module makes the choice whether or not it notifies Plotly.transition
        // about completion:
        onComplete = makeOnCompleteCallback();
    }

    function transitionComplete() {
        var aobj = {};
        for(var i = 0; i < updatedAxisIds.length; i++) {
            var axi = gd._fullLayout[updates[updatedAxisIds[i]].axisName];
            var to = updates[updatedAxisIds[i]].to;
            aobj[axi._name + '.range[0]'] = to[0];
            aobj[axi._name + '.range[1]'] = to[1];

            axi.range = to.slice();
        }

        // Signal that this transition has completed:
        onComplete && onComplete();

        return Registry.call('relayout', gd, aobj).then(function() {
            for(var i = 0; i < affectedSubplots.length; i++) {
                unsetSubplotTransform(affectedSubplots[i]);
            }
        });
    }

    function transitionInterrupt() {
        var aobj = {};
        for(var i = 0; i < updatedAxisIds.length; i++) {
            var axi = gd._fullLayout[updatedAxisIds[i] + 'axis'];
            aobj[axi._name + '.range[0]'] = axi.range[0];
            aobj[axi._name + '.range[1]'] = axi.range[1];

            axi.range = axi._r.slice();
        }

        return Registry.call('relayout', gd, aobj).then(function() {
            for(var i = 0; i < affectedSubplots.length; i++) {
                unsetSubplotTransform(affectedSubplots[i]);
            }
        });
    }

    var t1, t2, raf;
    var easeFn = d3.ease(transitionOpts.easing);

    gd._transitionData._interruptCallbacks.push(function() {
        window.cancelAnimationFrame(raf);
        raf = null;
        return transitionInterrupt();
    });

    function doFrame() {
        t2 = Date.now();

        var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration);
        var progress = easeFn(tInterp);

        for(var i = 0; i < affectedSubplots.length; i++) {
            updateSubplot(affectedSubplots[i], progress);
        }

        if(t2 - t1 > transitionOpts.duration) {
            transitionComplete();
            raf = window.cancelAnimationFrame(doFrame);
        } else {
            raf = window.requestAnimationFrame(doFrame);
        }
    }

    t1 = Date.now();
    raf = window.requestAnimationFrame(doFrame);

    return Promise.resolve();
};

},{"../../components/drawing":68,"../../registry":254,"./axes":206,"./constants":211,"d3":6}],229:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');
var autoType = require('./axis_autotype');
var name2id = require('./axis_ids').name2id;

/*
 *  data: the plot data to use in choosing auto type
 *  name: axis object name (ie 'xaxis') if one should be stored
 */
module.exports = function handleTypeDefaults(containerIn, containerOut, coerce, data, name) {
    // set up some private properties
    if(name) {
        containerOut._name = name;
        containerOut._id = name2id(name);
    }

    var axType = coerce('type');
    if(axType === '-') {
        setAutoType(containerOut, data);

        if(containerOut.type === '-') {
            containerOut.type = 'linear';
        }
        else {
            // copy autoType back to input axis
            // note that if this object didn't exist
            // in the input layout, we have to put it in
            // this happens in the main supplyDefaults function
            containerIn.type = containerOut.type;
        }
    }
};

function setAutoType(ax, data) {
    // new logic: let people specify any type they want,
    // only autotype if type is '-'
    if(ax.type !== '-') return;

    var id = ax._id;
    var axLetter = id.charAt(0);

    // support 3d
    if(id.indexOf('scene') !== -1) id = axLetter;

    var d0 = getFirstNonEmptyTrace(data, id, axLetter);
    if(!d0) return;

    // first check for histograms, as the count direction
    // should always default to a linear axis
    if(d0.type === 'histogram' &&
            axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) {
        ax.type = 'linear';
        return;
    }

    var calAttr = axLetter + 'calendar';
    var calendar = d0[calAttr];
    var i;

    // check all boxes on this x axis to see
    // if they're dates, numbers, or categories
    if(isBoxWithoutPositionCoords(d0, axLetter)) {
        var posLetter = getBoxPosLetter(d0);
        var boxPositions = [];

        for(i = 0; i < data.length; i++) {
            var trace = data[i];
            if(!Registry.traceIs(trace, 'box-violin') ||
               (trace[axLetter + 'axis'] || axLetter) !== id) continue;

            if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]);
            else if(trace.name !== undefined) boxPositions.push(trace.name);
            else boxPositions.push('text');

            if(trace[calAttr] !== calendar) calendar = undefined;
        }

        ax.type = autoType(boxPositions, calendar);
    }
    else if(d0.type === 'splom') {
        var dimensions = d0.dimensions;
        for(i = 0; i < dimensions.length; i++) {
            var dim = dimensions[i];
            if(dim.visible) {
                ax.type = autoType(dim.values, calendar);
                break;
            }
        }
    }
    else {
        ax.type = autoType(d0[axLetter] || [d0[axLetter + '0']], calendar);
    }
}

function getFirstNonEmptyTrace(data, id, axLetter) {
    for(var i = 0; i < data.length; i++) {
        var trace = data[i];

        if(trace.type === 'splom' &&
                trace._length > 0 &&
                trace['_' + axLetter + 'axes'][id]
        ) {
            return trace;
        }

        if((trace[axLetter + 'axis'] || axLetter) === id) {
            if(isBoxWithoutPositionCoords(trace, axLetter)) {
                return trace;
            }
            else if((trace[axLetter] || []).length || trace[axLetter + '0']) {
                return trace;
            }
        }
    }
}

function getBoxPosLetter(trace) {
    return {v: 'x', h: 'y'}[trace.orientation || 'v'];
}

function isBoxWithoutPositionCoords(trace, axLetter) {
    var posLetter = getBoxPosLetter(trace),
        isBox = Registry.traceIs(trace, 'box-violin'),
        isCandlestick = Registry.traceIs(trace._fullInput || {}, 'candlestick');

    return (
        isBox &&
        !isCandlestick &&
        axLetter === posLetter &&
        trace[posLetter] === undefined &&
        trace[posLetter + '0'] === undefined
    );
}

},{"../../registry":254,"./axis_autotype":207,"./axis_ids":209}],230:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../registry');
var Lib = require('../lib');

/*
 * Create or update an observer. This function is designed to be
 * idempotent so that it can be called over and over as the component
 * updates, and will attach and detach listeners as needed.
 *
 * @param {optional object} container
 *      An object on which the observer is stored. This is the mechanism
 *      by which it is idempotent. If it already exists, another won't be
 *      added. Each time it's called, the value lookup table is updated.
 * @param {array} commandList
 *      An array of commands, following either `buttons` of `updatemenus`
 *      or `steps` of `sliders`.
 * @param {function} onchange
 *      A listener called when the value is changed. Receives data object
 *      with information about the new state.
 */
exports.manageCommandObserver = function(gd, container, commandList, onchange) {
    var ret = {};
    var enabled = true;

    if(container && container._commandObserver) {
        ret = container._commandObserver;
    }

    if(!ret.cache) {
        ret.cache = {};
    }

    // Either create or just recompute this:
    ret.lookupTable = {};

    var binding = exports.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable);

    if(container && container._commandObserver) {
        if(!binding) {
            // If container exists and there are no longer any bindings,
            // remove existing:
            if(container._commandObserver.remove) {
                container._commandObserver.remove();
                container._commandObserver = null;
                return ret;
            }
        } else {
            // If container exists and there *are* bindings, then the lookup
            // table should have been updated and check is already attached,
            // so there's nothing to be done:
            return ret;


        }
    }

    // Determine whether there's anything to do for this binding:

    if(binding) {
        // Build the cache:
        bindingValueHasChanged(gd, binding, ret.cache);

        ret.check = function check() {
            if(!enabled) return;

            var update = bindingValueHasChanged(gd, binding, ret.cache);

            if(update.changed && onchange) {
                // Disable checks for the duration of this command in order to avoid
                // infinite loops:
                if(ret.lookupTable[update.value] !== undefined) {
                    ret.disable();
                    Promise.resolve(onchange({
                        value: update.value,
                        type: binding.type,
                        prop: binding.prop,
                        traces: binding.traces,
                        index: ret.lookupTable[update.value]
                    })).then(ret.enable, ret.enable);
                }
            }

            return update.changed;
        };

        var checkEvents = [
            'plotly_relayout',
            'plotly_redraw',
            'plotly_restyle',
            'plotly_update',
            'plotly_animatingframe',
            'plotly_afterplot'
        ];

        for(var i = 0; i < checkEvents.length; i++) {
            gd._internalOn(checkEvents[i], ret.check);
        }

        ret.remove = function() {
            for(var i = 0; i < checkEvents.length; i++) {
                gd._removeInternalListener(checkEvents[i], ret.check);
            }
        };
    } else {
        // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning
        // is a start
        Lib.log('Unable to automatically bind plot updates to API command');

        ret.lookupTable = {};
        ret.remove = function() {};
    }

    ret.disable = function disable() {
        enabled = false;
    };

    ret.enable = function enable() {
        enabled = true;
    };

    if(container) {
        container._commandObserver = ret;
    }

    return ret;
};

/*
 * This function checks to see if an array of objects containing
 * method and args properties is compatible with automatic two-way
 * binding. The criteria right now are that
 *
 *   1. multiple traces may be affected
 *   2. only one property may be affected
 *   3. the same property must be affected by all commands
 */
exports.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) {
    var i;
    var n = commandList.length;

    var refBinding;

    for(i = 0; i < n; i++) {
        var binding;
        var command = commandList[i];
        var method = command.method;
        var args = command.args;

        if(!Array.isArray(args)) args = [];

        // If any command has no method, refuse to bind:
        if(!method) {
            return false;
        }
        var bindings = exports.computeAPICommandBindings(gd, method, args);

        // Right now, handle one and *only* one property being set:
        if(bindings.length !== 1) {
            return false;
        }

        if(!refBinding) {
            refBinding = bindings[0];
            if(Array.isArray(refBinding.traces)) {
                refBinding.traces.sort();
            }
        } else {
            binding = bindings[0];
            if(binding.type !== refBinding.type) {
                return false;
            }
            if(binding.prop !== refBinding.prop) {
                return false;
            }
            if(Array.isArray(refBinding.traces)) {
                if(Array.isArray(binding.traces)) {
                    binding.traces.sort();
                    for(var j = 0; j < refBinding.traces.length; j++) {
                        if(refBinding.traces[j] !== binding.traces[j]) {
                            return false;
                        }
                    }
                } else {
                    return false;
                }
            } else {
                if(binding.prop !== refBinding.prop) {
                    return false;
                }
            }
        }

        binding = bindings[0];
        var value = binding.value;
        if(Array.isArray(value)) {
            if(value.length === 1) {
                value = value[0];
            } else {
                return false;
            }
        }
        if(bindingsByValue) {
            bindingsByValue[value] = i;
        }
    }

    return refBinding;
};

function bindingValueHasChanged(gd, binding, cache) {
    var container, value, obj;
    var changed = false;

    if(binding.type === 'data') {
        // If it's data, we need to get a trace. Based on the limited scope
        // of what we cover, we can just take the first trace from the list,
        // or otherwise just the first trace:
        container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0];
    } else if(binding.type === 'layout') {
        container = gd._fullLayout;
    } else {
        return false;
    }

    value = Lib.nestedProperty(container, binding.prop).get();

    obj = cache[binding.type] = cache[binding.type] || {};

    if(obj.hasOwnProperty(binding.prop)) {
        if(obj[binding.prop] !== value) {
            changed = true;
        }
    }

    obj[binding.prop] = value;

    return {
        changed: changed,
        value: value
    };
}

/*
 * Execute an API command. There's really not much to this; it just provides
 * a common hook so that implementations don't need to be synchronized across
 * multiple components with the ability to invoke API commands.
 *
 * @param {string} method
 *      The name of the plotly command to execute. Must be one of 'animate',
 *      'restyle', 'relayout', 'update'.
 * @param {array} args
 *      A list of arguments passed to the API command
 */
exports.executeAPICommand = function(gd, method, args) {
    if(method === 'skip') return Promise.resolve();

    var _method = Registry.apiMethodRegistry[method];
    var allArgs = [gd];
    if(!Array.isArray(args)) args = [];

    for(var i = 0; i < args.length; i++) {
        allArgs.push(args[i]);
    }

    return _method.apply(null, allArgs).catch(function(err) {
        Lib.warn('API call to Plotly.' + method + ' rejected.', err);
        return Promise.reject(err);
    });
};

exports.computeAPICommandBindings = function(gd, method, args) {
    var bindings;

    if(!Array.isArray(args)) args = [];

    switch(method) {
        case 'restyle':
            bindings = computeDataBindings(gd, args);
            break;
        case 'relayout':
            bindings = computeLayoutBindings(gd, args);
            break;
        case 'update':
            bindings = computeDataBindings(gd, [args[0], args[2]])
                .concat(computeLayoutBindings(gd, [args[1]]));
            break;
        case 'animate':
            bindings = computeAnimateBindings(gd, args);
            break;
        default:
            // This is the case where intelligent logic about what affects
            // this command is not implemented. It causes no ill effects.
            // For example, addFrames simply won't bind to a control component.
            bindings = [];
    }
    return bindings;
};

function computeAnimateBindings(gd, args) {
    // We'll assume that the only relevant modification an animation
    // makes that's meaningfully tracked is the frame:
    if(Array.isArray(args[0]) && args[0].length === 1 && ['string', 'number'].indexOf(typeof args[0][0]) !== -1) {
        return [{type: 'layout', prop: '_currentFrame', value: args[0][0].toString()}];
    } else {
        return [];
    }
}

function computeLayoutBindings(gd, args) {
    var bindings = [];

    var astr = args[0];
    var aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = args[1];
    } else if(Lib.isPlainObject(astr)) {
        aobj = astr;
    } else {
        return bindings;
    }

    crawl(aobj, function(path, attrName, attr) {
        bindings.push({type: 'layout', prop: path, value: attr});
    }, '', 0);

    return bindings;
}

function computeDataBindings(gd, args) {
    var traces, astr, val, aobj;
    var bindings = [];

    // Logic copied from Plotly.restyle:
    astr = args[0];
    val = args[1];
    traces = args[2];
    aobj = {};
    if(typeof astr === 'string') {
        aobj[astr] = val;
    } else if(Lib.isPlainObject(astr)) {
        // the 3-arg form
        aobj = astr;

        if(traces === undefined) {
            traces = val;
        }
    } else {
        return bindings;
    }

    if(traces === undefined) {
        // Explicitly assign this to null instead of undefined:
        traces = null;
    }

    crawl(aobj, function(path, attrName, attr) {
        var thisTraces;
        if(Array.isArray(attr)) {
            var nAttr = Math.min(attr.length, gd.data.length);
            if(traces) {
                nAttr = Math.min(nAttr, traces.length);
            }
            thisTraces = [];
            for(var j = 0; j < nAttr; j++) {
                thisTraces[j] = traces ? traces[j] : j;
            }
        } else {
            thisTraces = traces ? traces.slice(0) : null;
        }

        // Convert [7] to just 7 when traces is null:
        if(thisTraces === null) {
            if(Array.isArray(attr)) {
                attr = attr[0];
            }
        } else if(Array.isArray(thisTraces)) {
            if(!Array.isArray(attr)) {
                var tmp = attr;
                attr = [];
                for(var i = 0; i < thisTraces.length; i++) {
                    attr[i] = tmp;
                }
            }
            attr.length = Math.min(thisTraces.length, attr.length);
        }

        bindings.push({
            type: 'data',
            prop: path,
            traces: thisTraces,
            value: attr
        });
    }, '', 0);

    return bindings;
}

function crawl(attrs, callback, path, depth) {
    Object.keys(attrs).forEach(function(attrName) {
        var attr = attrs[attrName];

        if(attrName[0] === '_') return;

        var thisPath = path + (depth > 0 ? '.' : '') + attrName;

        if(Lib.isPlainObject(attr)) {
            crawl(attr, callback, thisPath, depth + 1);
        } else {
            // Only execute the callback on leaf nodes:
            callback(thisPath, attrName, attr);
        }
    });
}

},{"../lib":164,"../registry":254}],231:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var extendFlat = require('../lib/extend').extendFlat;

/**
 * Make a xy domain attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.name: name to be inserted in the default description
 *   @param {boolean}
 *     opts.trace: set to true for trace containers
 *   @param {string}
 *     opts.editType: editType for all pieces
 *   @param {boolean}
 *     opts.noGridCell: set to true to omit `row` and `column`
 *
 * @param {object} extra
 *   @param {string}
 *     extra.description: extra description. N.B we use
 *     a separate extra container to make it compatible with
 *     the compress_attributes transform.
 *
 * @return {object} attributes object containing {x,y} as specified
 */
exports.attributes = function(opts, extra) {
    opts = opts || {};
    extra = extra || {};

    var base = {
        valType: 'info_array',
        
        editType: opts.editType,
        items: [
            {valType: 'number', min: 0, max: 1, editType: opts.editType},
            {valType: 'number', min: 0, max: 1, editType: opts.editType}
        ],
        dflt: [0, 1]
    };

    var namePart = opts.name ? opts.name + ' ' : '';
    var contPart = opts.trace ? 'trace ' : 'subplot ';
    var descPart = extra.description ? ' ' + extra.description : '';

    var out = {
        x: extendFlat({}, base, {
            
        }),
        y: extendFlat({}, base, {
            
        }),
        editType: opts.editType
    };

    if(!opts.noGridCell) {
        out.row = {
            valType: 'integer',
            min: 0,
            dflt: 0,
            
            editType: opts.editType,
            
        };
        out.column = {
            valType: 'integer',
            min: 0,
            dflt: 0,
            
            editType: opts.editType,
            
        };
    }

    return out;
};

exports.defaults = function(containerOut, layout, coerce, dfltDomains) {
    var dfltX = (dfltDomains && dfltDomains.x) || [0, 1];
    var dfltY = (dfltDomains && dfltDomains.y) || [0, 1];

    var grid = layout.grid;
    if(grid) {
        var column = coerce('domain.column');
        if(column !== undefined) {
            if(column < grid.columns) dfltX = grid._domains.x[column];
            else delete containerOut.domain.column;
        }

        var row = coerce('domain.row');
        if(row !== undefined) {
            if(row < grid.rows) dfltY = grid._domains.y[row];
            else delete containerOut.domain.row;
        }
    }

    coerce('domain.x', dfltX);
    coerce('domain.y', dfltY);
};

},{"../lib/extend":157}],232:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

/*
 * make a font attribute group
 *
 * @param {object} opts
 *   @param {string}
 *     opts.description: where & how this font is used
 *   @param {optional bool} arrayOk:
 *     should each part (family, size, color) be arrayOk? default false.
 *   @param {string} editType:
 *     the editType for all pieces of this font
 *   @param {optional string} colorEditType:
 *     a separate editType just for color
 *
 * @return {object} attributes object containing {family, size, color} as specified
 */
module.exports = function(opts) {
    var editType = opts.editType;
    var colorEditType = opts.colorEditType;
    if(colorEditType === undefined) colorEditType = editType;
    var attrs = {
        family: {
            valType: 'string',
            
            noBlank: true,
            strict: true,
            editType: editType,
            
        },
        size: {
            valType: 'number',
            
            min: 1,
            editType: editType
        },
        color: {
            valType: 'color',
            
            editType: colorEditType
        },
        editType: editType,
        // blank strings so compress_attributes can remove
        // TODO - that's uber hacky... better solution?
        
    };

    if(opts.arrayOk) {
        attrs.family.arrayOk = true;
        attrs.size.arrayOk = true;
        attrs.color.arrayOk = true;
    }

    return attrs;
};

},{}],233:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    _isLinkedToArray: 'frames_entry',

    group: {
        valType: 'string',
        
        
    },
    name: {
        valType: 'string',
        
        
    },
    traces: {
        valType: 'any',
        
        
    },
    baseframe: {
        valType: 'string',
        
        
    },
    data: {
        valType: 'any',
        
        
    },
    layout: {
        valType: 'any',
        
        
    }
};

},{}],234:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Registry = require('../registry');
var SUBPLOT_PATTERN = require('./cartesian/constants').SUBPLOT_PATTERN;

/**
 * Get calcdata trace(s) associated with a given subplot
 *
 * @param {array} calcData: as in gd.calcdata
 * @param {string} type: subplot type
 * @param {string} subplotId: subplot id to look for
 *
 * @return {array} array of calcdata traces
 */
exports.getSubplotCalcData = function(calcData, type, subplotId) {
    var basePlotModule = Registry.subplotsRegistry[type];
    if(!basePlotModule) return [];

    var attr = basePlotModule.attr;
    var subplotCalcData = [];

    for(var i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];
        var trace = calcTrace[0].trace;

        if(trace[attr] === subplotId) subplotCalcData.push(calcTrace);
    }

    return subplotCalcData;
};
/**
 * Get calcdata trace(s) that can be plotted with a given module
 * NOTE: this isn't necessarily just exactly matching trace type,
 * if multiple trace types use the same plotting routine, they will be
 * collected here.
 * In order to not plot the same thing multiple times, we return two arrays,
 * the calcdata we *will* plot with this module, and the ones we *won't*
 *
 * @param {array} calcdata: as in gd.calcdata
 * @param {object|string|fn} arg1:
 *  the plotting module, or its name, or its plot method
 *
 * @return {array[array]} [foundCalcdata, remainingCalcdata]
 */
exports.getModuleCalcData = function(calcdata, arg1) {
    var moduleCalcData = [];
    var remainingCalcData = [];

    var plotMethod;
    if(typeof arg1 === 'string') {
        plotMethod = Registry.getModule(arg1).plot;
    } else if(typeof arg1 === 'function') {
        plotMethod = arg1;
    } else {
        plotMethod = arg1.plot;
    }
    if(!plotMethod) {
        return [moduleCalcData, calcdata];
    }

    for(var i = 0; i < calcdata.length; i++) {
        var cd = calcdata[i];
        var trace = cd[0].trace;
        if(trace.visible !== true) continue;

        // group calcdata trace not by 'module' (as the name of this function
        // would suggest), but by 'module plot method' so that if some traces
        // share the same module plot method (e.g. bar and histogram), we
        // only call it one!
        if(trace._module.plot === plotMethod) {
            moduleCalcData.push(cd);
        } else {
            remainingCalcData.push(cd);
        }
    }

    return [moduleCalcData, remainingCalcData];
};

/**
 * Get the data trace(s) associated with a given subplot.
 *
 * @param {array} data  plotly full data array.
 * @param {string} type subplot type to look for.
 * @param {string} subplotId subplot id to look for.
 *
 * @return {array} list of trace objects.
 *
 */
exports.getSubplotData = function getSubplotData(data, type, subplotId) {
    if(!Registry.subplotsRegistry[type]) return [];

    var attr = Registry.subplotsRegistry[type].attr;
    var subplotData = [];
    var trace, subplotX, subplotY;

    if(type === 'gl2d') {
        var spmatch = subplotId.match(SUBPLOT_PATTERN);
        subplotX = 'x' + spmatch[1];
        subplotY = 'y' + spmatch[2];
    }

    for(var i = 0; i < data.length; i++) {
        trace = data[i];

        if(type === 'gl2d' && Registry.traceIs(trace, 'gl2d')) {
            if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) {
                subplotData.push(trace);
            }
        }
        else {
            if(trace[attr] === subplotId) subplotData.push(trace);
        }
    }

    return subplotData;
};

/**
 * Get a lookup object of trace uids corresponding in a given calcdata array.
 *
 * @param {array} calcdata: as in gd.calcdata (or a subset)
 * @return {object} lookup object of uids (`uid: 1`)
 */
exports.getUidsFromCalcData = function(calcdata) {
    var out = {};

    for(var i = 0; i < calcdata.length; i++) {
        var trace = calcdata[i][0].trace;
        out[trace.uid] = 1;
    }

    return out;
};

},{"../registry":254,"./cartesian/constants":211}],235:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

function xformMatrix(m, v) {
    var out = [0, 0, 0, 0];
    var i, j;

    for(i = 0; i < 4; ++i) {
        for(j = 0; j < 4; ++j) {
            out[j] += m[4 * i + j] * v[i];
        }
    }

    return out;
}

function project(camera, v) {
    var p = xformMatrix(camera.projection,
        xformMatrix(camera.view,
        xformMatrix(camera.model, [v[0], v[1], v[2], 1])));
    return p;
}

module.exports = project;

},{}],236:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var fontAttrs = require('./font_attributes');
var colorAttrs = require('../components/color/attributes');

var globalFont = fontAttrs({
    editType: 'calc',
    
});
globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
globalFont.size.dflt = 12;
globalFont.color.dflt = colorAttrs.defaultLine;

module.exports = {
    font: globalFont,
    title: {
        valType: 'string',
        
        editType: 'layoutstyle',
        
    },
    titlefont: fontAttrs({
        editType: 'layoutstyle',
        
    }),
    autosize: {
        valType: 'boolean',
        
        dflt: false,
        // autosize, width, and height get special editType treatment in _relayout
        // so we can handle noop resizes more efficiently
        editType: 'none',
        
    },
    width: {
        valType: 'number',
        
        min: 10,
        dflt: 700,
        editType: 'plot',
        
    },
    height: {
        valType: 'number',
        
        min: 10,
        dflt: 450,
        editType: 'plot',
        
    },
    margin: {
        l: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        r: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        t: {
            valType: 'number',
            
            min: 0,
            dflt: 100,
            editType: 'plot',
            
        },
        b: {
            valType: 'number',
            
            min: 0,
            dflt: 80,
            editType: 'plot',
            
        },
        pad: {
            valType: 'number',
            
            min: 0,
            dflt: 0,
            editType: 'plot',
            
        },
        autoexpand: {
            valType: 'boolean',
            
            dflt: true,
            editType: 'plot'
        },
        editType: 'plot'
    },
    paper_bgcolor: {
        valType: 'color',
        
        dflt: colorAttrs.background,
        editType: 'plot',
        
    },
    plot_bgcolor: {
        // defined here, but set in cartesian.supplyLayoutDefaults
        // because it needs to know if there are (2D) axes or not
        valType: 'color',
        
        dflt: colorAttrs.background,
        editType: 'layoutstyle',
        
    },
    separators: {
        valType: 'string',
        
        editType: 'plot',
        
    },
    hidesources: {
        valType: 'boolean',
        
        dflt: false,
        editType: 'plot',
        
    },
    showlegend: {
        // handled in legend.supplyLayoutDefaults
        // but included here because it's not in the legend object
        valType: 'boolean',
        
        editType: 'legend',
        
    },
    colorway: {
        valType: 'colorlist',
        dflt: colorAttrs.defaults,
        
        editType: 'calc',
        
    },
    datarevision: {
        valType: 'any',
        
        editType: 'calc',
        
    }
};

},{"../components/color/attributes":42,"./font_attributes":232}],237:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var requiredVersion = '0.44.1';

module.exports = {
    requiredVersion: requiredVersion,

    styleUrlPrefix: 'mapbox://styles/mapbox/',
    styleUrlSuffix: 'v9',

    controlContainerClassName: 'mapboxgl-control-container',

    wrongVersionErrorMsg: [
        'Your custom plotly.js bundle is not using the correct mapbox-gl version',
        'Please install mapbox-gl@' + requiredVersion + '.'
    ].join('\n'),

    noAccessTokenErrorMsg: [
        'Missing Mapbox access token.',
        'Mapbox trace type require a Mapbox access token to be registered.',
        'For example:',
        '  Plotly.plot(gd, data, layout, { mapboxAccessToken: \'my-access-token\' });',
        'More info here: https://www.mapbox.com/help/define-access-token/'
    ].join('\n'),

    mapOnErrorMsg: 'Mapbox error.',

    // a subset of node_modules/mapbox-gl/dist/mapbox-gl.css
    styleRules: {
        map: 'overflow:hidden;position:relative;',
        'missing-css': 'display:none',
    }
};

},{}],238:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');

/**
 * Convert plotly.js 'textposition' to mapbox-gl 'anchor' and 'offset'
 * (with the help of the icon size).
 *
 * @param {string} textpostion : plotly.js textposition value
 * @param {number} iconSize : plotly.js icon size (e.g. marker.size for traces)
 *
 * @return {object}
 *      - anchor
 *      - offset
 */
module.exports = function convertTextOpts(textposition, iconSize) {
    var parts = textposition.split(' '),
        vPos = parts[0],
        hPos = parts[1];

    // ballpack values
    var factor = Lib.isArrayOrTypedArray(iconSize) ? Lib.mean(iconSize) : iconSize,
        xInc = 0.5 + (factor / 100),
        yInc = 1.5 + (factor / 100);

    var anchorVals = ['', ''],
        offset = [0, 0];

    switch(vPos) {
        case 'top':
            anchorVals[0] = 'top';
            offset[1] = -yInc;
            break;
        case 'bottom':
            anchorVals[0] = 'bottom';
            offset[1] = yInc;
            break;
    }

    switch(hPos) {
        case 'left':
            anchorVals[1] = 'right';
            offset[0] = -xInc;
            break;
        case 'right':
            anchorVals[1] = 'left';
            offset[0] = xInc;
            break;
    }

    // Mapbox text-anchor must be one of:
    //  center, left, right, top, bottom,
    //  top-left, top-right, bottom-left, bottom-right

    var anchor;
    if(anchorVals[0] && anchorVals[1]) anchor = anchorVals.join('-');
    else if(anchorVals[0]) anchor = anchorVals[0];
    else if(anchorVals[1]) anchor = anchorVals[1];
    else anchor = 'center';

    return { anchor: anchor, offset: offset };
};

},{"../../lib":164}],239:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var mapboxgl = require('mapbox-gl');

var Lib = require('../../lib');
var getSubplotCalcData = require('../../plots/get_data').getSubplotCalcData;
var xmlnsNamespaces = require('../../constants/xmlns_namespaces');

var createMapbox = require('./mapbox');
var constants = require('./constants');

var MAPBOX = 'mapbox';

for(var k in constants.styleRules) {
    Lib.addStyleRule('.mapboxgl-' + k, constants.styleRules[k]);
}

exports.name = MAPBOX;

exports.attr = 'subplot';

exports.idRoot = MAPBOX;

exports.idRegex = exports.attrRegex = Lib.counterRegex(MAPBOX);

exports.attributes = {
    subplot: {
        valType: 'subplotid',
        
        dflt: 'mapbox',
        editType: 'calc',
        
    }
};

exports.layoutAttributes = require('./layout_attributes');

exports.supplyLayoutDefaults = require('./layout_defaults');

exports.plot = function plotMapbox(gd) {
    var fullLayout = gd._fullLayout;
    var calcData = gd.calcdata;
    var mapboxIds = fullLayout._subplots[MAPBOX];

    if(mapboxgl.version !== constants.requiredVersion) {
        throw new Error(constants.wrongVersionErrorMsg);
    }

    var accessToken = findAccessToken(gd, mapboxIds);
    mapboxgl.accessToken = accessToken;

    for(var i = 0; i < mapboxIds.length; i++) {
        var id = mapboxIds[i],
            subplotCalcData = getSubplotCalcData(calcData, MAPBOX, id),
            opts = fullLayout[id],
            mapbox = opts._subplot;

        if(!mapbox) {
            mapbox = createMapbox({
                gd: gd,
                container: fullLayout._glcontainer.node(),
                id: id,
                fullLayout: fullLayout,
                staticPlot: gd._context.staticPlot
            });

            fullLayout[id]._subplot = mapbox;
        }

        if(!mapbox.viewInitial) {
            mapbox.viewInitial = {
                center: Lib.extendFlat({}, opts.center),
                zoom: opts.zoom,
                bearing: opts.bearing,
                pitch: opts.pitch
            };
        }

        mapbox.plot(subplotCalcData, fullLayout, gd._promises);
    }
};

exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldMapboxKeys = oldFullLayout._subplots[MAPBOX] || [];

    for(var i = 0; i < oldMapboxKeys.length; i++) {
        var oldMapboxKey = oldMapboxKeys[i];

        if(!newFullLayout[oldMapboxKey] && !!oldFullLayout[oldMapboxKey]._subplot) {
            oldFullLayout[oldMapboxKey]._subplot.destroy();
        }
    }
};

exports.toSVG = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds = fullLayout._subplots[MAPBOX];
    var size = fullLayout._size;

    for(var i = 0; i < subplotIds.length; i++) {
        var opts = fullLayout[subplotIds[i]],
            domain = opts.domain,
            mapbox = opts._subplot;

        var imageData = mapbox.toImage('png');
        var image = fullLayout._glimages.append('svg:image');

        image.attr({
            xmlns: xmlnsNamespaces.svg,
            'xlink:href': imageData,
            x: size.l + size.w * domain.x[0],
            y: size.t + size.h * (1 - domain.y[1]),
            width: size.w * (domain.x[1] - domain.x[0]),
            height: size.h * (domain.y[1] - domain.y[0]),
            preserveAspectRatio: 'none'
        });

        mapbox.destroy();
    }
};

function findAccessToken(gd, mapboxIds) {
    var fullLayout = gd._fullLayout,
        context = gd._context;

    // special case for Mapbox Atlas users
    if(context.mapboxAccessToken === '') return '';

    // Take the first token we find in a mapbox subplot.
    // These default to the context value but may be overridden.
    for(var i = 0; i < mapboxIds.length; i++) {
        var opts = fullLayout[mapboxIds[i]];

        if(opts.accesstoken) {
            return opts.accesstoken;
        }
    }

    throw new Error(constants.noAccessTokenErrorMsg);
}

exports.updateFx = function(fullLayout) {
    var subplotIds = fullLayout._subplots[MAPBOX];

    for(var i = 0; i < subplotIds.length; i++) {
        var subplotObj = fullLayout[subplotIds[i]]._subplot;
        subplotObj.updateFx(fullLayout);
    }
};

},{"../../constants/xmlns_namespaces":147,"../../lib":164,"../../plots/get_data":234,"./constants":237,"./layout_attributes":241,"./layout_defaults":242,"./mapbox":243,"mapbox-gl":14}],240:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var convertTextOpts = require('./convert_text_opts');

function MapboxLayer(mapbox, index) {
    this.mapbox = mapbox;
    this.map = mapbox.map;

    this.uid = mapbox.uid + '-' + 'layer' + index;

    this.idSource = this.uid + '-source';
    this.idLayer = this.uid + '-layer';

    // some state variable to check if a remove/add step is needed
    this.sourceType = null;
    this.source = null;
    this.layerType = null;
    this.below = null;

    // is layer currently visible
    this.visible = false;
}

var proto = MapboxLayer.prototype;

proto.update = function update(opts) {
    if(!this.visible) {
        // IMPORTANT: must create source before layer to not cause errors
        this.updateSource(opts);
        this.updateLayer(opts);
    } else if(this.needsNewSource(opts)) {
        // IMPORTANT: must delete layer before source to not cause errors
        this.updateLayer(opts);
        this.updateSource(opts);
    } else if(this.needsNewLayer(opts)) {
        this.updateLayer(opts);
    } else {
        this.updateStyle(opts);
    }

    this.visible = isVisible(opts);
};

proto.needsNewSource = function(opts) {
    // for some reason changing layer to 'fill' or 'symbol'
    // w/o changing the source throws an exception in mapbox-gl 0.18 ;
    // stay safe and make new source on type changes
    return (
        this.sourceType !== opts.sourcetype ||
        this.source !== opts.source ||
        this.layerType !== opts.type
    );
};

proto.needsNewLayer = function(opts) {
    return (
        this.layerType !== opts.type ||
        this.below !== opts.below
    );
};

proto.updateSource = function(opts) {
    var map = this.map;

    if(map.getSource(this.idSource)) map.removeSource(this.idSource);

    this.sourceType = opts.sourcetype;
    this.source = opts.source;

    if(!isVisible(opts)) return;

    var sourceOpts = convertSourceOpts(opts);

    map.addSource(this.idSource, sourceOpts);
};

proto.updateLayer = function(opts) {
    var map = this.map;
    var convertedOpts = convertOpts(opts);

    if(map.getLayer(this.idLayer)) map.removeLayer(this.idLayer);

    this.layerType = opts.type;

    if(isVisible(opts)) {
        map.addLayer({
            id: this.idLayer,
            source: this.idSource,
            'source-layer': opts.sourcelayer || '',
            type: opts.type,
            layout: convertedOpts.layout,
            paint: convertedOpts.paint
        }, opts.below);
    }
};

proto.updateStyle = function(opts) {
    if(isVisible(opts)) {
        var convertedOpts = convertOpts(opts);
        this.mapbox.setOptions(this.idLayer, 'setLayoutProperty', convertedOpts.layout);
        this.mapbox.setOptions(this.idLayer, 'setPaintProperty', convertedOpts.paint);
    }
};

proto.dispose = function dispose() {
    var map = this.map;
    map.removeLayer(this.idLayer);
    map.removeSource(this.idSource);
};

function isVisible(opts) {
    var source = opts.source;

    return (
        Lib.isPlainObject(source) ||
        (typeof source === 'string' && source.length > 0)
    );
}

function convertOpts(opts) {
    var layout = {},
        paint = {};

    switch(opts.type) {

        case 'circle':
            Lib.extendFlat(paint, {
                'circle-radius': opts.circle.radius,
                'circle-color': opts.color,
                'circle-opacity': opts.opacity
            });
            break;

        case 'line':
            Lib.extendFlat(paint, {
                'line-width': opts.line.width,
                'line-color': opts.color,
                'line-opacity': opts.opacity
            });
            break;

        case 'fill':
            Lib.extendFlat(paint, {
                'fill-color': opts.color,
                'fill-outline-color': opts.fill.outlinecolor,
                'fill-opacity': opts.opacity

                // no way to pass specify outline width at the moment
            });
            break;

        case 'symbol':
            var symbol = opts.symbol,
                textOpts = convertTextOpts(symbol.textposition, symbol.iconsize);

            Lib.extendFlat(layout, {
                'icon-image': symbol.icon + '-15',
                'icon-size': symbol.iconsize / 10,

                'text-field': symbol.text,
                'text-size': symbol.textfont.size,
                'text-anchor': textOpts.anchor,
                'text-offset': textOpts.offset

                // TODO font family
                // 'text-font': symbol.textfont.family.split(', '),
            });

            Lib.extendFlat(paint, {
                'icon-color': opts.color,
                'text-color': symbol.textfont.color,
                'text-opacity': opts.opacity
            });
            break;
    }

    return { layout: layout, paint: paint };
}

function convertSourceOpts(opts) {
    var sourceType = opts.sourcetype;
    var source = opts.source;
    var sourceOpts = {type: sourceType};
    var field;

    if(sourceType === 'geojson') {
        field = 'data';
    } else if(sourceType === 'vector') {
        field = typeof source === 'string' ? 'url' : 'tiles';
    }

    sourceOpts[field] = source;
    return sourceOpts;
}

module.exports = function createMapboxLayer(mapbox, index, opts) {
    var mapboxLayer = new MapboxLayer(mapbox, index);

    mapboxLayer.update(opts);

    return mapboxLayer;
};

},{"../../lib":164,"./convert_text_opts":238}],241:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');
var defaultLine = require('../../components/color').defaultLine;
var domainAttrs = require('../domain').attributes;
var fontAttrs = require('../font_attributes');
var textposition = require('../../traces/scatter/attributes').textposition;
var overrideAll = require('../../plot_api/edit_types').overrideAll;

var fontAttr = fontAttrs({
    
});
fontAttr.family.dflt = 'Open Sans Regular, Arial Unicode MS Regular';

module.exports = overrideAll({
    _arrayAttrRegexps: [Lib.counterRegex('mapbox', '.layers', true)],

    domain: domainAttrs({name: 'mapbox'}),

    accesstoken: {
        valType: 'string',
        noBlank: true,
        strict: true,
        
        
    },
    style: {
        valType: 'any',
        values: ['basic', 'streets', 'outdoors', 'light', 'dark', 'satellite', 'satellite-streets'],
        dflt: 'basic',
        
        
    },

    center: {
        lon: {
            valType: 'number',
            dflt: 0,
            
            
        },
        lat: {
            valType: 'number',
            dflt: 0,
            
            
        }
    },
    zoom: {
        valType: 'number',
        dflt: 1,
        
        
    },
    bearing: {
        valType: 'number',
        dflt: 0,
        
        
    },
    pitch: {
        valType: 'number',
        dflt: 0,
        
        
    },

    layers: {
        _isLinkedToArray: 'layer',

        sourcetype: {
            valType: 'enumerated',
            values: ['geojson', 'vector'],
            dflt: 'geojson',
            
            
        },

        source: {
            valType: 'any',
            
            
        },

        sourcelayer: {
            valType: 'string',
            dflt: '',
            
            
        },

        type: {
            valType: 'enumerated',
            values: ['circle', 'line', 'fill', 'symbol'],
            dflt: 'circle',
            
            
        },

        // attributes shared between all types
        below: {
            valType: 'string',
            dflt: '',
            
            
        },
        color: {
            valType: 'color',
            dflt: defaultLine,
            
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            dflt: 1,
            
            
        },

        // type-specific style attributes
        circle: {
            radius: {
                valType: 'number',
                dflt: 15,
                
                
            }
        },

        line: {
            width: {
                valType: 'number',
                dflt: 2,
                
                
            }
        },

        fill: {
            outlinecolor: {
                valType: 'color',
                dflt: defaultLine,
                
                
            }
        },

        symbol: {
            icon: {
                valType: 'string',
                dflt: 'marker',
                
                
            },
            iconsize: {
                valType: 'number',
                dflt: 10,
                
                
            },
            text: {
                valType: 'string',
                dflt: '',
                
                
            },
            textfont: fontAttr,
            textposition: Lib.extendFlat({}, textposition, { arrayOk: false })
        }
    }
}, 'plot', 'from-root');

},{"../../components/color":43,"../../lib":164,"../../plot_api/edit_types":191,"../../traces/scatter/attributes":266,"../domain":231,"../font_attributes":232}],242:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');

var handleSubplotDefaults = require('../subplot_defaults');
var layoutAttributes = require('./layout_attributes');


module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
    handleSubplotDefaults(layoutIn, layoutOut, fullData, {
        type: 'mapbox',
        attributes: layoutAttributes,
        handleDefaults: handleDefaults,
        partition: 'y',
        accessToken: layoutOut._mapboxAccessToken
    });
};

function handleDefaults(containerIn, containerOut, coerce, opts) {
    coerce('accesstoken', opts.accessToken);
    coerce('style');
    coerce('center.lon');
    coerce('center.lat');
    coerce('zoom');
    coerce('bearing');
    coerce('pitch');

    handleLayerDefaults(containerIn, containerOut);

    // copy ref to input container to update 'center' and 'zoom' on map move
    containerOut._input = containerIn;
}

function handleLayerDefaults(containerIn, containerOut) {
    var layersIn = containerIn.layers || [],
        layersOut = containerOut.layers = [];

    var layerIn, layerOut;

    function coerce(attr, dflt) {
        return Lib.coerce(layerIn, layerOut, layoutAttributes.layers, attr, dflt);
    }

    for(var i = 0; i < layersIn.length; i++) {
        layerIn = layersIn[i];
        layerOut = {};

        if(!Lib.isPlainObject(layerIn)) continue;

        var sourceType = coerce('sourcetype');
        coerce('source');

        if(sourceType === 'vector') coerce('sourcelayer');

        // maybe add smart default based off GeoJSON geometry?
        var type = coerce('type');

        coerce('below');
        coerce('color');
        coerce('opacity');

        if(type === 'circle') {
            coerce('circle.radius');
        }

        if(type === 'line') {
            coerce('line.width');
        }

        if(type === 'fill') {
            coerce('fill.outlinecolor');
        }

        if(type === 'symbol') {
            coerce('symbol.icon');
            coerce('symbol.iconsize');

            coerce('symbol.text');
            Lib.coerceFont(coerce, 'symbol.textfont');
            coerce('symbol.textposition');
        }

        layerOut._index = i;
        layersOut.push(layerOut);
    }
}

},{"../../lib":164,"../subplot_defaults":253,"./layout_attributes":241}],243:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var mapboxgl = require('mapbox-gl');

var Fx = require('../../components/fx');
var Lib = require('../../lib');
var dragElement = require('../../components/dragelement');
var prepSelect = require('../cartesian/select').prepSelect;
var constants = require('./constants');
var layoutAttributes = require('./layout_attributes');
var createMapboxLayer = require('./layers');

function Mapbox(opts) {
    this.id = opts.id;
    this.gd = opts.gd;
    this.container = opts.container;
    this.isStatic = opts.staticPlot;

    var fullLayout = opts.fullLayout;

    // unique id for this Mapbox instance
    this.uid = fullLayout._uid + '-' + this.id;

    // full mapbox options (N.B. needs to be updated on every updates)
    this.opts = fullLayout[this.id];

    // create framework on instantiation for a smoother first plot call
    this.div = null;
    this.xaxis = null;
    this.yaxis = null;
    this.createFramework(fullLayout);

    // state variables used to infer how and what to update
    this.map = null;
    this.accessToken = null;
    this.styleObj = null;
    this.traceHash = {};
    this.layerList = [];
}

var proto = Mapbox.prototype;

module.exports = function createMapbox(opts) {
    return new Mapbox(opts);
};

proto.plot = function(calcData, fullLayout, promises) {
    var self = this;

    // feed in new mapbox options
    var opts = self.opts = fullLayout[this.id];

    // remove map and create a new map if access token has change
    if(self.map && (opts.accesstoken !== self.accessToken)) {
        self.map.remove();
        self.map = null;
        self.styleObj = null;
        self.traceHash = [];
        self.layerList = {};
    }

    var promise;

    if(!self.map) {
        promise = new Promise(function(resolve, reject) {
            self.createMap(calcData, fullLayout, resolve, reject);
        });
    } else {
        promise = new Promise(function(resolve, reject) {
            self.updateMap(calcData, fullLayout, resolve, reject);
        });
    }

    promises.push(promise);
};

proto.createMap = function(calcData, fullLayout, resolve, reject) {
    var self = this;
    var gd = self.gd;
    var opts = self.opts;

    // store style id and URL or object
    var styleObj = self.styleObj = getStyleObj(opts.style);

    // store access token associated with this map
    self.accessToken = opts.accesstoken;

    // create the map!
    var map = self.map = new mapboxgl.Map({
        container: self.div,

        style: styleObj.style,
        center: convertCenter(opts.center),
        zoom: opts.zoom,
        bearing: opts.bearing,
        pitch: opts.pitch,

        interactive: !self.isStatic,
        preserveDrawingBuffer: self.isStatic,

        doubleClickZoom: false,
        boxZoom: false
    });

    // clear navigation container
    var className = constants.controlContainerClassName;
    var controlContainer = self.div.getElementsByClassName(className)[0];
    self.div.removeChild(controlContainer);

    // make sure canvas does not inherit left and top css
    map._canvas.style.left = '0px';
    map._canvas.style.top = '0px';

    self.rejectOnError(reject);

    map.once('load', function() {
        self.updateData(calcData);
        self.updateLayout(fullLayout);
        self.resolveOnRender(resolve);
    });

    if(self.isStatic) return;

    // keep track of pan / zoom in user layout and emit relayout event
    map.on('moveend', function(eventData) {
        if(!self.map) return;

        var view = self.getView();

        opts._input.center = opts.center = view.center;
        opts._input.zoom = opts.zoom = view.zoom;
        opts._input.bearing = opts.bearing = view.bearing;
        opts._input.pitch = opts.pitch = view.pitch;

        // 'moveend' gets triggered by map.setCenter, map.setZoom,
        // map.setBearing and map.setPitch.
        //
        // Here, we make sure that 'plotly_relayout' is
        // triggered here only when the 'moveend' originates from a
        // mouse target (filtering out API calls) to not
        // duplicate 'plotly_relayout' events.

        if(eventData.originalEvent) {
            var update = {};
            update[self.id] = Lib.extendFlat({}, view);
            gd.emit('plotly_relayout', update);
        }
    });

    map.on('mousemove', function(evt) {
        var bb = self.div.getBoundingClientRect();

        // some hackery to get Fx.hover to work
        evt.clientX = evt.point.x + bb.left;
        evt.clientY = evt.point.y + bb.top;

        evt.target.getBoundingClientRect = function() { return bb; };

        self.xaxis.p2c = function() { return evt.lngLat.lng; };
        self.yaxis.p2c = function() { return evt.lngLat.lat; };

        Fx.hover(gd, evt, self.id);
    });

    map.on('click', function(evt) {
        // TODO: this does not support right-click. If we want to support it, we
        // would likely need to change mapbox to use dragElement instead of straight
        // mapbox event binding. Or perhaps better, make a simple wrapper with the
        // right mousedown, mousemove, and mouseup handlers just for a left/right click
        // pie would use this too.
        Fx.click(gd, evt.originalEvent);
    });

    function unhover() {
        Fx.loneUnhover(fullLayout._toppaper);
    }

    map.on('dragstart', unhover);
    map.on('zoomstart', unhover);

    map.on('dblclick', function() {
        var viewInitial = self.viewInitial;

        map.setCenter(convertCenter(viewInitial.center));
        map.setZoom(viewInitial.zoom);
        map.setBearing(viewInitial.bearing);
        map.setPitch(viewInitial.pitch);

        var viewNow = self.getView();

        opts._input.center = opts.center = viewNow.center;
        opts._input.zoom = opts.zoom = viewNow.zoom;
        opts._input.bearing = opts.bearing = viewNow.bearing;
        opts._input.pitch = opts.pitch = viewNow.pitch;

        gd.emit('plotly_doubleclick', null);
    });

    // define clear select on map creation, to keep one ref per map,
    // so that map.on / map.off in updateFx works as expected
    self.clearSelect = function() {
        gd._fullLayout._zoomlayer.selectAll('.select-outline').remove();
    };
};

proto.updateMap = function(calcData, fullLayout, resolve, reject) {
    var self = this;
    var map = self.map;

    self.rejectOnError(reject);

    var styleObj = getStyleObj(self.opts.style);

    if(self.styleObj.id !== styleObj.id) {
        self.styleObj = styleObj;
        map.setStyle(styleObj.style);

        map.once('styledata', function() {
            // need to rebuild trace layers on reload
            // to avoid 'lost event' errors
            self.traceHash = {};
            self.updateData(calcData);
            self.updateLayout(fullLayout);
            self.resolveOnRender(resolve);
        });
    } else {
        self.updateData(calcData);
        self.updateLayout(fullLayout);
        self.resolveOnRender(resolve);
    }
};

proto.updateData = function(calcData) {
    var traceHash = this.traceHash;
    var traceObj, trace, i, j;

    // update or create trace objects
    for(i = 0; i < calcData.length; i++) {
        var calcTrace = calcData[i];

        trace = calcTrace[0].trace;
        traceObj = traceHash[trace.uid];

        if(traceObj) {
            traceObj.update(calcTrace);
        } else if(trace._module) {
            traceHash[trace.uid] = trace._module.plot(this, calcTrace);
        }
    }

    // remove empty trace objects
    var ids = Object.keys(traceHash);
    id_loop:
    for(i = 0; i < ids.length; i++) {
        var id = ids[i];

        for(j = 0; j < calcData.length; j++) {
            trace = calcData[j][0].trace;
            if(id === trace.uid) continue id_loop;
        }

        traceObj = traceHash[id];
        traceObj.dispose();
        delete traceHash[id];
    }
};

proto.updateLayout = function(fullLayout) {
    var map = this.map,
        opts = this.opts;

    map.setCenter(convertCenter(opts.center));
    map.setZoom(opts.zoom);
    map.setBearing(opts.bearing);
    map.setPitch(opts.pitch);

    this.updateLayers();
    this.updateFramework(fullLayout);
    this.updateFx(fullLayout);
    this.map.resize();
};

proto.resolveOnRender = function(resolve) {
    var map = this.map;

    map.on('render', function onRender() {
        if(map.loaded()) {
            map.off('render', onRender);
            // resolve at end of render loop
            setTimeout(resolve, 0);
        }
    });
};

proto.rejectOnError = function(reject) {
    var map = this.map;

    function handler() {
        reject(new Error(constants.mapOnErrorMsg));
    }

    map.once('error', handler);
    map.once('style.error', handler);
    map.once('source.error', handler);
    map.once('tile.error', handler);
    map.once('layer.error', handler);
};

proto.createFramework = function(fullLayout) {
    var self = this;

    var div = self.div = document.createElement('div');
    div.id = self.uid;
    div.style.position = 'absolute';
    self.container.appendChild(div);

    // create mock x/y axes for hover routine
    self.xaxis = {
        _id: 'x',
        c2p: function(v) { return self.project(v).x; }
    };
    self.yaxis = {
        _id: 'y',
        c2p: function(v) { return self.project(v).y; }
    };

    self.updateFramework(fullLayout);
};

proto.updateFx = function(fullLayout) {
    var self = this;
    var map = self.map;
    var gd = self.gd;

    if(self.isStatic) return;

    function invert(pxpy) {
        var obj = self.map.unproject(pxpy);
        return [obj.lng, obj.lat];
    }

    var dragMode = fullLayout.dragmode;
    var fillRangeItems;

    if(dragMode === 'select') {
        fillRangeItems = function(eventData, poly) {
            var ranges = eventData.range = {};
            ranges[self.id] = [
                invert([poly.xmin, poly.ymin]),
                invert([poly.xmax, poly.ymax])
            ];
        };
    } else {
        fillRangeItems = function(eventData, poly, pts) {
            var dataPts = eventData.lassoPoints = {};
            dataPts[self.id] = pts.filtered.map(invert);
        };
    }

    if(dragMode === 'select' || dragMode === 'lasso') {
        map.dragPan.disable();
        map.on('zoomstart', self.clearSelect);

        var dragOptions = {
            element: self.div,
            gd: gd,
            plotinfo: {
                xaxis: self.xaxis,
                yaxis: self.yaxis,
                fillRangeItems: fillRangeItems
            },
            xaxes: [self.xaxis],
            yaxes: [self.yaxis],
            subplot: self.id
        };

        dragOptions.prepFn = function(e, startX, startY) {
            prepSelect(e, startX, startY, dragOptions, dragMode);
        };

        dragElement.init(dragOptions);
    } else {
        map.dragPan.enable();
        map.off('zoomstart', self.clearSelect);
        self.div.onmousedown = null;
    }
};

proto.updateFramework = function(fullLayout) {
    var domain = fullLayout[this.id].domain;
    var size = fullLayout._size;

    var style = this.div.style;
    style.width = size.w * (domain.x[1] - domain.x[0]) + 'px';
    style.height = size.h * (domain.y[1] - domain.y[0]) + 'px';
    style.left = size.l + domain.x[0] * size.w + 'px';
    style.top = size.t + (1 - domain.y[1]) * size.h + 'px';

    this.xaxis._offset = size.l + domain.x[0] * size.w;
    this.xaxis._length = size.w * (domain.x[1] - domain.x[0]);

    this.yaxis._offset = size.t + (1 - domain.y[1]) * size.h;
    this.yaxis._length = size.h * (domain.y[1] - domain.y[0]);
};

proto.updateLayers = function() {
    var opts = this.opts;
    var layers = opts.layers;
    var layerList = this.layerList;
    var i;

    // if the layer arrays don't match,
    // don't try to be smart,
    // delete them all, and start all over.

    if(layers.length !== layerList.length) {
        for(i = 0; i < layerList.length; i++) {
            layerList[i].dispose();
        }

        layerList = this.layerList = [];

        for(i = 0; i < layers.length; i++) {
            layerList.push(createMapboxLayer(this, i, layers[i]));
        }
    } else {
        for(i = 0; i < layers.length; i++) {
            layerList[i].update(layers[i]);
        }
    }
};

proto.destroy = function() {
    if(this.map) {
        this.map.remove();
        this.map = null;
        this.container.removeChild(this.div);
    }
};

proto.toImage = function() {
    this.map.stop();
    return this.map.getCanvas().toDataURL();
};

// convenience wrapper to create set multiple layer
// 'layout' or 'paint options at once.
proto.setOptions = function(id, methodName, opts) {
    for(var k in opts) {
        this.map[methodName](id, k, opts[k]);
    }
};

// convenience method to project a [lon, lat] array to pixel coords
proto.project = function(v) {
    return this.map.project(new mapboxgl.LngLat(v[0], v[1]));
};

// get map's current view values in plotly.js notation
proto.getView = function() {
    var map = this.map;

    var mapCenter = map.getCenter();
    var center = { lon: mapCenter.lng, lat: mapCenter.lat };

    return {
        center: center,
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch()
    };
};

function getStyleObj(val) {
    var styleValues = layoutAttributes.style.values;
    var styleDflt = layoutAttributes.style.dflt;
    var styleObj = {};

    if(Lib.isPlainObject(val)) {
        styleObj.id = val.id;
        styleObj.style = val;
    } else if(typeof val === 'string') {
        styleObj.id = val;
        styleObj.style = (styleValues.indexOf(val) !== -1) ?
             convertStyleVal(val) :
             val;
    } else {
        styleObj.id = styleDflt;
        styleObj.style = convertStyleVal(styleDflt);
    }

    styleObj.transition = {duration: 0, delay: 0};

    return styleObj;
}

// if style is part of the 'official' mapbox values, add URL prefix and suffix
function convertStyleVal(val) {
    return constants.styleUrlPrefix + val + '-' + constants.styleUrlSuffix;
}

function convertCenter(center) {
    return [center.lon, center.lat];
}

},{"../../components/dragelement":65,"../../components/fx":85,"../../lib":164,"../cartesian/select":223,"./constants":237,"./layers":240,"./layout_attributes":241,"mapbox-gl":14}],244:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// This is used exclusively by components inside component arrays,
// hence the 'arraydraw' editType. If this ever gets used elsewhere
// we could generalize it as a function ala font_attributes
module.exports = {
    t: {
        valType: 'number',
        dflt: 0,
        
        editType: 'arraydraw',
        
    },
    r: {
        valType: 'number',
        dflt: 0,
        
        editType: 'arraydraw',
        
    },
    b: {
        valType: 'number',
        dflt: 0,
        
        editType: 'arraydraw',
        
    },
    l: {
        valType: 'number',
        dflt: 0,
        
        editType: 'arraydraw',
        
    },
    editType: 'arraydraw'
};

},{}],245:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var Registry = require('../registry');
var PlotSchema = require('../plot_api/plot_schema');
var Lib = require('../lib');
var Color = require('../components/color');
var BADNUM = require('../constants/numerical').BADNUM;

var axisIDs = require('../plots/cartesian/axis_ids');
var sortBasePlotModules = require('./sort_modules').sortBasePlotModules;

var animationAttrs = require('./animation_attributes');
var frameAttrs = require('./frame_attributes');

var relinkPrivateKeys = Lib.relinkPrivateKeys;
var _ = Lib._;

var plots = module.exports = {};

// Expose registry methods on Plots for backward-compatibility
Lib.extendFlat(plots, Registry);

plots.attributes = require('./attributes');
plots.attributes.type.values = plots.allTypes;
plots.fontAttrs = require('./font_attributes');
plots.layoutAttributes = require('./layout_attributes');

// TODO make this a plot attribute?
plots.fontWeight = 'normal';

var transformsRegistry = plots.transformsRegistry;

var commandModule = require('./command');
plots.executeAPICommand = commandModule.executeAPICommand;
plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
plots.manageCommandObserver = commandModule.manageCommandObserver;
plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;

// in some cases the browser doesn't seem to know how big
// the text is at first, so it needs to draw it,
// then wait a little, then draw it again
plots.redrawText = function(gd) {
    gd = Lib.getGraphDiv(gd);

    // do not work if polar is present
    if((gd.data && gd.data[0] && gd.data[0].r)) return;

    return new Promise(function(resolve) {
        setTimeout(function() {
            Registry.getComponentMethod('annotations', 'draw')(gd);
            Registry.getComponentMethod('legend', 'draw')(gd);

            (gd.calcdata || []).forEach(function(d) {
                if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
            });

            resolve(plots.previousPromises(gd));
        }, 300);
    });
};

// resize plot about the container size
plots.resize = function(gd) {
    gd = Lib.getGraphDiv(gd);

    return new Promise(function(resolve, reject) {

        function isHidden(gd) {
            var display = window.getComputedStyle(gd).display;
            return !display || display === 'none';
        }

        if(!gd || isHidden(gd)) {
            reject(new Error('Resize must be passed a displayed plot div element.'));
        }

        if(gd._redrawTimer) clearTimeout(gd._redrawTimer);

        gd._redrawTimer = setTimeout(function() {
            // return if there is nothing to resize
            if(gd.layout.width && gd.layout.height) {
                resolve(gd);
                return;
            }

            delete gd.layout.width;
            delete gd.layout.height;

            // autosizing doesn't count as a change that needs saving
            var oldchanged = gd.changed;

            // nor should it be included in the undo queue
            gd.autoplay = true;

            Registry.call('relayout', gd, {autosize: true}).then(function() {
                gd.changed = oldchanged;
                resolve(gd);
            });
        }, 100);
    });
};


// for use in Lib.syncOrAsync, check if there are any
// pending promises in this plot and wait for them
plots.previousPromises = function(gd) {
    if((gd._promises || []).length) {
        return Promise.all(gd._promises)
            .then(function() { gd._promises = []; });
    }
};

/**
 * Adds the 'Edit chart' link.
 * Note that now Plotly.plot() calls this so it can regenerate whenever it replots
 *
 * Add source links to your graph inside the 'showSources' config argument.
 */
plots.addLinks = function(gd) {
    // Do not do anything if showLink and showSources are not set to true in config
    if(!gd._context.showLink && !gd._context.showSources) return;

    var fullLayout = gd._fullLayout;

    var linkContainer = Lib.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) {
        s.style({
            'font-family': '"Open Sans", Arial, sans-serif',
            'font-size': '12px',
            'fill': Color.defaultLine,
            'pointer-events': 'all'
        })
        .each(function() {
            var links = d3.select(this);
            links.append('tspan').classed('js-link-to-tool', true);
            links.append('tspan').classed('js-link-spacer', true);
            links.append('tspan').classed('js-sourcelinks', true);
        });
    });

    // The text node inside svg
    var text = linkContainer.node();
    var attrs = {y: fullLayout._paper.attr('height') - 9};

    // If text's width is bigger than the layout
    // Check that text is a child node or document.body
    // because otherwise IE/Edge might throw an exception
    // when calling getComputedTextLength().
    // Apparently offsetParent is null for invisibles.
    if(document.body.contains(text) && text.getComputedTextLength() >= (fullLayout.width - 20)) {
        // Align the text at the left
        attrs['text-anchor'] = 'start';
        attrs.x = 5;
    }
    else {
        // Align the text at the right
        attrs['text-anchor'] = 'end';
        attrs.x = fullLayout._paper.attr('width') - 7;
    }

    linkContainer.attr(attrs);

    var toolspan = linkContainer.select('.js-link-to-tool'),
        spacespan = linkContainer.select('.js-link-spacer'),
        sourcespan = linkContainer.select('.js-sourcelinks');

    if(gd._context.showSources) gd._context.showSources(gd);

    // 'view in plotly' link for embedded plots
    if(gd._context.showLink) positionPlayWithData(gd, toolspan);

    // separator if we have both sources and tool link
    spacespan.text((toolspan.text() && sourcespan.text()) ? ' - ' : '');
};

// note that now this function is only adding the brand in
// iframes and 3rd-party apps
function positionPlayWithData(gd, container) {
    container.text('');
    var link = container.append('a')
        .attr({
            'xlink:xlink:href': '#',
            'class': 'link--impt link--embedview',
            'font-weight': 'bold'
        })
        .text(gd._context.linkText + ' ' + String.fromCharCode(187));

    if(gd._context.sendData) {
        link.on('click', function() {
            plots.sendDataToCloud(gd);
        });
    }
    else {
        var path = window.location.pathname.split('/');
        var query = window.location.search;
        link.attr({
            'xlink:xlink:show': 'new',
            'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
        });
    }
}

plots.sendDataToCloud = function(gd) {
    gd.emit('plotly_beforeexport');

    var baseUrl = (window.PLOTLYENV && window.PLOTLYENV.BASE_URL) || 'https://plot.ly';

    var hiddenformDiv = d3.select(gd)
        .append('div')
        .attr('id', 'hiddenform')
        .style('display', 'none');

    var hiddenform = hiddenformDiv
        .append('form')
        .attr({
            action: baseUrl + '/external',
            method: 'post',
            target: '_blank'
        });

    var hiddenformInput = hiddenform
        .append('input')
        .attr({
            type: 'text',
            name: 'data'
        });

    hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
    hiddenform.node().submit();
    hiddenformDiv.remove();

    gd.emit('plotly_afterexport');
    return false;
};

var d3FormatKeys = [
    'days', 'shortDays', 'months', 'shortMonths', 'periods',
    'dateTime', 'date', 'time',
    'decimal', 'thousands', 'grouping', 'currency'
];

var extraFormatKeys = [
    'year', 'month', 'dayMonth', 'dayMonthYear'
];

/*
 * Fill in default values
 * @param {DOM element} gd
 * @param {object} opts
 * @param {boolean} opts.skipUpdateCalc: normally if the existing gd.calcdata looks
 *   compatible with the new gd._fullData we finish by linking the new _fullData traces
 *   to the old gd.calcdata, so it's correctly set if we're not going to recalc. But also,
 *   if there are calcTransforms on the trace, we first remap data arrays from the old full
 *   trace into the new one. Use skipUpdateCalc to defer this (needed by Plotly.react)
 *
 * gd.data, gd.layout:
 *   are precisely what the user specified (except as modified by cleanData/cleanLayout),
 *   these fields shouldn't be modified (except for filling in some auto values)
 *   nor used directly after the supply defaults step.
 *
 * gd._fullData, gd._fullLayout:
 *   are complete descriptions of how to draw the plot,
 *   use these fields in all required computations.
 *
 * gd._fullLayout._modules
 *   is a list of all the trace modules required to draw the plot.
 *
 * gd._fullLayout._basePlotModules
 *   is a list of all the plot modules required to draw the plot.
 *
 * gd._fullLayout._transformModules
 *   is a list of all the transform modules invoked.
 *
 */
plots.supplyDefaults = function(gd, opts) {
    var skipUpdateCalc = opts && opts.skipUpdateCalc;
    var oldFullLayout = gd._fullLayout || {};

    if(oldFullLayout._skipDefaults) {
        delete oldFullLayout._skipDefaults;
        return;
    }

    var newFullLayout = gd._fullLayout = {};
    var newLayout = gd.layout || {};

    var oldFullData = gd._fullData || [];
    var newFullData = gd._fullData = [];
    var newData = gd.data || [];

    var oldCalcdata = gd.calcdata || [];

    var context = gd._context || {};

    var i;

    // Create all the storage space for frames, but only if doesn't already exist
    if(!gd._transitionData) plots.createTransitionData(gd);

    // So we only need to do this once (and since we have gd here)
    // get the translated placeholder titles.
    // These ones get used as default values so need to be known at supplyDefaults
    // others keep their blank defaults but render the placeholder as desired later
    // TODO: make these work the same way, only inserting the placeholder text at draw time?
    // The challenge is that this has slightly different behavior right now in editable mode:
    // using the placeholder as default makes this text permanently (but lightly) visible,
    // but explicit '' for these titles gives you a placeholder that's hidden until you mouse
    // over it - so you're not distracted by it if you really don't want a title, but if you do
    // and you're new to plotly you may not be able to find it.
    // When editable=false the two behave the same, no title is drawn.
    newFullLayout._dfltTitle = {
        plot: _(gd, 'Click to enter Plot title'),
        x: _(gd, 'Click to enter X axis title'),
        y: _(gd, 'Click to enter Y axis title'),
        colorbar: _(gd, 'Click to enter Colorscale title'),
        annotation: _(gd, 'new text')
    };
    newFullLayout._traceWord = _(gd, 'trace');

    var formatObj = getFormatObj(gd, d3FormatKeys);

    // stash the token from context so mapbox subplots can use it as default
    newFullLayout._mapboxAccessToken = context.mapboxAccessToken;

    // first fill in what we can of layout without looking at data
    // because fullData needs a few things from layout
    if(oldFullLayout._initialAutoSizeIsDone) {

        // coerce the updated layout while preserving width and height
        var oldWidth = oldFullLayout.width,
            oldHeight = oldFullLayout.height;

        plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);

        if(!newLayout.width) newFullLayout.width = oldWidth;
        if(!newLayout.height) newFullLayout.height = oldHeight;
    }
    else {

        // coerce the updated layout and autosize if needed
        plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);

        var missingWidthOrHeight = (!newLayout.width || !newLayout.height),
            autosize = newFullLayout.autosize,
            autosizable = context.autosizable,
            initialAutoSize = missingWidthOrHeight && (autosize || autosizable);

        if(initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);
        else if(missingWidthOrHeight) plots.sanitizeMargins(gd);

        // for backwards-compatibility with Plotly v1.x.x
        if(!autosize && missingWidthOrHeight) {
            newLayout.width = newFullLayout.width;
            newLayout.height = newFullLayout.height;
        }
    }

    newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators);
    newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys);

    newFullLayout._initialAutoSizeIsDone = true;

    // keep track of how many traces are inputted
    newFullLayout._dataLength = newData.length;

    // clear the lists of trace and baseplot modules, and subplots
    newFullLayout._modules = [];
    newFullLayout._basePlotModules = [];
    var subplots = newFullLayout._subplots = emptySubplotLists();

    // initialize axis and subplot hash objects for splom-generated grids
    var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}};
    var splomSubplots = newFullLayout._splomSubplots = {};

    // for traces to request a default rangeslider on their x axes
    // eg set `_requestRangeslider.x2 = true` for xaxis2
    newFullLayout._requestRangeslider = {};

    // then do the data
    newFullLayout._globalTransforms = (gd._context || {}).globalTransforms;
    plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);

    // redo grid size defaults with info about splom x/y axes,
    // and fill in generated cartesian axes and subplots
    var splomXa = Object.keys(splomAxes.x);
    var splomYa = Object.keys(splomAxes.y);
    if(splomXa.length > 1 && splomYa.length > 1) {
        Registry.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout);

        for(i = 0; i < splomXa.length; i++) {
            Lib.pushUnique(subplots.xaxis, splomXa[i]);
        }
        for(i = 0; i < splomYa.length; i++) {
            Lib.pushUnique(subplots.yaxis, splomYa[i]);
        }
        for(var k in splomSubplots) {
            Lib.pushUnique(subplots.cartesian, k);
        }
    }

    // attach helper method to check whether a plot type is present on graph
    newFullLayout._has = plots._hasPlotType.bind(newFullLayout);

    // special cases that introduce interactions between traces
    var _modules = newFullLayout._modules;
    for(i = 0; i < _modules.length; i++) {
        var _module = _modules[i];
        if(_module.cleanData) _module.cleanData(newFullData);
    }

    if(oldFullData.length === newFullData.length) {
        for(i = 0; i < newFullData.length; i++) {
            relinkPrivateKeys(newFullData[i], oldFullData[i]);
        }
    }

    // finally, fill in the pieces of layout that may need to look at data
    plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);

    // turn on flag to optimize large splom-only graphs
    // mostly by omitting SVG layers during Cartesian.drawFramework
    newFullLayout._hasOnlyLargeSploms = (
        newFullLayout._basePlotModules.length === 1 &&
        newFullLayout._basePlotModules[0].name === 'splom' &&
        splomXa.length > 15 &&
        splomYa.length > 15 &&
        newFullLayout.shapes.length === 0 &&
        newFullLayout.images.length === 0
    );

    // TODO remove in v2.0.0
    // add has-plot-type refs to fullLayout for backward compatibility
    newFullLayout._hasCartesian = newFullLayout._has('cartesian');
    newFullLayout._hasGeo = newFullLayout._has('geo');
    newFullLayout._hasGL3D = newFullLayout._has('gl3d');
    newFullLayout._hasGL2D = newFullLayout._has('gl2d');
    newFullLayout._hasTernary = newFullLayout._has('ternary');
    newFullLayout._hasPie = newFullLayout._has('pie');

    // relink / initialize subplot axis objects
    plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);

    // clean subplots and other artifacts from previous plot calls
    plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata);

    // relink functions and _ attributes to promote consistency between plots
    relinkPrivateKeys(newFullLayout, oldFullLayout);

    // TODO may return a promise
    plots.doAutoMargin(gd);

    // set scale after auto margin routine
    var axList = axisIDs.list(gd);
    for(i = 0; i < axList.length; i++) {
        var ax = axList[i];
        ax.setScale();
    }

    // update object references in calcdata
    if(!skipUpdateCalc && oldCalcdata.length === newFullData.length) {
        plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
    }

    // sort base plot modules for consistent ordering
    newFullLayout._basePlotModules.sort(sortBasePlotModules);
};

plots.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) {
    for(var i = 0; i < newFullData.length; i++) {
        var newTrace = newFullData[i];
        var cd0 = oldCalcdata[i][0];
        if(cd0 && cd0.trace) {
            var oldTrace = cd0.trace;
            if(oldTrace._hasCalcTransform) {
                var arrayAttrs = oldTrace._arrayAttrs;
                var j, astr, oldArrayVal;

                for(j = 0; j < arrayAttrs.length; j++) {
                    astr = arrayAttrs[j];
                    oldArrayVal = Lib.nestedProperty(oldTrace, astr).get().slice();
                    Lib.nestedProperty(newTrace, astr).set(oldArrayVal);
                }
            }
            cd0.trace = newTrace;
        }
    }
};

/**
 * Make a container for collecting subplots we need to display.
 *
 * Finds all subplot types we need to enumerate once and caches it,
 * but makes a new output object each time.
 * Single-trace subplots (which have no `id`) such as pie, table, etc
 * do not need to be collected because we just draw all visible traces.
 */
var collectableSubplotTypes;
function emptySubplotLists() {
    var out = {};
    var i, j;

    if(!collectableSubplotTypes) {
        collectableSubplotTypes = [];

        var subplotsRegistry = Registry.subplotsRegistry;

        for(var subplotType in subplotsRegistry) {
            var subplotModule = subplotsRegistry[subplotType];
            var subplotAttr = subplotModule.attr;

            if(subplotAttr) {
                collectableSubplotTypes.push(subplotType);

                // special case, currently just for cartesian:
                // we need to enumerate axes, not just subplots
                if(Array.isArray(subplotAttr)) {
                    for(j = 0; j < subplotAttr.length; j++) {
                        Lib.pushUnique(collectableSubplotTypes, subplotAttr[j]);
                    }
                }
            }
        }
    }

    for(i = 0; i < collectableSubplotTypes.length; i++) {
        out[collectableSubplotTypes[i]] = [];
    }
    return out;
}

/**
 * getFormatObj: use _context to get the format object from locale.
 * Used to get d3.locale argument object and extraFormat argument object
 *
 * Regarding d3.locale argument :
 * decimal and thousands can be overridden later by layout.separators
 * grouping and currency are not presently used by our automatic number
 * formatting system but can be used by custom formats.
 *
 * @returns {object} d3.locale format object
 */
function getFormatObj(gd, formatKeys) {
    var locale = gd._context.locale;
    if(!locale) locale === 'en-US';

    var formatDone = false;
    var formatObj = {};

    function includeFormat(newFormat) {
        var formatFinished = true;
        for(var i = 0; i < formatKeys.length; i++) {
            var formatKey = formatKeys[i];
            if(!formatObj[formatKey]) {
                if(newFormat[formatKey]) {
                    formatObj[formatKey] = newFormat[formatKey];
                }
                else formatFinished = false;
            }
        }
        if(formatFinished) formatDone = true;
    }

    // same as localize, look for format parts in each format spec in the chain
    for(var i = 0; i < 2; i++) {
        var locales = gd._context.locales;
        for(var j = 0; j < 2; j++) {
            var formatj = (locales[locale] || {}).format;
            if(formatj) {
                includeFormat(formatj);
                if(formatDone) break;
            }
            locales = Registry.localeRegistry;
        }

        var baseLocale = locale.split('-')[0];
        if(formatDone || baseLocale === locale) break;
        locale = baseLocale;
    }

    // lastly pick out defaults from english (non-US, as DMY is so much more common)
    if(!formatDone) includeFormat(Registry.localeRegistry.en.format);

    return formatObj;
}

/**
 * getFormatter: combine the final separators with the locale formatting object
 * we pulled earlier to generate number and time formatters
 * TODO: remove separators in v2, only use locale, so we don't need this step?
 *
 * @param {object} formatObj: d3.locale format object
 * @param {string} separators: length-2 string to override decimal and thousands
 *   separators in number formatting
 *
 * @returns {object} {numberFormat, timeFormat} d3 formatter factory functions
 *   for numbers and time
 */
function getFormatter(formatObj, separators) {
    formatObj.decimal = separators.charAt(0);
    formatObj.thousands = separators.charAt(1);

    return d3.locale(formatObj);
}

// Create storage for all of the data related to frames and transitions:
plots.createTransitionData = function(gd) {
    // Set up the default keyframe if it doesn't exist:
    if(!gd._transitionData) {
        gd._transitionData = {};
    }

    if(!gd._transitionData._frames) {
        gd._transitionData._frames = [];
    }

    if(!gd._transitionData._frameHash) {
        gd._transitionData._frameHash = {};
    }

    if(!gd._transitionData._counter) {
        gd._transitionData._counter = 0;
    }

    if(!gd._transitionData._interruptCallbacks) {
        gd._transitionData._interruptCallbacks = [];
    }
};

// helper function to be bound to fullLayout to check
// whether a certain plot type is present on plot
// or trace has a category
plots._hasPlotType = function(category) {
    var i;

    // check base plot modules
    var basePlotModules = this._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        if(basePlotModules[i].name === category) return true;
    }

    // check trace modules
    var modules = this._modules || [];
    for(i = 0; i < modules.length; i++) {
        var name = modules[i].name;
        if(name === category) return true;
        // N.B. this is modules[i] along with 'categories' as a hash object
        var _module = Registry.modules[name];
        if(_module && _module.categories[category]) return true;
    }

    return false;
};

plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata) {
    var i, j;

    var basePlotModules = oldFullLayout._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        var _module = basePlotModules[i];

        if(_module.clean) {
            _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout, oldCalcdata);
        }
    }

    var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
    var hasGl = newFullLayout._has && newFullLayout._has('gl');

    if(hadGl && !hasGl) {
        if(oldFullLayout._glcontainer !== undefined) {
            oldFullLayout._glcontainer.selectAll('.gl-canvas').remove();
            oldFullLayout._glcanvas = null;
        }
    }

    var hasInfoLayer = !!oldFullLayout._infolayer;

    oldLoop:
    for(i = 0; i < oldFullData.length; i++) {
        var oldTrace = oldFullData[i],
            oldUid = oldTrace.uid;

        for(j = 0; j < newFullData.length; j++) {
            var newTrace = newFullData[j];

            if(oldUid === newTrace.uid) continue oldLoop;
        }

        // clean old colorbars
        if(hasInfoLayer) {
            oldFullLayout._infolayer.select('.cb' + oldUid).remove();
        }
    }

    if(oldFullLayout._zoomlayer) {
        oldFullLayout._zoomlayer.selectAll('.select-outline').remove();
    }
};

plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
    var oldSubplots = oldFullLayout._plots || {};
    var newSubplots = newFullLayout._plots = {};
    var newSubplotList = newFullLayout._subplots;

    var mockGd = {
        _fullData: newFullData,
        _fullLayout: newFullLayout
    };

    var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []);

    var i, j, id, ax;

    for(i = 0; i < ids.length; i++) {
        id = ids[i];
        var oldSubplot = oldSubplots[id];
        var xaxis = axisIDs.getFromId(mockGd, id, 'x');
        var yaxis = axisIDs.getFromId(mockGd, id, 'y');
        var plotinfo;

        if(oldSubplot) {
            plotinfo = newSubplots[id] = oldSubplot;

            if(plotinfo.xaxis.layer !== xaxis.layer) {
                plotinfo.xlines.attr('d', null);
                plotinfo.xaxislayer.selectAll('*').remove();
            }

            if(plotinfo.yaxis.layer !== yaxis.layer) {
                plotinfo.ylines.attr('d', null);
                plotinfo.yaxislayer.selectAll('*').remove();
            }
        } else {
            plotinfo = newSubplots[id] = {};
            plotinfo.id = id;
        }

        plotinfo.xaxis = xaxis;
        plotinfo.yaxis = yaxis;

        // By default, we clip at the subplot level,
        // but if one trace on a given subplot has *cliponaxis* set to false,
        // we need to clip at the trace module layer level;
        // find this out here, once of for all.
        plotinfo._hasClipOnAxisFalse = false;

        for(j = 0; j < newFullData.length; j++) {
            var trace = newFullData[j];

            if(
                trace.xaxis === plotinfo.xaxis._id &&
                trace.yaxis === plotinfo.yaxis._id &&
                trace.cliponaxis === false
            ) {
                plotinfo._hasClipOnAxisFalse = true;
                break;
            }
        }
    }

    // while we're at it, link overlaying axes to their main axes and
    // anchored axes to the axes they're anchored to
    var axList = axisIDs.list(mockGd, null, true);
    for(i = 0; i < axList.length; i++) {
        ax = axList[i];
        var mainAx = null;

        if(ax.overlaying) {
            mainAx = axisIDs.getFromId(mockGd, ax.overlaying);

            // you cannot overlay an axis that's already overlaying another
            if(mainAx && mainAx.overlaying) {
                ax.overlaying = false;
                mainAx = null;
            }
        }
        ax._mainAxis = mainAx || ax;

        /*
         * For now force overlays to overlay completely... so they
         * can drag together correctly and share backgrounds.
         * Later perhaps we make separate axis domain and
         * tick/line domain or something, so they can still share
         * the (possibly larger) dragger and background but don't
         * have to both be drawn over that whole domain
         */
        if(mainAx) ax.domain = mainAx.domain.slice();

        ax._anchorAxis = ax.anchor === 'free' ?
            null :
            axisIDs.getFromId(mockGd, ax.anchor);
    }

    for(i = 0; i < axList.length; i++) {
        // Figure out which subplot to draw ticks, labels, & axis lines on
        // do this as a separate loop so we already have all the
        // _mainAxis and _anchorAxis links set
        ax = axList[i];
        var isX = ax._id.charAt(0) === 'x';
        var anchorAx = ax._mainAxis._anchorAxis;
        var mainSubplotID = '';
        var nextBestMainSubplotID = '';
        var anchorID = '';
        // First try the main ID with the anchor
        if(anchorAx) {
            anchorID = anchorAx._mainAxis._id;
            mainSubplotID = isX ? (ax._id + anchorID) : (anchorID + ax._id);
        }
        // Then look for a subplot with the counteraxis overlaying the anchor
        // If that fails just use the first subplot including this axis
        if(!mainSubplotID || !newSubplots[mainSubplotID]) {
            mainSubplotID = '';
            for(j = 0; j < ids.length; j++) {
                id = ids[j];
                var yIndex = id.indexOf('y');
                var idPart = isX ? id.substr(0, yIndex) : id.substr(yIndex);
                var counterPart = isX ? id.substr(yIndex) : id.substr(0, yIndex);
                if(idPart === ax._id) {
                    if(!nextBestMainSubplotID) nextBestMainSubplotID = id;
                    var counterAx = axisIDs.getFromId(mockGd, counterPart);
                    if(anchorID && counterAx.overlaying === anchorID) {
                        mainSubplotID = id;
                        break;
                    }
                }
            }
        }
        ax._mainSubplot = mainSubplotID || nextBestMainSubplotID;
    }
};

// This function clears any trace attributes with valType: color and
// no set dflt filed in the plot schema. This is needed because groupby (which
// is the only transform for which this currently applies) supplies parent
// trace defaults, then expanded trace defaults. The result is that `null`
// colors are default-supplied and inherited as a color instead of a null.
// The result is that expanded trace default colors have no effect, with
// the final result that groups are indistinguishable. This function clears
// those colors so that individual groupby groups get unique colors.
plots.clearExpandedTraceDefaultColors = function(trace) {
    var colorAttrs, path, i;

    // This uses weird closure state in order to satisfy the linter rule
    // that we can't create functions in a loop.
    function locateColorAttrs(attr, attrName, attrs, level) {
        path[level] = attrName;
        path.length = level + 1;
        if(attr.valType === 'color' && attr.dflt === undefined) {
            colorAttrs.push(path.join('.'));
        }
    }

    path = [];

    // Get the cached colorAttrs:
    colorAttrs = trace._module._colorAttrs;

    // Or else compute and cache the colorAttrs on the module:
    if(!colorAttrs) {
        trace._module._colorAttrs = colorAttrs = [];
        PlotSchema.crawl(
            trace._module.attributes,
            locateColorAttrs
        );
    }

    for(i = 0; i < colorAttrs.length; i++) {
        var origprop = Lib.nestedProperty(trace, '_input.' + colorAttrs[i]);

        if(!origprop.get()) {
            Lib.nestedProperty(trace, colorAttrs[i]).set(null);
        }
    }
};


plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) {
    var modules = fullLayout._modules;
    var basePlotModules = fullLayout._basePlotModules;
    var cnt = 0;
    var colorCnt = 0;

    var i, fullTrace, trace;

    fullLayout._transformModules = [];

    function pushModule(fullTrace) {
        dataOut.push(fullTrace);

        var _module = fullTrace._module;
        if(!_module) return;

        if(fullTrace.visible === true) Lib.pushUnique(modules, _module);
        Lib.pushUnique(basePlotModules, fullTrace._module.basePlotModule);

        cnt++;

        // TODO: do we really want color not to increment for explicitly invisible traces?
        // This logic is weird, but matches previous behavior: traces that you explicitly
        // set to visible:false do not increment the color, but traces WE determine to be
        // empty or invalid (and thus set to visible:false) DO increment color.
        // I kind of think we should just let all traces increment color, visible or not.
        // see mock: axes-autotype-empty vs. a test of restyling visible: false that
        // I can't find right now...
        if(fullTrace._input.visible !== false) colorCnt++;
    }

    var carpetIndex = {};
    var carpetDependents = [];

    for(i = 0; i < dataIn.length; i++) {
        trace = dataIn[i];
        fullTrace = plots.supplyTraceDefaults(trace, colorCnt, fullLayout, i);

        fullTrace.index = i;
        fullTrace._input = trace;
        fullTrace._expandedIndex = cnt;

        if(fullTrace.transforms && fullTrace.transforms.length) {
            var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout);

            for(var j = 0; j < expandedTraces.length; j++) {
                var expandedTrace = expandedTraces[j];
                var fullExpandedTrace = plots.supplyTraceDefaults(expandedTrace, cnt, fullLayout, i);

                // relink private (i.e. underscore) keys expanded trace to full expanded trace so
                // that transform supply-default methods can set _ keys for future use.
                relinkPrivateKeys(fullExpandedTrace, expandedTrace);

                // mutate uid here using parent uid and expanded index
                // to promote consistency between update calls
                expandedTrace.uid = fullExpandedTrace.uid = fullTrace.uid + j;

                // add info about parent data trace
                fullExpandedTrace.index = i;
                fullExpandedTrace._input = trace;
                fullExpandedTrace._fullInput = fullTrace;

                // add info about the expanded data
                fullExpandedTrace._expandedIndex = cnt;
                fullExpandedTrace._expandedInput = expandedTrace;

                pushModule(fullExpandedTrace);
            }
        }
        else {
            // add identify refs for consistency with transformed traces
            fullTrace._fullInput = fullTrace;
            fullTrace._expandedInput = fullTrace;

            pushModule(fullTrace);
        }

        if(Registry.traceIs(fullTrace, 'carpetAxis')) {
            carpetIndex[fullTrace.carpet] = fullTrace;
        }

        if(Registry.traceIs(fullTrace, 'carpetDependent')) {
            carpetDependents.push(i);
        }
    }

    for(i = 0; i < carpetDependents.length; i++) {
        fullTrace = dataOut[carpetDependents[i]];

        if(!fullTrace.visible) continue;

        var carpetAxis = carpetIndex[fullTrace.carpet];
        fullTrace._carpet = carpetAxis;

        if(!carpetAxis || !carpetAxis.visible) {
            fullTrace.visible = false;
            continue;
        }

        fullTrace.xaxis = carpetAxis.xaxis;
        fullTrace.yaxis = carpetAxis.yaxis;
    }
};

plots.supplyAnimationDefaults = function(opts) {
    opts = opts || {};
    var i;
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
    }

    coerce('mode');
    coerce('direction');
    coerce('fromcurrent');

    if(Array.isArray(opts.frame)) {
        optsOut.frame = [];
        for(i = 0; i < opts.frame.length; i++) {
            optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
        }
    } else {
        optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
    }

    if(Array.isArray(opts.transition)) {
        optsOut.transition = [];
        for(i = 0; i < opts.transition.length; i++) {
            optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
        }
    } else {
        optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
    }

    return optsOut;
};

plots.supplyAnimationFrameDefaults = function(opts) {
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
    }

    coerce('duration');
    coerce('redraw');

    return optsOut;
};

plots.supplyAnimationTransitionDefaults = function(opts) {
    var optsOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
    }

    coerce('duration');
    coerce('easing');

    return optsOut;
};

plots.supplyFrameDefaults = function(frameIn) {
    var frameOut = {};

    function coerce(attr, dflt) {
        return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
    }

    coerce('group');
    coerce('name');
    coerce('traces');
    coerce('baseframe');
    coerce('data');
    coerce('layout');

    return frameOut;
};

plots.supplyTraceDefaults = function(traceIn, colorIndex, layout, traceInIndex) {
    var colorway = layout.colorway || Color.defaults;
    var traceOut = {},
        defaultColor = colorway[colorIndex % colorway.length];

    var i;

    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
    }

    var visible = coerce('visible');

    coerce('type');
    coerce('uid');
    coerce('name', layout._traceWord + ' ' + traceInIndex);

    // we want even invisible traces to make their would-be subplots visible
    // so coerce the subplot id(s) now no matter what
    var _module = plots.getModule(traceOut);
    traceOut._module = _module;
    if(_module) {
        var basePlotModule = _module.basePlotModule;
        var subplotAttr = basePlotModule.attr;
        var subplotAttrs = basePlotModule.attributes;
        if(subplotAttr && subplotAttrs) {
            var subplots = layout._subplots;
            var subplotId = '';

            // TODO - currently if we draw an empty gl2d subplot, it draws
            // nothing then gets stuck and you can't get it back without newPlot
            // sort this out in the regl refactor? but for now just drop empty gl2d subplots
            if(basePlotModule.name !== 'gl2d' || visible) {
                if(Array.isArray(subplotAttr)) {
                    for(i = 0; i < subplotAttr.length; i++) {
                        var attri = subplotAttr[i];
                        var vali = Lib.coerce(traceIn, traceOut, subplotAttrs, attri);

                        if(subplots[attri]) Lib.pushUnique(subplots[attri], vali);
                        subplotId += vali;
                    }
                }
                else {
                    subplotId = Lib.coerce(traceIn, traceOut, subplotAttrs, subplotAttr);
                }

                if(subplots[basePlotModule.name]) {
                    Lib.pushUnique(subplots[basePlotModule.name], subplotId);
                }
            }
        }
    }

    if(visible) {
        coerce('customdata');
        coerce('ids');

        if(Registry.traceIs(traceOut, 'showLegend')) {
            coerce('showlegend');
            coerce('legendgroup');
        }

        Registry.getComponentMethod(
            'fx',
            'supplyDefaults'
        )(traceIn, traceOut, defaultColor, layout);

        // TODO add per-base-plot-module trace defaults step

        if(_module) {
            _module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
            Lib.coerceHoverinfo(traceIn, traceOut, layout);
        }

        if(!Registry.traceIs(traceOut, 'noOpacity')) coerce('opacity');

        if(Registry.traceIs(traceOut, 'notLegendIsolatable')) {
            // This clears out the legendonly state for traces like carpet that
            // cannot be isolated in the legend
            traceOut.visible = !!traceOut.visible;
        }

        if(_module && _module.selectPoints) {
            coerce('selectedpoints');
        }

        plots.supplyTransformDefaults(traceIn, traceOut, layout);
    }

    return traceOut;
};

plots.supplyTransformDefaults = function(traceIn, traceOut, layout) {
    // For now we only allow transforms on 1D traces, ie those that specify a _length.
    // If we were to implement 2D transforms, we'd need to have each transform
    // describe its own applicability and disable itself when it doesn't apply.
    if(!traceOut._length) return;

    var globalTransforms = layout._globalTransforms || [];
    var transformModules = layout._transformModules || [];

    if(!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return;

    var containerIn = traceIn.transforms || [],
        transformList = globalTransforms.concat(containerIn),
        containerOut = traceOut.transforms = [];

    for(var i = 0; i < transformList.length; i++) {
        var transformIn = transformList[i],
            type = transformIn.type,
            _module = transformsRegistry[type],
            transformOut;

        /*
         * Supply defaults may run twice. First pass runs all supply defaults steps
         * and adds the _module to any output transforms.
         * If transforms exist another pass is run so that any generated traces also
         * go through supply defaults. This has the effect of rerunning
         * supplyTransformDefaults. If the transform does not have a `transform`
         * function it could not have generated any new traces and the second stage
         * is unnecessary. We detect this case with the following variables.
         */
        var isFirstStage = !(transformIn._module && transformIn._module === _module),
            doLaterStages = _module && typeof _module.transform === 'function';

        if(!_module) Lib.warn('Unrecognized transform type ' + type + '.');

        if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) {
            transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn);
            transformOut.type = type;
            transformOut._module = _module;

            Lib.pushUnique(transformModules, _module);
        }
        else {
            transformOut = Lib.extendFlat({}, transformIn);
        }

        containerOut.push(transformOut);
    }
};

function applyTransforms(fullTrace, fullData, layout, fullLayout) {
    var container = fullTrace.transforms,
        dataOut = [fullTrace];

    for(var i = 0; i < container.length; i++) {
        var transform = container[i],
            _module = transformsRegistry[transform.type];

        if(_module && _module.transform) {
            dataOut = _module.transform(dataOut, {
                transform: transform,
                fullTrace: fullTrace,
                fullData: fullData,
                layout: layout,
                fullLayout: fullLayout,
                transformIndex: i
            });
        }
    }

    return dataOut;
}

plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) {
    function coerce(attr, dflt) {
        return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
    }

    var globalFont = Lib.coerceFont(coerce, 'font');

    coerce('title', layoutOut._dfltTitle.plot);

    Lib.coerceFont(coerce, 'titlefont', {
        family: globalFont.family,
        size: Math.round(globalFont.size * 1.4),
        color: globalFont.color
    });

    // Make sure that autosize is defaulted to *true*
    // on layouts with no set width and height for backward compatibly,
    // in particular https://plot.ly/javascript/responsive-fluid-layout/
    //
    // Before https://github.com/plotly/plotly.js/pull/635 ,
    // layouts with no set width and height were set temporary set to 'initial'
    // to pass through the autosize routine
    //
    // This behavior is subject to change in v2.
    coerce('autosize', !(layoutIn.width && layoutIn.height));

    coerce('width');
    coerce('height');
    coerce('margin.l');
    coerce('margin.r');
    coerce('margin.t');
    coerce('margin.b');
    coerce('margin.pad');
    coerce('margin.autoexpand');

    if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut);

    Registry.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut);

    coerce('paper_bgcolor');

    coerce('separators', formatObj.decimal + formatObj.thousands);
    coerce('hidesources');

    coerce('colorway');

    coerce('datarevision');

    Registry.getComponentMethod(
        'calendars',
        'handleDefaults'
    )(layoutIn, layoutOut, 'calendar');

    Registry.getComponentMethod(
        'fx',
        'supplyLayoutGlobalDefaults'
    )(layoutIn, layoutOut, coerce);
};

plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) {
    var context = gd._context || {},
        frameMargins = context.frameMargins,
        newWidth,
        newHeight;

    var isPlotDiv = Lib.isPlotDiv(gd);

    if(isPlotDiv) gd.emit('plotly_autosize');

    // embedded in an iframe - just take the full iframe size
    // if we get to this point, with no aspect ratio restrictions
    if(context.fillFrame) {
        newWidth = window.innerWidth;
        newHeight = window.innerHeight;

        // somehow we get a few extra px height sometimes...
        // just hide it
        document.body.style.overflow = 'hidden';
    }
    else if(isNumeric(frameMargins) && frameMargins > 0) {
        var reservedMargins = calculateReservedMargins(gd._boundingBoxMargins),
            reservedWidth = reservedMargins.left + reservedMargins.right,
            reservedHeight = reservedMargins.bottom + reservedMargins.top,
            factor = 1 - 2 * frameMargins;

        var gdBB = fullLayout._container && fullLayout._container.node ?
            fullLayout._container.node().getBoundingClientRect() : {
                width: fullLayout.width,
                height: fullLayout.height
            };

        newWidth = Math.round(factor * (gdBB.width - reservedWidth));
        newHeight = Math.round(factor * (gdBB.height - reservedHeight));
    }
    else {
        // plotly.js - let the developers do what they want, either
        // provide height and width for the container div,
        // specify size in layout, or take the defaults,
        // but don't enforce any ratio restrictions
        var computedStyle = isPlotDiv ? window.getComputedStyle(gd) : {};

        newWidth = parseFloat(computedStyle.width) || fullLayout.width;
        newHeight = parseFloat(computedStyle.height) || fullLayout.height;
    }

    var minWidth = plots.layoutAttributes.width.min,
        minHeight = plots.layoutAttributes.height.min;
    if(newWidth < minWidth) newWidth = minWidth;
    if(newHeight < minHeight) newHeight = minHeight;

    var widthHasChanged = !layout.width &&
            (Math.abs(fullLayout.width - newWidth) > 1),
        heightHasChanged = !layout.height &&
            (Math.abs(fullLayout.height - newHeight) > 1);

    if(heightHasChanged || widthHasChanged) {
        if(widthHasChanged) fullLayout.width = newWidth;
        if(heightHasChanged) fullLayout.height = newHeight;
    }

    // cache initial autosize value, used in relayout when
    // width or height values are set to null
    if(!gd._initialAutoSize) {
        gd._initialAutoSize = { width: newWidth, height: newHeight };
    }

    plots.sanitizeMargins(fullLayout);
};

/**
 * Reduce all reserved margin objects to a single required margin reservation.
 *
 * @param {Object} margins
 * @returns {{left: number, right: number, bottom: number, top: number}}
 */
function calculateReservedMargins(margins) {
    var resultingMargin = {left: 0, right: 0, bottom: 0, top: 0},
        marginName;

    if(margins) {
        for(marginName in margins) {
            if(margins.hasOwnProperty(marginName)) {
                resultingMargin.left += margins[marginName].left || 0;
                resultingMargin.right += margins[marginName].right || 0;
                resultingMargin.bottom += margins[marginName].bottom || 0;
                resultingMargin.top += margins[marginName].top || 0;
            }
        }
    }
    return resultingMargin;
}

plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) {
    var componentsRegistry = Registry.componentsRegistry;
    var basePlotModules = layoutOut._basePlotModules;
    var component, i, _module;

    var Cartesian = Registry.subplotsRegistry.cartesian;

    // check if any components need to add more base plot modules
    // that weren't captured by traces
    for(component in componentsRegistry) {
        _module = componentsRegistry[component];

        if(_module.includeBasePlot) {
            _module.includeBasePlot(layoutIn, layoutOut);
        }
    }

    // make sure we *at least* have some cartesian axes
    if(!basePlotModules.length) {
        basePlotModules.push(Cartesian);
    }

    // ensure all cartesian axes have at least one subplot
    if(layoutOut._has('cartesian')) {
        Registry.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut);
        Cartesian.finalizeSubplots(layoutIn, layoutOut);
    }

    // sort subplot lists
    for(var subplotType in layoutOut._subplots) {
        layoutOut._subplots[subplotType].sort(Lib.subplotSort);
    }

    // base plot module layout defaults
    for(i = 0; i < basePlotModules.length; i++) {
        _module = basePlotModules[i];

        // e.g. pie does not have a layout-defaults step
        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }

    // trace module layout defaults
    var modules = layoutOut._modules;
    for(i = 0; i < modules.length; i++) {
        _module = modules[i];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }

    // transform module layout defaults
    var transformModules = layoutOut._transformModules;
    for(i = 0; i < transformModules.length; i++) {
        _module = transformModules[i];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData);
        }
    }

    for(component in componentsRegistry) {
        _module = componentsRegistry[component];

        if(_module.supplyLayoutDefaults) {
            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
        }
    }
};

// Remove all plotly attributes from a div so it can be replotted fresh
// TODO: these really need to be encapsulated into a much smaller set...
plots.purge = function(gd) {
    // note: we DO NOT remove _context because it doesn't change when we insert
    // a new plot, and may have been set outside of our scope.

    var fullLayout = gd._fullLayout || {};
    if(fullLayout._glcontainer !== undefined) {
        fullLayout._glcontainer.selectAll('.gl-canvas').remove();
        fullLayout._glcontainer.remove();
        fullLayout._glcanvas = null;
    }
    if(fullLayout._geocontainer !== undefined) fullLayout._geocontainer.remove();

    // remove modebar
    if(fullLayout._modeBar) fullLayout._modeBar.destroy();

    if(gd._transitionData) {
        // Ensure any dangling callbacks are simply dropped if the plot is purged.
        // This is more or less only actually important for testing.
        if(gd._transitionData._interruptCallbacks) {
            gd._transitionData._interruptCallbacks.length = 0;
        }

        if(gd._transitionData._animationRaf) {
            window.cancelAnimationFrame(gd._transitionData._animationRaf);
        }
    }

    // remove any planned throttles
    Lib.clearThrottle();

    // data and layout
    delete gd.data;
    delete gd.layout;
    delete gd._fullData;
    delete gd._fullLayout;
    delete gd.calcdata;
    delete gd.framework;
    delete gd.empty;

    delete gd.fid;

    delete gd.undoqueue; // action queue
    delete gd.undonum;
    delete gd.autoplay; // are we doing an action that doesn't go in undo queue?
    delete gd.changed;

    // these get recreated on Plotly.plot anyway, but just to be safe
    // (and to have a record of them...)
    delete gd._promises;
    delete gd._redrawTimer;
    delete gd.firstscatter;
    delete gd._hmlumcount;
    delete gd._hmpixcount;
    delete gd._transitionData;
    delete gd._transitioning;
    delete gd._initialAutoSize;
    delete gd._transitioningWithDuration;

    // created during certain events, that *should* clean them up
    // themselves, but may not if there was an error
    delete gd._dragging;
    delete gd._dragged;
    delete gd._hoverdata;
    delete gd._snapshotInProgress;
    delete gd._editing;
    delete gd._replotPending;
    delete gd._mouseDownTime;
    delete gd._legendMouseDownTime;

    // remove all event listeners
    if(gd.removeAllListeners) gd.removeAllListeners();
};

plots.style = function(gd) {
    var _modules = gd._fullLayout._modules;
    var styleModules = [];
    var i;

    // some trace modules reuse the same style method,
    // make sure to not unnecessary call them multiple times.

    for(i = 0; i < _modules.length; i++) {
        var _module = _modules[i];
        if(_module.style) {
            Lib.pushUnique(styleModules, _module.style);
        }
    }

    for(i = 0; i < styleModules.length; i++) {
        styleModules[i](gd);
    }
};

plots.sanitizeMargins = function(fullLayout) {
    // polar doesn't do margins...
    if(!fullLayout || !fullLayout.margin) return;

    var width = fullLayout.width,
        height = fullLayout.height,
        margin = fullLayout.margin,
        plotWidth = width - (margin.l + margin.r),
        plotHeight = height - (margin.t + margin.b),
        correction;

    // if margin.l + margin.r = 0 then plotWidth > 0
    // as width >= 10 by supplyDefaults
    // similarly for margin.t + margin.b

    if(plotWidth < 0) {
        correction = (width - 1) / (margin.l + margin.r);
        margin.l = Math.floor(correction * margin.l);
        margin.r = Math.floor(correction * margin.r);
    }

    if(plotHeight < 0) {
        correction = (height - 1) / (margin.t + margin.b);
        margin.t = Math.floor(correction * margin.t);
        margin.b = Math.floor(correction * margin.b);
    }
};

// called by components to see if we need to
// expand the margins to show them
// o is {x,l,r,y,t,b} where x and y are plot fractions,
// the rest are pixels in each direction
// or leave o out to delete this entry (like if it's hidden)
plots.autoMargin = function(gd, id, o) {
    var fullLayout = gd._fullLayout;

    if(!fullLayout._pushmargin) fullLayout._pushmargin = {};

    if(fullLayout.margin.autoexpand !== false) {
        if(!o) delete fullLayout._pushmargin[id];
        else {
            var pad = o.pad === undefined ? 12 : o.pad;

            // if the item is too big, just give it enough automargin to
            // make sure you can still grab it and bring it back
            if(o.l + o.r > fullLayout.width * 0.5) o.l = o.r = 0;
            if(o.b + o.t > fullLayout.height * 0.5) o.b = o.t = 0;

            fullLayout._pushmargin[id] = {
                l: {val: o.x, size: o.l + pad},
                r: {val: o.x, size: o.r + pad},
                b: {val: o.y, size: o.b + pad},
                t: {val: o.y, size: o.t + pad}
            };
        }

        if(!fullLayout._replotting) plots.doAutoMargin(gd);
    }
};

plots.doAutoMargin = function(gd) {
    var fullLayout = gd._fullLayout;
    if(!fullLayout._size) fullLayout._size = {};
    if(!fullLayout._pushmargin) fullLayout._pushmargin = {};

    var gs = fullLayout._size,
        oldmargins = JSON.stringify(gs);

    // adjust margins for outside components
    // fullLayout.margin is the requested margin,
    // fullLayout._size has margins and plotsize after adjustment
    var ml = Math.max(fullLayout.margin.l || 0, 0),
        mr = Math.max(fullLayout.margin.r || 0, 0),
        mt = Math.max(fullLayout.margin.t || 0, 0),
        mb = Math.max(fullLayout.margin.b || 0, 0),
        pm = fullLayout._pushmargin;

    if(fullLayout.margin.autoexpand !== false) {

        // fill in the requested margins
        pm.base = {
            l: {val: 0, size: ml},
            r: {val: 1, size: mr},
            t: {val: 1, size: mt},
            b: {val: 0, size: mb}
        };

        // now cycle through all the combinations of l and r
        // (and t and b) to find the required margins

        for(var k1 in pm) {

            var pushleft = pm[k1].l || {},
                pushbottom = pm[k1].b || {},
                fl = pushleft.val,
                pl = pushleft.size,
                fb = pushbottom.val,
                pb = pushbottom.size;

            for(var k2 in pm) {
                if(isNumeric(pl) && pm[k2].r) {
                    var fr = pm[k2].r.val,
                        pr = pm[k2].r.size;

                    if(fr > fl) {
                        var newl = (pl * fr +
                                (pr - fullLayout.width) * fl) / (fr - fl),
                            newr = (pr * (1 - fl) +
                                (pl - fullLayout.width) * (1 - fr)) / (fr - fl);
                        if(newl >= 0 && newr >= 0 && newl + newr > ml + mr) {
                            ml = newl;
                            mr = newr;
                        }
                    }
                }

                if(isNumeric(pb) && pm[k2].t) {
                    var ft = pm[k2].t.val,
                        pt = pm[k2].t.size;

                    if(ft > fb) {
                        var newb = (pb * ft +
                                (pt - fullLayout.height) * fb) / (ft - fb),
                            newt = (pt * (1 - fb) +
                                (pb - fullLayout.height) * (1 - ft)) / (ft - fb);
                        if(newb >= 0 && newt >= 0 && newb + newt > mb + mt) {
                            mb = newb;
                            mt = newt;
                        }
                    }
                }
            }
        }
    }

    gs.l = Math.round(ml);
    gs.r = Math.round(mr);
    gs.t = Math.round(mt);
    gs.b = Math.round(mb);
    gs.p = Math.round(fullLayout.margin.pad);
    gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
    gs.h = Math.round(fullLayout.height) - gs.t - gs.b;

    // if things changed and we're not already redrawing, trigger a redraw
    if(!fullLayout._replotting && oldmargins !== '{}' &&
            oldmargins !== JSON.stringify(fullLayout._size)) {
        return Registry.call('plot', gd);
    }
};

/**
 * JSONify the graph data and layout
 *
 * This function needs to recurse because some src can be inside
 * sub-objects.
 *
 * It also strips out functions and private (starts with _) elements.
 * Therefore, we can add temporary things to data and layout that don't
 * get saved.
 *
 * @param gd The graphDiv
 * @param {Boolean} dataonly If true, don't return layout.
 * @param {'keepref'|'keepdata'|'keepall'} [mode='keepref'] Filter what's kept
 *      keepref: remove data for which there's a src present
 *          eg if there's xsrc present (and xsrc is well-formed,
 *          ie has : and some chars before it), strip out x
 *      keepdata: remove all src tags, don't remove the data itself
 *      keepall: keep data and src
 * @param {String} output If you specify 'object', the result will not be stringified
 * @param {Boolean} useDefaults If truthy, use _fullLayout and _fullData
 * @returns {Object|String}
 */
plots.graphJson = function(gd, dataonly, mode, output, useDefaults) {
    // if the defaults aren't supplied yet, we need to do that...
    if((useDefaults && dataonly && !gd._fullData) ||
            (useDefaults && !dataonly && !gd._fullLayout)) {
        plots.supplyDefaults(gd);
    }

    var data = (useDefaults) ? gd._fullData : gd.data,
        layout = (useDefaults) ? gd._fullLayout : gd.layout,
        frames = (gd._transitionData || {})._frames;

    function stripObj(d) {
        if(typeof d === 'function') {
            return null;
        }
        if(Lib.isPlainObject(d)) {
            var o = {}, v, src;
            for(v in d) {
                // remove private elements and functions
                // _ is for private, [ is a mistake ie [object Object]
                if(typeof d[v] === 'function' ||
                        ['_', '['].indexOf(v.charAt(0)) !== -1) {
                    continue;
                }

                // look for src/data matches and remove the appropriate one
                if(mode === 'keepdata') {
                    // keepdata: remove all ...src tags
                    if(v.substr(v.length - 3) === 'src') {
                        continue;
                    }
                }
                else if(mode === 'keepstream') {
                    // keep sourced data if it's being streamed.
                    // similar to keepref, but if the 'stream' object exists
                    // in a trace, we will keep the data array.
                    src = d[v + 'src'];
                    if(typeof src === 'string' && src.indexOf(':') > 0) {
                        if(!Lib.isPlainObject(d.stream)) {
                            continue;
                        }
                    }
                }
                else if(mode !== 'keepall') {
                    // keepref: remove sourced data but only
                    // if the source tag is well-formed
                    src = d[v + 'src'];
                    if(typeof src === 'string' && src.indexOf(':') > 0) {
                        continue;
                    }
                }

                // OK, we're including this... recurse into it
                o[v] = stripObj(d[v]);
            }
            return o;
        }

        if(Array.isArray(d)) {
            return d.map(stripObj);
        }

        // convert native dates to date strings...
        // mostly for external users exporting to plotly
        if(Lib.isJSDate(d)) return Lib.ms2DateTimeLocal(+d);

        return d;
    }

    var obj = {
        data: (data || []).map(function(v) {
            var d = stripObj(v);
            // fit has some little arrays in it that don't contain data,
            // just fit params and meta
            if(dataonly) { delete d.fit; }
            return d;
        })
    };
    if(!dataonly) { obj.layout = stripObj(layout); }

    if(gd.framework && gd.framework.isPolar) obj = gd.framework.getConfig();

    if(frames) obj.frames = stripObj(frames);

    return (output === 'object') ? obj : JSON.stringify(obj);
};

/**
 * Modify a keyframe using a list of operations:
 *
 * @param {array of objects} operations
 *      Sequence of operations to be performed on the keyframes
 */
plots.modifyFrames = function(gd, operations) {
    var i, op, frame;
    var _frames = gd._transitionData._frames;
    var _frameHash = gd._transitionData._frameHash;

    for(i = 0; i < operations.length; i++) {
        op = operations[i];

        switch(op.type) {
            // No reason this couldn't exist, but is currently unused/untested:
            /* case 'rename':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frameHash[op.name] = frame;
                frame.name = op.name;
                break;*/
            case 'replace':
                frame = op.value;
                var oldName = (_frames[op.index] || {}).name;
                var newName = frame.name;
                _frames[op.index] = _frameHash[newName] = frame;

                if(newName !== oldName) {
                    // If name has changed in addition to replacement, then update
                    // the lookup table:
                    delete _frameHash[oldName];
                    _frameHash[newName] = frame;
                }

                break;
            case 'insert':
                frame = op.value;
                _frameHash[frame.name] = frame;
                _frames.splice(op.index, 0, frame);
                break;
            case 'delete':
                frame = _frames[op.index];
                delete _frameHash[frame.name];
                _frames.splice(op.index, 1);
                break;
        }
    }

    return Promise.resolve();
};

/*
 * Compute a keyframe. Merge a keyframe into its base frame(s) and
 * expand properties.
 *
 * @param {object} frameLookup
 *      An object containing frames keyed by name (i.e. gd._transitionData._frameHash)
 * @param {string} frame
 *      The name of the keyframe to be computed
 *
 * Returns: a new object with the merged content
 */
plots.computeFrame = function(gd, frameName) {
    var frameLookup = gd._transitionData._frameHash;
    var i, traceIndices, traceIndex, destIndex;

    // Null or undefined will fail on .toString(). We'll allow numbers since we
    // make it clear frames must be given string names, but we'll allow numbers
    // here since they're otherwise fine for looking up frames as long as they're
    // properly cast to strings. We really just want to ensure here that this
    // 1) doesn't fail, and
    // 2) doens't give an incorrect answer (which String(frameName) would)
    if(!frameName) {
        throw new Error('computeFrame must be given a string frame name');
    }

    var framePtr = frameLookup[frameName.toString()];

    // Return false if the name is invalid:
    if(!framePtr) {
        return false;
    }

    var frameStack = [framePtr];
    var frameNameStack = [framePtr.name];

    // Follow frame pointers:
    while(framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) {
        // Avoid infinite loops:
        if(frameNameStack.indexOf(framePtr.name) !== -1) break;

        frameStack.push(framePtr);
        frameNameStack.push(framePtr.name);
    }

    // A new object for the merged result:
    var result = {};

    // Merge, starting with the last and ending with the desired frame:
    while((framePtr = frameStack.pop())) {
        if(framePtr.layout) {
            result.layout = plots.extendLayout(result.layout, framePtr.layout);
        }

        if(framePtr.data) {
            if(!result.data) {
                result.data = [];
            }
            traceIndices = framePtr.traces;

            if(!traceIndices) {
                // If not defined, assume serial order starting at zero
                traceIndices = [];
                for(i = 0; i < framePtr.data.length; i++) {
                    traceIndices[i] = i;
                }
            }

            if(!result.traces) {
                result.traces = [];
            }

            for(i = 0; i < framePtr.data.length; i++) {
                // Loop through this frames data, find out where it should go,
                // and merge it!
                traceIndex = traceIndices[i];
                if(traceIndex === undefined || traceIndex === null) {
                    continue;
                }

                destIndex = result.traces.indexOf(traceIndex);
                if(destIndex === -1) {
                    destIndex = result.data.length;
                    result.traces[destIndex] = traceIndex;
                }

                result.data[destIndex] = plots.extendTrace(result.data[destIndex], framePtr.data[i]);
            }
        }
    }

    return result;
};

/*
 * Recompute the lookup table that maps frame name -> frame object. addFrames/
 * deleteFrames already manages this data one at a time, so the only time this
 * is necessary is if you poke around manually in `gd._transitionData._frames`
 * and create and haven't updated the lookup table.
 */
plots.recomputeFrameHash = function(gd) {
    var hash = gd._transitionData._frameHash = {};
    var frames = gd._transitionData._frames;
    for(var i = 0; i < frames.length; i++) {
        var frame = frames[i];
        if(frame && frame.name) {
            hash[frame.name] = frame;
        }
    }
};

/**
 * Extend an object, treating container arrays very differently by extracting
 * their contents and merging them separately.
 *
 * This exists so that we can extendDeepNoArrays and avoid stepping into data
 * arrays without knowledge of the plot schema, but so that we may also manually
 * recurse into known container arrays, such as transforms.
 *
 * See extendTrace and extendLayout below for usage.
 */
plots.extendObjectWithContainers = function(dest, src, containerPaths) {
    var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer;
    var copy = Lib.extendDeepNoArrays({}, src || {});
    var expandedObj = Lib.expandObjectPaths(copy);
    var containerObj = {};

    // Step through and extract any container properties. Otherwise extendDeepNoArrays
    // will clobber any existing properties with an empty array and then supplyDefaults
    // will reset everything to defaults.
    if(containerPaths && containerPaths.length) {
        for(i = 0; i < containerPaths.length; i++) {
            containerProp = Lib.nestedProperty(expandedObj, containerPaths[i]);
            containerVal = containerProp.get();

            if(containerVal === undefined) {
                Lib.nestedProperty(containerObj, containerPaths[i]).set(null);
            }
            else {
                containerProp.set(null);
                Lib.nestedProperty(containerObj, containerPaths[i]).set(containerVal);
            }
        }
    }

    dest = Lib.extendDeepNoArrays(dest || {}, expandedObj);

    if(containerPaths && containerPaths.length) {
        for(i = 0; i < containerPaths.length; i++) {
            srcProp = Lib.nestedProperty(containerObj, containerPaths[i]);
            srcContainer = srcProp.get();

            if(!srcContainer) continue;

            destProp = Lib.nestedProperty(dest, containerPaths[i]);
            destContainer = destProp.get();

            if(!Array.isArray(destContainer)) {
                destContainer = [];
                destProp.set(destContainer);
            }

            for(j = 0; j < srcContainer.length; j++) {
                var srcObj = srcContainer[j];

                if(srcObj === null) destContainer[j] = null;
                else {
                    destContainer[j] = plots.extendObjectWithContainers(destContainer[j], srcObj);
                }
            }

            destProp.set(destContainer);
        }
    }

    return dest;
};

plots.dataArrayContainers = ['transforms', 'dimensions'];
plots.layoutArrayContainers = Registry.layoutArrayContainers;

/*
 * Extend a trace definition. This method:
 *
 *  1. directly transfers any array references
 *  2. manually recurses into container arrays like transforms
 *
 * The result is the original object reference with the new contents merged in.
 */
plots.extendTrace = function(destTrace, srcTrace) {
    return plots.extendObjectWithContainers(destTrace, srcTrace, plots.dataArrayContainers);
};

/*
 * Extend a layout definition. This method:
 *
 *  1. directly transfers any array references (not critically important for
 *     layout since there aren't really data arrays)
 *  2. manually recurses into container arrays like annotations
 *
 * The result is the original object reference with the new contents merged in.
 */
plots.extendLayout = function(destLayout, srcLayout) {
    return plots.extendObjectWithContainers(destLayout, srcLayout, plots.layoutArrayContainers);
};

/**
 * Transition to a set of new data and layout properties
 *
 * @param {DOM element} gd
 *      the DOM element of the graph container div
 * @param {Object[]} data
 *      an array of data objects following the normal Plotly data definition format
 * @param {Object} layout
 *      a layout object, following normal Plotly layout format
 * @param {Number[]} traces
 *      indices of the corresponding traces specified in `data`
 * @param {Object} frameOpts
 *      options for the frame (i.e. whether to redraw post-transition)
 * @param {Object} transitionOpts
 *      options for the transition
 */
plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) {
    var i, traceIdx;

    var dataLength = Array.isArray(data) ? data.length : 0;
    var traceIndices = traces.slice(0, dataLength);

    var transitionedTraces = [];

    function prepareTransitions() {
        var i;

        for(i = 0; i < traceIndices.length; i++) {
            var traceIdx = traceIndices[i];
            var trace = gd._fullData[traceIdx];
            var module = trace._module;

            // There's nothing to do if this module is not defined:
            if(!module) continue;

            // Don't register the trace as transitioned if it doens't know what to do.
            // If it *is* registered, it will receive a callback that it's responsible
            // for calling in order to register the transition as having completed.
            if(module.animatable) {
                transitionedTraces.push(traceIdx);
            }

            gd.data[traceIndices[i]] = plots.extendTrace(gd.data[traceIndices[i]], data[i]);
        }

        // Follow the same procedure. Clone it so we don't mangle the input, then
        // expand any object paths so we can merge deep into gd.layout:
        var layoutUpdate = Lib.expandObjectPaths(Lib.extendDeepNoArrays({}, layout));

        // Before merging though, we need to modify the incoming layout. We only
        // know how to *transition* layout ranges, so it's imperative that a new
        // range not be sent to the layout before the transition has started. So
        // we must remove the things we can transition:
        var axisAttrRe = /^[xy]axis[0-9]*$/;
        for(var attr in layoutUpdate) {
            if(!axisAttrRe.test(attr)) continue;
            delete layoutUpdate[attr].range;
        }

        plots.extendLayout(gd.layout, layoutUpdate);

        // Supply defaults after applying the incoming properties. Note that any attempt
        // to simplify this step and reduce the amount of work resulted in the reconstruction
        // of essentially the whole supplyDefaults step, so that it seems sensible to just use
        // supplyDefaults even though it's heavier than would otherwise be desired for
        // transitions:

        // first delete calcdata so supplyDefaults knows a calc step is coming
        delete gd.calcdata;

        plots.supplyDefaults(gd);

        plots.doCalcdata(gd);

        Registry.getComponentMethod('errorbars', 'calc')(gd);

        return Promise.resolve();
    }

    function executeCallbacks(list) {
        var p = Promise.resolve();
        if(!list) return p;
        while(list.length) {
            p = p.then((list.shift()));
        }
        return p;
    }

    function flushCallbacks(list) {
        if(!list) return;
        while(list.length) {
            list.shift();
        }
    }

    var aborted = false;

    function executeTransitions() {

        gd.emit('plotly_transitioning', []);

        return new Promise(function(resolve) {
            // This flag is used to disabled things like autorange:
            gd._transitioning = true;

            // When instantaneous updates are coming through quickly, it's too much to simply disable
            // all interaction, so store this flag so we can disambiguate whether mouse interactions
            // should be fully disabled or not:
            if(transitionOpts.duration > 0) {
                gd._transitioningWithDuration = true;
            }


            // If another transition is triggered, this callback will be executed simply because it's
            // in the interruptCallbacks queue. If this transition completes, it will instead flush
            // that queue and forget about this callback.
            gd._transitionData._interruptCallbacks.push(function() {
                aborted = true;
            });

            if(frameOpts.redraw) {
                gd._transitionData._interruptCallbacks.push(function() {
                    return Registry.call('redraw', gd);
                });
            }

            // Emit this and make sure it happens last:
            gd._transitionData._interruptCallbacks.push(function() {
                gd.emit('plotly_transitioninterrupted', []);
            });

            // Construct callbacks that are executed on transition end. This ensures the d3 transitions
            // are *complete* before anything else is done.
            var numCallbacks = 0;
            var numCompleted = 0;
            function makeCallback() {
                numCallbacks++;
                return function() {
                    numCompleted++;
                    // When all are complete, perform a redraw:
                    if(!aborted && numCompleted === numCallbacks) {
                        completeTransition(resolve);
                    }
                };
            }

            var traceTransitionOpts;
            var j;
            var basePlotModules = gd._fullLayout._basePlotModules;
            var hasAxisTransition = false;

            if(layout) {
                for(j = 0; j < basePlotModules.length; j++) {
                    if(basePlotModules[j].transitionAxes) {
                        var newLayout = Lib.expandObjectPaths(layout);
                        hasAxisTransition = basePlotModules[j].transitionAxes(gd, newLayout, transitionOpts, makeCallback) || hasAxisTransition;
                    }
                }
            }

            // Here handle the exception that we refuse to animate scales and axes at the same
            // time. In other words, if there's an axis transition, then set the data transition
            // to instantaneous.
            if(hasAxisTransition) {
                traceTransitionOpts = Lib.extendFlat({}, transitionOpts);
                traceTransitionOpts.duration = 0;
            } else {
                traceTransitionOpts = transitionOpts;
            }

            for(j = 0; j < basePlotModules.length; j++) {
                // Note that we pass a callback to *create* the callback that must be invoked on completion.
                // This is since not all traces know about transitions, so it greatly simplifies matters if
                // the trace is responsible for creating a callback, if needed, and then executing it when
                // the time is right.
                basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
            }

            // If nothing else creates a callback, then this will trigger the completion in the next tick:
            setTimeout(makeCallback());

        });
    }

    function completeTransition(callback) {
        // This a simple workaround for tests which purge the graph before animations
        // have completed. That's not a very common case, so this is the simplest
        // fix.
        if(!gd._transitionData) return;

        flushCallbacks(gd._transitionData._interruptCallbacks);

        return Promise.resolve().then(function() {
            if(frameOpts.redraw) {
                return Registry.call('redraw', gd);
            }
        }).then(function() {
            // Set transitioning false again once the redraw has occurred. This is used, for example,
            // to prevent the trailing redraw from autoranging:
            gd._transitioning = false;
            gd._transitioningWithDuration = false;

            gd.emit('plotly_transitioned', []);
        }).then(callback);
    }

    function interruptPreviousTransitions() {
        // Fail-safe against purged plot:
        if(!gd._transitionData) return;

        // If a transition is interrupted, set this to false. At the moment, the only thing that would
        // interrupt a transition is another transition, so that it will momentarily be set to true
        // again, but this determines whether autorange or dragbox work, so it's for the sake of
        // cleanliness:
        gd._transitioning = false;

        return executeCallbacks(gd._transitionData._interruptCallbacks);
    }

    for(i = 0; i < traceIndices.length; i++) {
        traceIdx = traceIndices[i];
        var contFull = gd._fullData[traceIdx];
        var module = contFull._module;

        if(!module) continue;
    }

    var seq = [plots.previousPromises, interruptPreviousTransitions, prepareTransitions, plots.rehover, executeTransitions];

    var transitionStarting = Lib.syncOrAsync(seq, gd);

    if(!transitionStarting || !transitionStarting.then) {
        transitionStarting = Promise.resolve();
    }

    return transitionStarting.then(function() {
        return gd;
    });
};

plots.doCalcdata = function(gd, traces) {
    var axList = axisIDs.list(gd),
        fullData = gd._fullData,
        fullLayout = gd._fullLayout;

    var trace, _module, i, j;

    // XXX: Is this correct? Needs a closer look so that *some* traces can be recomputed without
    // *all* needing doCalcdata:
    var calcdata = new Array(fullData.length);
    var oldCalcdata = (gd.calcdata || []).slice(0);
    gd.calcdata = calcdata;

    // extra helper variables
    // firstscatter: fill-to-next on the first trace goes to zero
    gd.firstscatter = true;

    // how many box/violins plots do we have (in case they're grouped)
    fullLayout._numBoxes = 0;
    fullLayout._numViolins = 0;

    // initialize violin per-scale-group stats container
    fullLayout._violinScaleGroupStats = {};

    // for calculating avg luminosity of heatmaps
    gd._hmpixcount = 0;
    gd._hmlumcount = 0;

    // for sharing colors across pies (and for legend)
    fullLayout._piecolormap = {};
    fullLayout._piecolorway = null;
    fullLayout._piedefaultcolorcount = 0;

    // If traces were specified and this trace was not included,
    // then transfer it over from the old calcdata:
    for(i = 0; i < fullData.length; i++) {
        if(Array.isArray(traces) && traces.indexOf(i) === -1) {
            calcdata[i] = oldCalcdata[i];
            continue;
        }
    }

    // find array attributes in trace
    for(i = 0; i < fullData.length; i++) {
        trace = fullData[i];
        trace._arrayAttrs = PlotSchema.findArrayAttributes(trace);
    }

    // add polar axes to axis list
    var polarIds = fullLayout._subplots.polar || [];
    for(i = 0; i < polarIds.length; i++) {
        axList.push(
            fullLayout[polarIds[i]].radialaxis,
            fullLayout[polarIds[i]].angularaxis
        );
    }

    clearAxesCalc(axList);

    var hasCalcTransform = false;

    // transform loop
    for(i = 0; i < fullData.length; i++) {
        trace = fullData[i];

        if(trace.visible === true && trace.transforms) {
            _module = trace._module;

            // we need one round of trace module calc before
            // the calc transform to 'fill in' the categories list
            // used for example in the data-to-coordinate method
            if(_module && _module.calc) _module.calc(gd, trace);

            for(j = 0; j < trace.transforms.length; j++) {
                var transform = trace.transforms[j];

                _module = transformsRegistry[transform.type];
                if(_module && _module.calcTransform) {
                    trace._hasCalcTransform = true;
                    hasCalcTransform = true;
                    _module.calcTransform(gd, trace, transform);
                }
            }
        }
    }

    // clear stuff that should recomputed in 'regular' loop
    if(hasCalcTransform) clearAxesCalc(axList);

    function calci(i, isContainer) {
        trace = fullData[i];
        _module = trace._module;

        if(!!_module.isContainer !== isContainer) return;

        var cd = [];

        if(trace.visible === true) {

            // keep ref of index-to-points map object of the *last* enabled transform,
            // this index-to-points map object is required to determine the calcdata indices
            // that correspond to input indices (e.g. from 'selectedpoints')
            var transforms = trace.transforms || [];
            for(j = transforms.length - 1; j >= 0; j--) {
                if(transforms[j].enabled) {
                    trace._indexToPoints = transforms[j]._indexToPoints;
                    break;
                }
            }

            if(_module && _module.calc) {
                cd = _module.calc(gd, trace);
            }
        }

        // Make sure there is a first point.
        //
        // This ensures there is a calcdata item for every trace,
        // even if cartesian logic doesn't handle it (for things like legends).
        if(!Array.isArray(cd) || !cd[0]) {
            cd = [{x: BADNUM, y: BADNUM}];
        }

        // add the trace-wide properties to the first point,
        // per point properties to every point
        // t is the holder for trace-wide properties
        if(!cd[0].t) cd[0].t = {};
        cd[0].trace = trace;

        calcdata[i] = cd;
    }

    // 'regular' loop - make sure container traces (eg carpet) calc before
    // contained traces (eg contourcarpet)
    for(i = 0; i < fullData.length; i++) calci(i, true);
    for(i = 0; i < fullData.length; i++) calci(i, false);

    Registry.getComponentMethod('fx', 'calc')(gd);
};

function clearAxesCalc(axList) {
    for(var i = 0; i < axList.length; i++) {
        axList[i].clearCalc();
    }
}

plots.rehover = function(gd) {
    if(gd._fullLayout._rehover) {
        gd._fullLayout._rehover();
    }
};

plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) {
    var traceHashOld = subplot.traceHash;
    var traceHash = {};
    var i;

    // build up moduleName -> calcData hash
    for(i = 0; i < subplotCalcData.length; i++) {
        var calcTraces = subplotCalcData[i],
            trace = calcTraces[0].trace;

        // skip over visible === false traces
        // as they don't have `_module` ref
        if(trace.visible) {
            traceHash[trace.type] = traceHash[trace.type] || [];
            traceHash[trace.type].push(calcTraces);
        }
    }

    // when a trace gets deleted, make sure that its module's
    // plot method is called so that it is properly
    // removed from the DOM.
    for(var moduleNameOld in traceHashOld) {
        if(!traceHash[moduleNameOld]) {
            var fakeCalcTrace = traceHashOld[moduleNameOld][0],
                fakeTrace = fakeCalcTrace[0].trace;

            fakeTrace.visible = false;
            traceHash[moduleNameOld] = [fakeCalcTrace];
        }
    }

    // call module plot method
    for(var moduleName in traceHash) {
        var moduleCalcData = traceHash[moduleName];
        var _module = moduleCalcData[0][0].trace._module;

        _module.plot(gd, subplot, Lib.filterVisible(moduleCalcData), subplotLayout);
    }

    // update moduleName -> calcData hash
    subplot.traceHash = traceHash;
};

},{"../components/color":43,"../constants/numerical":145,"../lib":164,"../plot_api/plot_schema":197,"../plots/cartesian/axis_ids":209,"../registry":254,"./animation_attributes":201,"./attributes":203,"./command":230,"./font_attributes":232,"./frame_attributes":233,"./layout_attributes":236,"./sort_modules":252,"d3":6,"fast-isnumeric":9}],246:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = require('../../../traces/scatter/attributes');
var scatterMarkerAttrs = scatterAttrs.marker;

module.exports = {
    r: scatterAttrs.r,
    t: scatterAttrs.t,
    marker: {
        color: scatterMarkerAttrs.color,
        size: scatterMarkerAttrs.size,
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        editType: 'calc'
    }
};

},{"../../../traces/scatter/attributes":266}],247:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var axesAttrs = require('../../cartesian/layout_attributes');
var extendFlat = require('../../../lib/extend').extendFlat;
var overrideAll = require('../../../plot_api/edit_types').overrideAll;

var domainAttr = extendFlat({}, axesAttrs.domain, {
    
});

function mergeAttrs(axisName, nonCommonAttrs) {
    var commonAttrs = {
        showline: {
            valType: 'boolean',
            
            
        },
        showticklabels: {
            valType: 'boolean',
            
            
        },
        tickorientation: {
            valType: 'enumerated',
            values: ['horizontal', 'vertical'],
            
            
        },
        ticklen: {
            valType: 'number',
            min: 0,
            
            
        },
        tickcolor: {
            valType: 'color',
            
            
        },
        ticksuffix: {
            valType: 'string',
            
            
        },
        endpadding: {
            valType: 'number',
            
        },
        visible: {
            valType: 'boolean',
            
            
        }
    };

    return extendFlat({}, nonCommonAttrs, commonAttrs);
}

module.exports = overrideAll({
    radialaxis: mergeAttrs('radial', {
        range: {
            valType: 'info_array',
            
            items: [
                { valType: 'number' },
                { valType: 'number' }
            ],
            
        },
        domain: domainAttr,
        orientation: {
            valType: 'number',
            
            
        }
    }),

    angularaxis: mergeAttrs('angular', {
        range: {
            valType: 'info_array',
            
            items: [
                { valType: 'number', dflt: 0 },
                { valType: 'number', dflt: 360 }
            ],
            
        },
        domain: domainAttr
    }),

    // attributes that appear at layout root
    layout: {
        direction: {
            valType: 'enumerated',
            values: ['clockwise', 'counterclockwise'],
            
            
        },
        orientation: {
            valType: 'angle',
            
            
        }
    }
}, 'plot', 'nested');

},{"../../../lib/extend":157,"../../../plot_api/edit_types":191,"../../cartesian/layout_attributes":218}],248:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Polar = module.exports = require('./micropolar');

Polar.manager = require('./micropolar_manager');

},{"./micropolar":249,"./micropolar_manager":250}],249:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

var d3 = require('d3');
var Lib = require('../../../lib');
var extendDeepAll = Lib.extendDeepAll;
var MID_SHIFT = require('../../../constants/alignment').MID_SHIFT;

var µ = module.exports = { version: '0.2.2' };

µ.Axis = function module() {
    var config = {
        data: [],
        layout: {}
    }, inputConfig = {}, liveConfig = {};
    var svg, container, dispatch = d3.dispatch('hover'), radialScale, angularScale;
    var exports = {};
    function render(_container) {
        container = _container || container;
        var data = config.data;
        var axisConfig = config.layout;
        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
        container.datum(data).each(function(_data, _index) {
            var dataOriginal = _data.slice();
            liveConfig = {
                data: µ.util.cloneJson(dataOriginal),
                layout: µ.util.cloneJson(axisConfig)
            };
            var colorIndex = 0;
            dataOriginal.forEach(function(d, i) {
                if (!d.color) {
                    d.color = axisConfig.defaultColorRange[colorIndex];
                    colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length;
                }
                if (!d.strokeColor) {
                    d.strokeColor = d.geometry === 'LinePlot' ? d.color : d3.rgb(d.color).darker().toString();
                }
                liveConfig.data[i].color = d.color;
                liveConfig.data[i].strokeColor = d.strokeColor;
                liveConfig.data[i].strokeDash = d.strokeDash;
                liveConfig.data[i].strokeSize = d.strokeSize;
            });
            var data = dataOriginal.filter(function(d, i) {
                var visible = d.visible;
                return typeof visible === 'undefined' || visible === true;
            });
            var isStacked = false;
            var dataWithGroupId = data.map(function(d, i) {
                isStacked = isStacked || typeof d.groupId !== 'undefined';
                return d;
            });
            if (isStacked) {
                var grouped = d3.nest().key(function(d, i) {
                    return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked';
                }).entries(dataWithGroupId);
                var dataYStack = [];
                var stacked = grouped.map(function(d, i) {
                    if (d.key === 'unstacked') return d.values; else {
                        var prevArray = d.values[0].r.map(function(d, i) {
                            return 0;
                        });
                        d.values.forEach(function(d, i, a) {
                            d.yStack = [ prevArray ];
                            dataYStack.push(prevArray);
                            prevArray = µ.util.sumArrays(d.r, prevArray);
                        });
                        return d.values;
                    }
                });
                data = d3.merge(stacked);
            }
            data.forEach(function(d, i) {
                d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ];
                d.r = Array.isArray(d.r[0]) ? d.r : [ d.r ];
            });
            var radius = Math.min(axisConfig.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
            radius = Math.max(10, radius);
            var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
            var extent;
            if (isStacked) {
                var highestStackedValue = d3.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack)));
                extent = [ 0, highestStackedValue ];
            } else extent = d3.extent(µ.util.flattenArray(data.map(function(d, i) {
                return d.r;
            })));
            if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0;
            radialScale = d3.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]);
            liveConfig.layout.radialAxis.domain = radialScale.domain();
            var angularDataMerged = µ.util.flattenArray(data.map(function(d, i) {
                return d.t;
            }));
            var isOrdinal = typeof angularDataMerged[0] === 'string';
            var ticks;
            if (isOrdinal) {
                angularDataMerged = µ.util.deduplicate(angularDataMerged);
                ticks = angularDataMerged.slice();
                angularDataMerged = d3.range(angularDataMerged.length);
                data = data.map(function(d, i) {
                    var result = d;
                    d.t = [ angularDataMerged ];
                    if (isStacked) result.yStack = d.yStack;
                    return result;
                });
            }
            var hasOnlyLineOrDotPlot = data.filter(function(d, i) {
                return d.geometry === 'LinePlot' || d.geometry === 'DotPlot';
            }).length === data.length;
            var needsEndSpacing = axisConfig.needsEndSpacing === null ? isOrdinal || !hasOnlyLineOrDotPlot : axisConfig.needsEndSpacing;
            var useProvidedDomain = axisConfig.angularAxis.domain && axisConfig.angularAxis.domain != µ.DATAEXTENT && !isOrdinal && axisConfig.angularAxis.domain[0] >= 0;
            var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : d3.extent(angularDataMerged);
            var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]);
            if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0;
            var angularDomainWithPadding = angularDomain.slice();
            if (needsEndSpacing && isOrdinal) angularDomainWithPadding[1] += angularDomainStep;
            var tickCount = axisConfig.angularAxis.ticksCount || 4;
            if (tickCount > 8) tickCount = tickCount / (tickCount / 8) + tickCount % 8;
            if (axisConfig.angularAxis.ticksStep) {
                tickCount = (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / tickCount;
            }
            var angularTicksStep = axisConfig.angularAxis.ticksStep || (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / (tickCount * (axisConfig.minorTicks + 1));
            if (ticks) angularTicksStep = Math.max(Math.round(angularTicksStep), 1);
            if (!angularDomainWithPadding[2]) angularDomainWithPadding[2] = angularTicksStep;
            var angularAxisRange = d3.range.apply(this, angularDomainWithPadding);
            angularAxisRange = angularAxisRange.map(function(d, i) {
                return parseFloat(d.toPrecision(12));
            });
            angularScale = d3.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]);
            liveConfig.layout.angularAxis.domain = angularScale.domain();
            liveConfig.layout.angularAxis.endPadding = needsEndSpacing ? angularDomainStep : 0;
            svg = d3.select(this).select('svg.chart-root');
            if (typeof svg === 'undefined' || svg.empty()) {
                var skeleton = "<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>";
                var doc = new DOMParser().parseFromString(skeleton, 'application/xml');
                var newSvg = this.appendChild(this.ownerDocument.importNode(doc.documentElement, true));
                svg = d3.select(newSvg);
            }
            svg.select('.guides-group').style({
                'pointer-events': 'none'
            });
            svg.select('.angular.axis-group').style({
                'pointer-events': 'none'
            });
            svg.select('.radial.axis-group').style({
                'pointer-events': 'none'
            });
            var chartGroup = svg.select('.chart-group');
            var lineStyle = {
                fill: 'none',
                stroke: axisConfig.tickColor
            };
            var fontStyle = {
                'font-size': axisConfig.font.size,
                'font-family': axisConfig.font.family,
                fill: axisConfig.font.color,
                'text-shadow': [ '-1px 0px', '1px -1px', '-1px 1px', '1px 1px' ].map(function(d, i) {
                    return ' ' + d + ' 0 ' + axisConfig.font.outlineColor;
                }).join(',')
            };
            var legendContainer;
            if (axisConfig.showLegend) {
                legendContainer = svg.select('.legend-group').attr({
                    transform: 'translate(' + [ radius, axisConfig.margin.top ] + ')'
                }).style({
                    display: 'block'
                });
                var elements = data.map(function(d, i) {
                    var datumClone = µ.util.cloneJson(d);
                    datumClone.symbol = d.geometry === 'DotPlot' ? d.dotType || 'circle' : d.geometry != 'LinePlot' ? 'square' : 'line';
                    datumClone.visibleInLegend = typeof d.visibleInLegend === 'undefined' || d.visibleInLegend;
                    datumClone.color = d.geometry === 'LinePlot' ? d.strokeColor : d.color;
                    return datumClone;
                });

                µ.Legend().config({
                    data: data.map(function(d, i) {
                        return d.name || 'Element' + i;
                    }),
                    legendConfig: extendDeepAll({},
                        µ.Legend.defaultConfig().legendConfig,
                        {
                            container: legendContainer,
                            elements: elements,
                            reverseOrder: axisConfig.legend.reverseOrder
                        }
                    )
                })();

                var legendBBox = legendContainer.node().getBBox();
                radius = Math.min(axisConfig.width - legendBBox.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
                radius = Math.max(10, radius);
                chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
                radialScale.range([ 0, radius ]);
                liveConfig.layout.radialAxis.domain = radialScale.domain();
                legendContainer.attr('transform', 'translate(' + [ chartCenter[0] + radius, chartCenter[1] - radius ] + ')');
            } else {
                legendContainer = svg.select('.legend-group').style({
                    display: 'none'
                });
            }
            svg.attr({
                width: axisConfig.width,
                height: axisConfig.height
            }).style({
                opacity: axisConfig.opacity
            });
            chartGroup.attr('transform', 'translate(' + chartCenter + ')').style({
                cursor: 'crosshair'
            });
            var centeringOffset = [ (axisConfig.width - (axisConfig.margin.left + axisConfig.margin.right + radius * 2 + (legendBBox ? legendBBox.width : 0))) / 2, (axisConfig.height - (axisConfig.margin.top + axisConfig.margin.bottom + radius * 2)) / 2 ];
            centeringOffset[0] = Math.max(0, centeringOffset[0]);
            centeringOffset[1] = Math.max(0, centeringOffset[1]);
            svg.select('.outer-group').attr('transform', 'translate(' + centeringOffset + ')');
            if (axisConfig.title) {
                var title = svg.select('g.title-group text').style(fontStyle).text(axisConfig.title);
                var titleBBox = title.node().getBBox();
                title.attr({
                    x: chartCenter[0] - titleBBox.width / 2,
                    y: chartCenter[1] - radius - 20
                });
            }
            var radialAxis = svg.select('.radial.axis-group');
            if (axisConfig.radialAxis.gridLinesVisible) {
                var gridCircles = radialAxis.selectAll('circle.grid-circle').data(radialScale.ticks(5));
                gridCircles.enter().append('circle').attr({
                    'class': 'grid-circle'
                }).style(lineStyle);
                gridCircles.attr('r', radialScale);
                gridCircles.exit().remove();
            }
            radialAxis.select('circle.outside-circle').attr({
                r: radius
            }).style(lineStyle);
            var backgroundCircle = svg.select('circle.background-circle').attr({
                r: radius
            }).style({
                fill: axisConfig.backgroundColor,
                stroke: axisConfig.stroke
            });
            function currentAngle(d, i) {
                return angularScale(d) % 360 + axisConfig.orientation;
            }
            if (axisConfig.radialAxis.visible) {
                var axis = d3.svg.axis().scale(radialScale).ticks(5).tickSize(5);
                radialAxis.call(axis).attr({
                    transform: 'rotate(' + axisConfig.radialAxis.orientation + ')'
                });
                radialAxis.selectAll('.domain').style(lineStyle);
                radialAxis.selectAll('g>text').text(function(d, i) {
                    return this.textContent + axisConfig.radialAxis.ticksSuffix;
                }).style(fontStyle).style({
                    'text-anchor': 'start'
                }).attr({
                    x: 0,
                    y: 0,
                    dx: 0,
                    dy: 0,
                    transform: function(d, i) {
                        if (axisConfig.radialAxis.tickOrientation === 'horizontal') {
                            return 'rotate(' + -axisConfig.radialAxis.orientation + ') translate(' + [ 0, fontStyle['font-size'] ] + ')';
                        } else return 'translate(' + [ 0, fontStyle['font-size'] ] + ')';
                    }
                });
                radialAxis.selectAll('g>line').style({
                    stroke: 'black'
                });
            }
            var angularAxis = svg.select('.angular.axis-group').selectAll('g.angular-tick').data(angularAxisRange);
            var angularAxisEnter = angularAxis.enter().append('g').classed('angular-tick', true);
            angularAxis.attr({
                transform: function(d, i) {
                    return 'rotate(' + currentAngle(d, i) + ')';
                }
            }).style({
                display: axisConfig.angularAxis.visible ? 'block' : 'none'
            });
            angularAxis.exit().remove();
            angularAxisEnter.append('line').classed('grid-line', true).classed('major', function(d, i) {
                return i % (axisConfig.minorTicks + 1) == 0;
            }).classed('minor', function(d, i) {
                return !(i % (axisConfig.minorTicks + 1) == 0);
            }).style(lineStyle);
            angularAxisEnter.selectAll('.minor').style({
                stroke: axisConfig.minorTickColor
            });
            angularAxis.select('line.grid-line').attr({
                x1: axisConfig.tickLength ? radius - axisConfig.tickLength : 0,
                x2: radius
            }).style({
                display: axisConfig.angularAxis.gridLinesVisible ? 'block' : 'none'
            });
            angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle);
            var ticksText = angularAxis.select('text.axis-text').attr({
                x: radius + axisConfig.labelOffset,
                dy: MID_SHIFT + 'em',
                transform: function(d, i) {
                    var angle = currentAngle(d, i);
                    var rad = radius + axisConfig.labelOffset;
                    var orient = axisConfig.angularAxis.tickOrientation;
                    if (orient == 'horizontal') return 'rotate(' + -angle + ' ' + rad + ' 0)'; else if (orient == 'radial') return angle < 270 && angle > 90 ? 'rotate(180 ' + rad + ' 0)' : null; else return 'rotate(' + (angle <= 180 && angle > 0 ? -90 : 90) + ' ' + rad + ' 0)';
                }
            }).style({
                'text-anchor': 'middle',
                display: axisConfig.angularAxis.labelsVisible ? 'block' : 'none'
            }).text(function(d, i) {
                if (i % (axisConfig.minorTicks + 1) != 0) return '';
                if (ticks) {
                    return ticks[d] + axisConfig.angularAxis.ticksSuffix;
                } else return d + axisConfig.angularAxis.ticksSuffix;
            }).style(fontStyle);
            if (axisConfig.angularAxis.rewriteTicks) ticksText.text(function(d, i) {
                if (i % (axisConfig.minorTicks + 1) != 0) return '';
                return axisConfig.angularAxis.rewriteTicks(this.textContent, i);
            });
            var rightmostTickEndX = d3.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) {
                return d.getCTM().e + d.getBBox().width;
            }));
            legendContainer.attr({
                transform: 'translate(' + [ radius + rightmostTickEndX, axisConfig.margin.top ] + ')'
            });
            var hasGeometry = svg.select('g.geometry-group').selectAll('g').size() > 0;
            var geometryContainer = svg.select('g.geometry-group').selectAll('g.geometry').data(data);
            geometryContainer.enter().append('g').attr({
                'class': function(d, i) {
                    return 'geometry geometry' + i;
                }
            });
            geometryContainer.exit().remove();
            if (data[0] || hasGeometry) {
                var geometryConfigs = [];
                data.forEach(function(d, i) {
                    var geometryConfig = {};
                    geometryConfig.radialScale = radialScale;
                    geometryConfig.angularScale = angularScale;
                    geometryConfig.container = geometryContainer.filter(function(dB, iB) {
                        return iB == i;
                    });
                    geometryConfig.geometry = d.geometry;
                    geometryConfig.orientation = axisConfig.orientation;
                    geometryConfig.direction = axisConfig.direction;
                    geometryConfig.index = i;
                    geometryConfigs.push({
                        data: d,
                        geometryConfig: geometryConfig
                    });
                });
                var geometryConfigsGrouped = d3.nest().key(function(d, i) {
                    return typeof d.data.groupId != 'undefined' || 'unstacked';
                }).entries(geometryConfigs);
                var geometryConfigsGrouped2 = [];
                geometryConfigsGrouped.forEach(function(d, i) {
                    if (d.key === 'unstacked') geometryConfigsGrouped2 = geometryConfigsGrouped2.concat(d.values.map(function(d, i) {
                        return [ d ];
                    })); else geometryConfigsGrouped2.push(d.values);
                });
                geometryConfigsGrouped2.forEach(function(d, i) {
                    var geometry;
                    if (Array.isArray(d)) geometry = d[0].geometryConfig.geometry; else geometry = d.geometryConfig.geometry;
                    var finalGeometryConfig = d.map(function(dB, iB) {
                        return extendDeepAll(µ[geometry].defaultConfig(), dB);
                    });
                    µ[geometry]().config(finalGeometryConfig)();
                });
            }
            var guides = svg.select('.guides-group');
            var tooltipContainer = svg.select('.tooltips-group');
            var angularTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                fontSize: 8
            })();
            var radialTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                fontSize: 8
            })();
            var geometryTooltip = µ.tooltipPanel().config({
                container: tooltipContainer,
                hasTick: true
            })();
            var angularValue, radialValue;
            if (!isOrdinal) {
                var angularGuideLine = guides.select('line').attr({
                    x1: 0,
                    y1: 0,
                    y2: 0
                }).style({
                    stroke: 'grey',
                    'pointer-events': 'none'
                });
                chartGroup.on('mousemove.angular-guide', function(d, i) {
                    var mouseAngle = µ.util.getMousePos(backgroundCircle).angle;
                    angularGuideLine.attr({
                        x2: -radius,
                        transform: 'rotate(' + mouseAngle + ')'
                    }).style({
                        opacity: .5
                    });
                    var angleWithOriginOffset = (mouseAngle + 180 + 360 - axisConfig.orientation) % 360;
                    angularValue = angularScale.invert(angleWithOriginOffset);
                    var pos = µ.util.convertToCartesian(radius + 12, mouseAngle + 180);
                    angularTooltip.text(µ.util.round(angularValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
                }).on('mouseout.angular-guide', function(d, i) {
                    guides.select('line').style({
                        opacity: 0
                    });
                });
            }
            var angularGuideCircle = guides.select('circle').style({
                stroke: 'grey',
                fill: 'none'
            });
            chartGroup.on('mousemove.radial-guide', function(d, i) {
                var r = µ.util.getMousePos(backgroundCircle).radius;
                angularGuideCircle.attr({
                    r: r
                }).style({
                    opacity: .5
                });
                radialValue = radialScale.invert(µ.util.getMousePos(backgroundCircle).radius);
                var pos = µ.util.convertToCartesian(r, axisConfig.radialAxis.orientation);
                radialTooltip.text(µ.util.round(radialValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
            }).on('mouseout.radial-guide', function(d, i) {
                angularGuideCircle.style({
                    opacity: 0
                });
                geometryTooltip.hide();
                angularTooltip.hide();
                radialTooltip.hide();
            });
            svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) {
                var el = d3.select(this);
                var color = this.style.fill;
                var newColor = 'black';
                var opacity = this.style.opacity || 1;
                el.attr({
                    'data-opacity': opacity
                });
                if (color && color !== 'none') {
                    el.attr({
                        'data-fill': color
                    });
                    newColor = d3.hsl(color).darker().toString();
                    el.style({
                        fill: newColor,
                        opacity: 1
                    });
                    var textData = {
                        t: µ.util.round(d[0]),
                        r: µ.util.round(d[1])
                    };
                    if (isOrdinal) textData.t = ticks[d[0]];
                    var text = 't: ' + textData.t + ', r: ' + textData.r;
                    var bbox = this.getBoundingClientRect();
                    var svgBBox = svg.node().getBoundingClientRect();
                    var pos = [ bbox.left + bbox.width / 2 - centeringOffset[0] - svgBBox.left, bbox.top + bbox.height / 2 - centeringOffset[1] - svgBBox.top ];
                    geometryTooltip.config({
                        color: newColor
                    }).text(text);
                    geometryTooltip.move(pos);
                } else {
                    color = this.style.stroke || 'black';
                    el.attr({
                        'data-stroke': color
                    });
                    newColor = d3.hsl(color).darker().toString();
                    el.style({
                        stroke: newColor,
                        opacity: 1
                    });
                }
            }).on('mousemove.tooltip', function(d, i) {
                if (d3.event.which != 0) return false;
                if (d3.select(this).attr('data-fill')) geometryTooltip.show();
            }).on('mouseout.tooltip', function(d, i) {
                geometryTooltip.hide();
                var el = d3.select(this);
                var fillColor = el.attr('data-fill');
                if (fillColor) el.style({
                    fill: fillColor,
                    opacity: el.attr('data-opacity')
                }); else el.style({
                    stroke: el.attr('data-stroke'),
                    opacity: el.attr('data-opacity')
                });
            });
        });
        return exports;
    }
    exports.render = function(_container) {
        render(_container);
        return this;
    };
    exports.config = function(_x) {
        if (!arguments.length) return config;
        var xClone = µ.util.cloneJson(_x);
        xClone.data.forEach(function(d, i) {
            if (!config.data[i]) config.data[i] = {};
            extendDeepAll(config.data[i], µ.Axis.defaultConfig().data[0]);
            extendDeepAll(config.data[i], d);
        });
        extendDeepAll(config.layout, µ.Axis.defaultConfig().layout);
        extendDeepAll(config.layout, xClone.layout);
        return this;
    };
    exports.getLiveConfig = function() {
        return liveConfig;
    };
    exports.getinputConfig = function() {
        return inputConfig;
    };
    exports.radialScale = function(_x) {
        return radialScale;
    };
    exports.angularScale = function(_x) {
        return angularScale;
    };
    exports.svg = function() {
        return svg;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.Axis.defaultConfig = function(d, i) {
    var config = {
        data: [ {
            t: [ 1, 2, 3, 4 ],
            r: [ 10, 11, 12, 13 ],
            name: 'Line1',
            geometry: 'LinePlot',
            color: null,
            strokeDash: 'solid',
            strokeColor: null,
            strokeSize: '1',
            visibleInLegend: true,
            opacity: 1
        } ],
        layout: {
            defaultColorRange: d3.scale.category10().range(),
            title: null,
            height: 450,
            width: 500,
            margin: {
                top: 40,
                right: 40,
                bottom: 40,
                left: 40
            },
            font: {
                size: 12,
                color: 'gray',
                outlineColor: 'white',
                family: 'Tahoma, sans-serif'
            },
            direction: 'clockwise',
            orientation: 0,
            labelOffset: 10,
            radialAxis: {
                domain: null,
                orientation: -45,
                ticksSuffix: '',
                visible: true,
                gridLinesVisible: true,
                tickOrientation: 'horizontal',
                rewriteTicks: null
            },
            angularAxis: {
                domain: [ 0, 360 ],
                ticksSuffix: '',
                visible: true,
                gridLinesVisible: true,
                labelsVisible: true,
                tickOrientation: 'horizontal',
                rewriteTicks: null,
                ticksCount: null,
                ticksStep: null
            },
            minorTicks: 0,
            tickLength: null,
            tickColor: 'silver',
            minorTickColor: '#eee',
            backgroundColor: 'none',
            needsEndSpacing: null,
            showLegend: true,
            legend: {
                reverseOrder: false
            },
            opacity: 1
        }
    };
    return config;
};

µ.util = {};

µ.DATAEXTENT = 'dataExtent';

µ.AREA = 'AreaChart';

µ.LINE = 'LinePlot';

µ.DOT = 'DotPlot';

µ.BAR = 'BarChart';

µ.util._override = function(_objA, _objB) {
    for (var x in _objA) if (x in _objB) _objB[x] = _objA[x];
};

µ.util._extend = function(_objA, _objB) {
    for (var x in _objA) _objB[x] = _objA[x];
};

µ.util._rndSnd = function() {
    return Math.random() * 2 - 1 + (Math.random() * 2 - 1) + (Math.random() * 2 - 1);
};

µ.util.dataFromEquation2 = function(_equation, _step) {
    var step = _step || 6;
    var data = d3.range(0, 360 + step, step).map(function(deg, index) {
        var theta = deg * Math.PI / 180;
        var radius = _equation(theta);
        return [ deg, radius ];
    });
    return data;
};

µ.util.dataFromEquation = function(_equation, _step, _name) {
    var step = _step || 6;
    var t = [], r = [];
    d3.range(0, 360 + step, step).forEach(function(deg, index) {
        var theta = deg * Math.PI / 180;
        var radius = _equation(theta);
        t.push(deg);
        r.push(radius);
    });
    var result = {
        t: t,
        r: r
    };
    if (_name) result.name = _name;
    return result;
};

µ.util.ensureArray = function(_val, _count) {
    if (typeof _val === 'undefined') return null;
    var arr = [].concat(_val);
    return d3.range(_count).map(function(d, i) {
        return arr[i] || arr[0];
    });
};

µ.util.fillArrays = function(_obj, _valueNames, _count) {
    _valueNames.forEach(function(d, i) {
        _obj[d] = µ.util.ensureArray(_obj[d], _count);
    });
    return _obj;
};

µ.util.cloneJson = function(json) {
    return JSON.parse(JSON.stringify(json));
};

µ.util.validateKeys = function(obj, keys) {
    if (typeof keys === 'string') keys = keys.split('.');
    var next = keys.shift();
    return obj[next] && (!keys.length || objHasKeys(obj[next], keys));
};

µ.util.sumArrays = function(a, b) {
    return d3.zip(a, b).map(function(d, i) {
        return d3.sum(d);
    });
};

µ.util.arrayLast = function(a) {
    return a[a.length - 1];
};

µ.util.arrayEqual = function(a, b) {
    var i = Math.max(a.length, b.length, 1);
    while (i-- >= 0 && a[i] === b[i]) ;
    return i === -2;
};

µ.util.flattenArray = function(arr) {
    var r = [];
    while (!µ.util.arrayEqual(r, arr)) {
        r = arr;
        arr = [].concat.apply([], arr);
    }
    return arr;
};

µ.util.deduplicate = function(arr) {
    return arr.filter(function(v, i, a) {
        return a.indexOf(v) == i;
    });
};

µ.util.convertToCartesian = function(radius, theta) {
    var thetaRadians = theta * Math.PI / 180;
    var x = radius * Math.cos(thetaRadians);
    var y = radius * Math.sin(thetaRadians);
    return [ x, y ];
};

µ.util.round = function(_value, _digits) {
    var digits = _digits || 2;
    var mult = Math.pow(10, digits);
    return Math.round(_value * mult) / mult;
};

µ.util.getMousePos = function(_referenceElement) {
    var mousePos = d3.mouse(_referenceElement.node());
    var mouseX = mousePos[0];
    var mouseY = mousePos[1];
    var mouse = {};
    mouse.x = mouseX;
    mouse.y = mouseY;
    mouse.pos = mousePos;
    mouse.angle = (Math.atan2(mouseY, mouseX) + Math.PI) * 180 / Math.PI;
    mouse.radius = Math.sqrt(mouseX * mouseX + mouseY * mouseY);
    return mouse;
};

µ.util.duplicatesCount = function(arr) {
    var uniques = {}, val;
    var dups = {};
    for (var i = 0, len = arr.length; i < len; i++) {
        val = arr[i];
        if (val in uniques) {
            uniques[val]++;
            dups[val] = uniques[val];
        } else {
            uniques[val] = 1;
        }
    }
    return dups;
};

µ.util.duplicates = function(arr) {
    return Object.keys(µ.util.duplicatesCount(arr));
};

µ.util.translator = function(obj, sourceBranch, targetBranch, reverse) {
    if (reverse) {
        var targetBranchCopy = targetBranch.slice();
        targetBranch = sourceBranch;
        sourceBranch = targetBranchCopy;
    }
    var value = sourceBranch.reduce(function(previousValue, currentValue) {
        if (typeof previousValue != 'undefined') return previousValue[currentValue];
    }, obj);
    if (typeof value === 'undefined') return;
    sourceBranch.reduce(function(previousValue, currentValue, index) {
        if (typeof previousValue == 'undefined') return;
        if (index === sourceBranch.length - 1) delete previousValue[currentValue];
        return previousValue[currentValue];
    }, obj);
    targetBranch.reduce(function(previousValue, currentValue, index) {
        if (typeof previousValue[currentValue] === 'undefined') previousValue[currentValue] = {};
        if (index === targetBranch.length - 1) previousValue[currentValue] = value;
        return previousValue[currentValue];
    }, obj);
};

µ.PolyChart = function module() {
    var config = [ µ.PolyChart.defaultConfig() ];
    var dispatch = d3.dispatch('hover');
    var dashArray = {
        solid: 'none',
        dash: [ 5, 2 ],
        dot: [ 2, 5 ]
    };
    var colorScale;
    function exports() {
        var geometryConfig = config[0].geometryConfig;
        var container = geometryConfig.container;
        if (typeof container == 'string') container = d3.select(container);
        container.datum(config).each(function(_config, _index) {
            var isStack = !!_config[0].data.yStack;
            var data = _config.map(function(d, i) {
                if (isStack) return d3.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return d3.zip(d.data.t[0], d.data.r[0]);
            });
            var angularScale = geometryConfig.angularScale;
            var domainMin = geometryConfig.radialScale.domain()[0];
            var generator = {};
            generator.bar = function(d, i, pI) {
                var dataConfig = _config[pI].data;
                var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0);
                var stackTop = geometryConfig.radialScale(d[2] || 0);
                var w = dataConfig.barWidth;
                d3.select(this).attr({
                    'class': 'mark bar',
                    d: 'M' + [ [ h + stackTop, -w / 2 ], [ h + stackTop, w / 2 ], [ stackTop, w / 2 ], [ stackTop, -w / 2 ] ].join('L') + 'Z',
                    transform: function(d, i) {
                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0])) + ')';
                    }
                });
            };
            generator.dot = function(d, i, pI) {
                var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d;
                var symbol = d3.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i);
                d3.select(this).attr({
                    'class': 'mark dot',
                    d: symbol,
                    transform: function(d, i) {
                        var coord = convertToCartesian(getPolarCoordinates(stackedData));
                        return 'translate(' + [ coord.x, coord.y ] + ')';
                    }
                });
            };
            var line = d3.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) {
                return geometryConfig.radialScale(d[1]);
            }).angle(function(d) {
                return geometryConfig.angularScale(d[0]) * Math.PI / 180;
            });
            generator.line = function(d, i, pI) {
                var lineData = d[2] ? data[pI].map(function(d, i) {
                    return [ d[0], d[1] + d[2] ];
                }) : data[pI];
                d3.select(this).each(generator['dot']).style({
                    opacity: function(dB, iB) {
                        return +_config[pI].data.dotVisible;
                    },
                    fill: markStyle.stroke(d, i, pI)
                }).attr({
                    'class': 'mark dot'
                });
                if (i > 0) return;
                var lineSelection = d3.select(this.parentNode).selectAll('path.line').data([ 0 ]);
                lineSelection.enter().insert('path');
                lineSelection.attr({
                    'class': 'line',
                    d: line(lineData),
                    transform: function(dB, iB) {
                        return 'rotate(' + (geometryConfig.orientation + 90) + ')';
                    },
                    'pointer-events': 'none'
                }).style({
                    fill: function(dB, iB) {
                        return markStyle.fill(d, i, pI);
                    },
                    'fill-opacity': 0,
                    stroke: function(dB, iB) {
                        return markStyle.stroke(d, i, pI);
                    },
                    'stroke-width': function(dB, iB) {
                        return markStyle['stroke-width'](d, i, pI);
                    },
                    'stroke-dasharray': function(dB, iB) {
                        return markStyle['stroke-dasharray'](d, i, pI);
                    },
                    opacity: function(dB, iB) {
                        return markStyle.opacity(d, i, pI);
                    },
                    display: function(dB, iB) {
                        return markStyle.display(d, i, pI);
                    }
                });
            };
            var angularRange = geometryConfig.angularScale.range();
            var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180;
            var arc = d3.svg.arc().startAngle(function(d) {
                return -triangleAngle / 2;
            }).endAngle(function(d) {
                return triangleAngle / 2;
            }).innerRadius(function(d) {
                return geometryConfig.radialScale(domainMin + (d[2] || 0));
            }).outerRadius(function(d) {
                return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]);
            });
            generator.arc = function(d, i, pI) {
                d3.select(this).attr({
                    'class': 'mark arc',
                    d: arc,
                    transform: function(d, i) {
                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0]) + 90) + ')';
                    }
                });
            };
            var markStyle = {
                fill: function(d, i, pI) {
                    return _config[pI].data.color;
                },
                stroke: function(d, i, pI) {
                    return _config[pI].data.strokeColor;
                },
                'stroke-width': function(d, i, pI) {
                    return _config[pI].data.strokeSize + 'px';
                },
                'stroke-dasharray': function(d, i, pI) {
                    return dashArray[_config[pI].data.strokeDash];
                },
                opacity: function(d, i, pI) {
                    return _config[pI].data.opacity;
                },
                display: function(d, i, pI) {
                    return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none';
                }
            };
            var geometryLayer = d3.select(this).selectAll('g.layer').data(data);
            geometryLayer.enter().append('g').attr({
                'class': 'layer'
            });
            var geometry = geometryLayer.selectAll('path.mark').data(function(d, i) {
                return d;
            });
            geometry.enter().append('path').attr({
                'class': 'mark'
            });
            geometry.style(markStyle).each(generator[geometryConfig.geometryType]);
            geometry.exit().remove();
            geometryLayer.exit().remove();
            function getPolarCoordinates(d, i) {
                var r = geometryConfig.radialScale(d[1]);
                var t = (geometryConfig.angularScale(d[0]) + geometryConfig.orientation) * Math.PI / 180;
                return {
                    r: r,
                    t: t
                };
            }
            function convertToCartesian(polarCoordinates) {
                var x = polarCoordinates.r * Math.cos(polarCoordinates.t);
                var y = polarCoordinates.r * Math.sin(polarCoordinates.t);
                return {
                    x: x,
                    y: y
                };
            }
        });
    }
    exports.config = function(_x) {
        if (!arguments.length) return config;
        _x.forEach(function(d, i) {
            if (!config[i]) config[i] = {};
            extendDeepAll(config[i], µ.PolyChart.defaultConfig());
            extendDeepAll(config[i], d);
        });
        return this;
    };
    exports.getColorScale = function() {
        return colorScale;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.PolyChart.defaultConfig = function() {
    var config = {
        data: {
            name: 'geom1',
            t: [ [ 1, 2, 3, 4 ] ],
            r: [ [ 1, 2, 3, 4 ] ],
            dotType: 'circle',
            dotSize: 64,
            dotVisible: false,
            barWidth: 20,
            color: '#ffa500',
            strokeSize: 1,
            strokeColor: 'silver',
            strokeDash: 'solid',
            opacity: 1,
            index: 0,
            visible: true,
            visibleInLegend: true
        },
        geometryConfig: {
            geometry: 'LinePlot',
            geometryType: 'arc',
            direction: 'clockwise',
            orientation: 0,
            container: 'body',
            radialScale: null,
            angularScale: null,
            colorScale: d3.scale.category20()
        }
    };
    return config;
};

µ.BarChart = function module() {
    return µ.PolyChart();
};

µ.BarChart.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'bar'
        }
    };
    return config;
};

µ.AreaChart = function module() {
    return µ.PolyChart();
};

µ.AreaChart.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'arc'
        }
    };
    return config;
};

µ.DotPlot = function module() {
    return µ.PolyChart();
};

µ.DotPlot.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'dot',
            dotType: 'circle'
        }
    };
    return config;
};

µ.LinePlot = function module() {
    return µ.PolyChart();
};

µ.LinePlot.defaultConfig = function() {
    var config = {
        geometryConfig: {
            geometryType: 'line'
        }
    };
    return config;
};

µ.Legend = function module() {
    var config = µ.Legend.defaultConfig();
    var dispatch = d3.dispatch('hover');
    function exports() {
        var legendConfig = config.legendConfig;
        var flattenData = config.data.map(function(d, i) {
            return [].concat(d).map(function(dB, iB) {
                var element = extendDeepAll({}, legendConfig.elements[i]);
                element.name = dB;
                element.color = [].concat(legendConfig.elements[i].color)[iB];
                return element;
            });
        });
        var data = d3.merge(flattenData);
        data = data.filter(function(d, i) {
            return legendConfig.elements[i] && (legendConfig.elements[i].visibleInLegend || typeof legendConfig.elements[i].visibleInLegend === 'undefined');
        });
        if (legendConfig.reverseOrder) data = data.reverse();
        var container = legendConfig.container;
        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
        var colors = data.map(function(d, i) {
            return d.color;
        });
        var lineHeight = legendConfig.fontSize;
        var isContinuous = legendConfig.isContinuous == null ? typeof data[0] === 'number' : legendConfig.isContinuous;
        var height = isContinuous ? legendConfig.height : lineHeight * data.length;
        var legendContainerGroup = container.classed('legend-group', true);
        var svg = legendContainerGroup.selectAll('svg').data([ 0 ]);
        var svgEnter = svg.enter().append('svg').attr({
            width: 300,
            height: height + lineHeight,
            xmlns: 'http://www.w3.org/2000/svg',
            'xmlns:xlink': 'http://www.w3.org/1999/xlink',
            version: '1.1'
        });
        svgEnter.append('g').classed('legend-axis', true);
        svgEnter.append('g').classed('legend-marks', true);
        var dataNumbered = d3.range(data.length);
        var colorScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors);
        var dataScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]);
        var shapeGenerator = function(_type, _size) {
            var squareSize = _size * 3;
            if (_type === 'line') {
                return 'M' + [ [ -_size / 2, -_size / 12 ], [ _size / 2, -_size / 12 ], [ _size / 2, _size / 12 ], [ -_size / 2, _size / 12 ] ] + 'Z';
            } else if (d3.svg.symbolTypes.indexOf(_type) != -1) return d3.svg.symbol().type(_type).size(squareSize)(); else return d3.svg.symbol().type('square').size(squareSize)();
        };
        if (isContinuous) {
            var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({
                id: 'grad1',
                x1: '0%',
                y1: '0%',
                x2: '0%',
                y2: '100%'
            }).selectAll('stop').data(colors);
            gradient.enter().append('stop');
            gradient.attr({
                offset: function(d, i) {
                    return i / (colors.length - 1) * 100 + '%';
                }
            }).style({
                'stop-color': function(d, i) {
                    return d;
                }
            });
            svg.append('rect').classed('legend-mark', true).attr({
                height: legendConfig.height,
                width: legendConfig.colorBandWidth,
                fill: 'url(#grad1)'
            });
        } else {
            var legendElement = svg.select('.legend-marks').selectAll('path.legend-mark').data(data);
            legendElement.enter().append('path').classed('legend-mark', true);
            legendElement.attr({
                transform: function(d, i) {
                    return 'translate(' + [ lineHeight / 2, dataScale(i) + lineHeight / 2 ] + ')';
                },
                d: function(d, i) {
                    var symbolType = d.symbol;
                    return shapeGenerator(symbolType, lineHeight);
                },
                fill: function(d, i) {
                    return colorScale(i);
                }
            });
            legendElement.exit().remove();
        }
        var legendAxis = d3.svg.axis().scale(dataScale).orient('right');
        var axis = svg.select('g.legend-axis').attr({
            transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')'
        }).call(legendAxis);
        axis.selectAll('.domain').style({
            fill: 'none',
            stroke: 'none'
        });
        axis.selectAll('line').style({
            fill: 'none',
            stroke: isContinuous ? legendConfig.textColor : 'none'
        });
        axis.selectAll('text').style({
            fill: legendConfig.textColor,
            'font-size': legendConfig.fontSize
        }).text(function(d, i) {
            return data[i].name;
        });
        return exports;
    }
    exports.config = function(_x) {
        if (!arguments.length) return config;
        extendDeepAll(config, _x);
        return this;
    };
    d3.rebind(exports, dispatch, 'on');
    return exports;
};

µ.Legend.defaultConfig = function(d, i) {
    var config = {
        data: [ 'a', 'b', 'c' ],
        legendConfig: {
            elements: [ {
                symbol: 'line',
                color: 'red'
            }, {
                symbol: 'square',
                color: 'yellow'
            }, {
                symbol: 'diamond',
                color: 'limegreen'
            } ],
            height: 150,
            colorBandWidth: 30,
            fontSize: 12,
            container: 'body',
            isContinuous: null,
            textColor: 'grey',
            reverseOrder: false
        }
    };
    return config;
};

µ.tooltipPanel = function() {
    var tooltipEl, tooltipTextEl, backgroundEl;
    var config = {
        container: null,
        hasTick: false,
        fontSize: 12,
        color: 'white',
        padding: 5
    };
    var id = 'tooltip-' + µ.tooltipPanel.uid++;
    var tickSize = 10;
    var exports = function() {
        tooltipEl = config.container.selectAll('g.' + id).data([ 0 ]);
        var tooltipEnter = tooltipEl.enter().append('g').classed(id, true).style({
            'pointer-events': 'none',
            display: 'none'
        });
        backgroundEl = tooltipEnter.append('path').style({
            fill: 'white',
            'fill-opacity': .9
        }).attr({
            d: 'M0 0'
        });
        tooltipTextEl = tooltipEnter.append('text').attr({
            dx: config.padding + tickSize,
            dy: +config.fontSize * .3
        });
        return exports;
    };
    exports.text = function(_text) {
        var l = d3.hsl(config.color).l;
        var strokeColor = l >= .5 ? '#aaa' : 'white';
        var fillColor = l >= .5 ? 'black' : 'white';
        var text = _text || '';
        tooltipTextEl.style({
            fill: fillColor,
            'font-size': config.fontSize + 'px'
        }).text(text);
        var padding = config.padding;
        var bbox = tooltipTextEl.node().getBBox();
        var boxStyle = {
            fill: config.color,
            stroke: strokeColor,
            'stroke-width': '2px'
        };
        var backGroundW = bbox.width + padding * 2 + tickSize;
        var backGroundH = bbox.height + padding * 2;
        backgroundEl.attr({
            d: 'M' + [ [ tickSize, -backGroundH / 2 ], [ tickSize, -backGroundH / 4 ], [ config.hasTick ? 0 : tickSize, 0 ], [ tickSize, backGroundH / 4 ], [ tickSize, backGroundH / 2 ], [ backGroundW, backGroundH / 2 ], [ backGroundW, -backGroundH / 2 ] ].join('L') + 'Z'
        }).style(boxStyle);
        tooltipEl.attr({
            transform: 'translate(' + [ tickSize, -backGroundH / 2 + padding * 2 ] + ')'
        });
        tooltipEl.style({
            display: 'block'
        });
        return exports;
    };
    exports.move = function(_pos) {
        if (!tooltipEl) return;
        tooltipEl.attr({
            transform: 'translate(' + [ _pos[0], _pos[1] ] + ')'
        }).style({
            display: 'block'
        });
        return exports;
    };
    exports.hide = function() {
        if (!tooltipEl) return;
        tooltipEl.style({
            display: 'none'
        });
        return exports;
    };
    exports.show = function() {
        if (!tooltipEl) return;
        tooltipEl.style({
            display: 'block'
        });
        return exports;
    };
    exports.config = function(_x) {
        extendDeepAll(config, _x);
        return exports;
    };
    return exports;
};

µ.tooltipPanel.uid = 1;

µ.adapter = {};

µ.adapter.plotly = function module() {
    var exports = {};
    exports.convert = function(_inputConfig, reverse) {
        var outputConfig = {};
        if (_inputConfig.data) {
            outputConfig.data = _inputConfig.data.map(function(d, i) {
                var r = extendDeepAll({}, d);
                var toTranslate = [
                    [ r, [ 'marker', 'color' ], [ 'color' ] ],
                    [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ],
                    [ r, [ 'marker', 'line', 'color' ], [ 'strokeColor' ] ],
                    [ r, [ 'marker', 'line', 'dash' ], [ 'strokeDash' ] ],
                    [ r, [ 'marker', 'line', 'width' ], [ 'strokeSize' ] ],
                    [ r, [ 'marker', 'symbol' ], [ 'dotType' ] ],
                    [ r, [ 'marker', 'size' ], [ 'dotSize' ] ],
                    [ r, [ 'marker', 'barWidth' ], [ 'barWidth' ] ],
                    [ r, [ 'line', 'interpolation' ], [ 'lineInterpolation' ] ],
                    [ r, [ 'showlegend' ], [ 'visibleInLegend' ] ]
                ];
                toTranslate.forEach(function(d, i) {
                    µ.util.translator.apply(null, d.concat(reverse));
                });

                if (!reverse) delete r.marker;
                if (reverse) delete r.groupId;
                if (!reverse) {
                    if (r.type === 'scatter') {
                        if (r.mode === 'lines') r.geometry = 'LinePlot'; else if (r.mode === 'markers') r.geometry = 'DotPlot'; else if (r.mode === 'lines+markers') {
                            r.geometry = 'LinePlot';
                            r.dotVisible = true;
                        }
                    } else if (r.type === 'area') r.geometry = 'AreaChart'; else if (r.type === 'bar') r.geometry = 'BarChart';
                    delete r.mode;
                    delete r.type;
                } else {
                    if (r.geometry === 'LinePlot') {
                        r.type = 'scatter';
                        if (r.dotVisible === true) {
                            delete r.dotVisible;
                            r.mode = 'lines+markers';
                        } else r.mode = 'lines';
                    } else if (r.geometry === 'DotPlot') {
                        r.type = 'scatter';
                        r.mode = 'markers';
                    } else if (r.geometry === 'AreaChart') r.type = 'area'; else if (r.geometry === 'BarChart') r.type = 'bar';
                    delete r.geometry;
                }
                return r;
            });
            if (!reverse && _inputConfig.layout && _inputConfig.layout.barmode === 'stack') {
                var duplicates = µ.util.duplicates(outputConfig.data.map(function(d, i) {
                    return d.geometry;
                }));
                outputConfig.data.forEach(function(d, i) {
                    var idx = duplicates.indexOf(d.geometry);
                    if (idx != -1) outputConfig.data[i].groupId = idx;
                });
            }
        }
        if (_inputConfig.layout) {
            var r = extendDeepAll({}, _inputConfig.layout);
            var toTranslate = [
                [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ],
                [ r, [ 'showlegend' ], [ 'showLegend' ] ],
                [ r, [ 'radialaxis' ], [ 'radialAxis' ] ],
                [ r, [ 'angularaxis' ], [ 'angularAxis' ] ],
                [ r.angularaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.angularaxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
                [ r.angularaxis, [ 'nticks' ], [ 'ticksCount' ] ],
                [ r.angularaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.angularaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.angularaxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularaxis, [ 'endpadding' ], [ 'endPadding' ] ],
                [ r.radialaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.radialaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.radialaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.radialaxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.angularAxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
                [ r.angularAxis, [ 'nticks' ], [ 'ticksCount' ] ],
                [ r.angularAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.angularAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.angularAxis, [ 'range' ], [ 'domain' ] ],
                [ r.angularAxis, [ 'endpadding' ], [ 'endPadding' ] ],
                [ r.radialAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
                [ r.radialAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
                [ r.radialAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
                [ r.radialAxis, [ 'range' ], [ 'domain' ] ],
                [ r.font, [ 'outlinecolor' ], [ 'outlineColor' ] ],
                [ r.legend, [ 'traceorder' ], [ 'reverseOrder' ] ],
                [ r, [ 'labeloffset' ], [ 'labelOffset' ] ],
                [ r, [ 'defaultcolorrange' ], [ 'defaultColorRange' ] ]
            ];
            toTranslate.forEach(function(d, i) {
                µ.util.translator.apply(null, d.concat(reverse));
            });

            if (!reverse) {
                if (r.angularAxis && typeof r.angularAxis.ticklen !== 'undefined') r.tickLength = r.angularAxis.ticklen;
                if (r.angularAxis && typeof r.angularAxis.tickcolor !== 'undefined') r.tickColor = r.angularAxis.tickcolor;
            } else {
                if (typeof r.tickLength !== 'undefined') {
                    r.angularaxis.ticklen = r.tickLength;
                    delete r.tickLength;
                }
                if (r.tickColor) {
                    r.angularaxis.tickcolor = r.tickColor;
                    delete r.tickColor;
                }
            }
            if (r.legend && typeof r.legend.reverseOrder != 'boolean') {
                r.legend.reverseOrder = r.legend.reverseOrder != 'normal';
            }
            if (r.legend && typeof r.legend.traceorder == 'boolean') {
                r.legend.traceorder = r.legend.traceorder ? 'reversed' : 'normal';
                delete r.legend.reverseOrder;
            }
            if (r.margin && typeof r.margin.t != 'undefined') {
                var source = [ 't', 'r', 'b', 'l', 'pad' ];
                var target = [ 'top', 'right', 'bottom', 'left', 'pad' ];
                var margin = {};
                d3.entries(r.margin).forEach(function(dB, iB) {
                    margin[target[source.indexOf(dB.key)]] = dB.value;
                });
                r.margin = margin;
            }
            if (reverse) {
                delete r.needsEndSpacing;
                delete r.minorTickColor;
                delete r.minorTicks;
                delete r.angularaxis.ticksCount;
                delete r.angularaxis.ticksCount;
                delete r.angularaxis.ticksStep;
                delete r.angularaxis.rewriteTicks;
                delete r.angularaxis.nticks;
                delete r.radialaxis.ticksCount;
                delete r.radialaxis.ticksCount;
                delete r.radialaxis.ticksStep;
                delete r.radialaxis.rewriteTicks;
                delete r.radialaxis.nticks;
            }
            outputConfig.layout = r;
        }
        return outputConfig;
    };
    return exports;
};

},{"../../../constants/alignment":143,"../../../lib":164,"d3":6}],250:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/* eslint-disable new-cap */

'use strict';

var d3 = require('d3');
var Lib = require('../../../lib');
var Color = require('../../../components/color');

var micropolar = require('./micropolar');
var UndoManager = require('./undo_manager');
var extendDeepAll = Lib.extendDeepAll;

var manager = module.exports = {};

manager.framework = function(_gd) {
    var config, previousConfigClone, plot, convertedInput, container;
    var undoManager = new UndoManager();

    function exports(_inputConfig, _container) {
        if(_container) container = _container;
        d3.select(d3.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove();

        config = (!config) ?
            _inputConfig :
            extendDeepAll(config, _inputConfig);

        if(!plot) plot = micropolar.Axis();
        convertedInput = micropolar.adapter.plotly().convert(config);
        plot.config(convertedInput).render(container);
        _gd.data = config.data;
        _gd.layout = config.layout;
        manager.fillLayout(_gd);
        return config;
    }
    exports.isPolar = true;
    exports.svg = function() { return plot.svg(); };
    exports.getConfig = function() { return config; };
    exports.getLiveConfig = function() {
        return micropolar.adapter.plotly().convert(plot.getLiveConfig(), true);
    };
    exports.getLiveScales = function() { return {t: plot.angularScale(), r: plot.radialScale()}; };
    exports.setUndoPoint = function() {
        var that = this;
        var configClone = micropolar.util.cloneJson(config);
        (function(_configClone, _previousConfigClone) {
            undoManager.add({
                undo: function() {
                    if(_previousConfigClone) that(_previousConfigClone);
                },
                redo: function() {
                    that(_configClone);
                }
            });
        })(configClone, previousConfigClone);
        previousConfigClone = micropolar.util.cloneJson(configClone);
    };
    exports.undo = function() { undoManager.undo(); };
    exports.redo = function() { undoManager.redo(); };
    return exports;
};

manager.fillLayout = function(_gd) {
    var container = d3.select(_gd).selectAll('.plot-container'),
        paperDiv = container.selectAll('.svg-container'),
        paper = _gd.framework && _gd.framework.svg && _gd.framework.svg(),
        dflts = {
            width: 800,
            height: 600,
            paper_bgcolor: Color.background,
            _container: container,
            _paperdiv: paperDiv,
            _paper: paper
        };

    _gd._fullLayout = extendDeepAll(dflts, _gd.layout);
};

},{"../../../components/color":43,"../../../lib":164,"./micropolar":249,"./undo_manager":251,"d3":6}],251:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager
// Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com
module.exports = function UndoManager() {
    var undoCommands = [],
        index = -1,
        isExecuting = false,
        callback;

    function execute(command, action) {
        if(!command) return this;

        isExecuting = true;
        command[action]();
        isExecuting = false;

        return this;
    }

    return {
        add: function(command) {
            if(isExecuting) return this;
            undoCommands.splice(index + 1, undoCommands.length - index);
            undoCommands.push(command);
            index = undoCommands.length - 1;
            return this;
        },
        setCallback: function(callbackFunc) { callback = callbackFunc; },
        undo: function() {
            var command = undoCommands[index];
            if(!command) return this;
            execute(command, 'undo');
            index -= 1;
            if(callback) callback(command.undo);
            return this;
        },
        redo: function() {
            var command = undoCommands[index + 1];
            if(!command) return this;
            execute(command, 'redo');
            index += 1;
            if(callback) callback(command.redo);
            return this;
        },
        clear: function() {
            undoCommands = [];
            index = -1;
        },
        hasUndo: function() { return index !== -1; },
        hasRedo: function() { return index < (undoCommands.length - 1); },
        getCommands: function() { return undoCommands; },
        getPreviousCommand: function() { return undoCommands[index - 1]; },
        getIndex: function() { return index; }
    };
};

},{}],252:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

// always plot splom before cartesian (i.e. scattergl traces)
function sortModules(a, b) {
    if(a === 'splom') return -1;
    if(b === 'splom') return 1;
    return 0;
}

function sortBasePlotModules(a, b) {
    return sortModules(a.name, b.name);
}

module.exports = {
    sortBasePlotModules: sortBasePlotModules,
    sortModules: sortModules
};

},{}],253:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../lib');
var handleDomainDefaults = require('./domain').defaults;


/**
 * Find and supply defaults to all subplots of a given type
 * This handles subplots that are contained within one container - so
 * gl3d, geo, ternary... but not 2d axes which have separate x and y axes
 * finds subplots, coerces their `domain` attributes, then calls the
 * given handleDefaults function to fill in everything else.
 *
 * layoutIn: the complete user-supplied input layout
 * layoutOut: the complete finished layout
 * fullData: the finished data array, used only to find subplots
 * opts: {
 *  type: subplot type string
 *  attributes: subplot attributes object
 *  partition: 'x' or 'y', which direction to divide domain space by default
 *      (default 'x', ie side-by-side subplots)
 *      TODO: this option is only here because 3D and geo made opposite
 *      choices in this regard previously and I didn't want to change it.
 *      Instead we should do:
 *      - something consistent
 *      - something more square (4 cuts 2x2, 5/6 cuts 2x3, etc.)
 *      - something that includes all subplot types in one arrangement,
 *        now that we can have them together!
 *  handleDefaults: function of (subplotLayoutIn, subplotLayoutOut, coerce, opts)
 *      this opts object is passed through to handleDefaults, so attach any
 *      additional items needed by this function here as well
 * }
 */
module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) {
    var subplotType = opts.type;
    var subplotAttributes = opts.attributes;
    var handleDefaults = opts.handleDefaults;
    var partition = opts.partition || 'x';

    var ids = layoutOut._subplots[subplotType];
    var idsLength = ids.length;

    var subplotLayoutIn, subplotLayoutOut;

    function coerce(attr, dflt) {
        return Lib.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt);
    }

    for(var i = 0; i < idsLength; i++) {
        var id = ids[i];

        // ternary traces get a layout ternary for free!
        if(layoutIn[id]) subplotLayoutIn = layoutIn[id];
        else subplotLayoutIn = layoutIn[id] = {};

        layoutOut[id] = subplotLayoutOut = {};

        var dfltDomains = {};
        dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength];
        handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains);

        opts.id = id;
        handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts);
    }
};

},{"../lib":164,"./domain":231}],254:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Loggers = require('./lib/loggers');
var noop = require('./lib/noop');
var pushUnique = require('./lib/push_unique');
var isPlainObject = require('./lib/is_plain_object');
var ExtendModule = require('./lib/extend');

var basePlotAttributes = require('./plots/attributes');
var baseLayoutAttributes = require('./plots/layout_attributes');

var extendFlat = ExtendModule.extendFlat;
var extendDeepAll = ExtendModule.extendDeepAll;

exports.modules = {};
exports.allCategories = {};
exports.allTypes = [];
exports.subplotsRegistry = {};
exports.transformsRegistry = {};
exports.componentsRegistry = {};
exports.layoutArrayContainers = [];
exports.layoutArrayRegexes = [];
exports.traceLayoutAttributes = {};
exports.localeRegistry = {};
exports.apiMethodRegistry = {};

/**
 * Top-level register routine, exported as Plotly.register
 *
 * @param {object array or array of objects} _modules :
 *  module object or list of module object to register.
 *
 *  A valid `moduleType: 'trace'` module has fields:
 *  - name {string} : the trace type
 *  - categories {array} : categories associated with this trace type,
 *                         tested with Register.traceIs()
 *  - meta {object} : meta info (mostly for plot-schema)
 *
 *  A valid `moduleType: 'locale'` module has fields:
 *  - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
 *                    optionally with a country/region code ('en-GB', 'de-CH'). If a country
 *                    code is used but the base language locale has not yet been supplied,
 *                    we will use this locale for the base as well.
 *  - dictionary {object} : the dictionary mapping input strings to localized strings
 *                          generally the keys should be the literal input strings, but
 *                          if default translations are provided you can use any string as a key.
 *  - format {object} : a `d3.locale` format specifier for this locale
 *                      any omitted keys we'll fall back on en-US.
 *
 *  A valid `moduleType: 'transform'` module has fields:
 *  - name {string} : transform name
 *  - transform {function} : default-level transform function
 *  - calcTransform {function} : calc-level transform function
 *  - attributes {object} : transform attributes declarations
 *  - supplyDefaults {function} : attributes default-supply function
 *
 *  A valid `moduleType: 'component'` module has fields:
 *  - name {string} : the component name, used it with Register.getComponentMethod()
 *                    to employ component method.
 *
 *  A valid `moduleType: 'apiMethod'` module has fields:
 *  - name {string} : the api method name.
 *  - fn {function} : the api method called with Register.call();
 *
 */
exports.register = function register(_modules) {
    if(!_modules) {
        throw new Error('No argument passed to Plotly.register.');
    } else if(_modules && !Array.isArray(_modules)) {
        _modules = [_modules];
    }

    for(var i = 0; i < _modules.length; i++) {
        var newModule = _modules[i];

        if(!newModule) {
            throw new Error('Invalid module was attempted to be registered!');
        }

        switch(newModule.moduleType) {
            case 'trace':
                registerTraceModule(newModule);
                break;
            case 'transform':
                registerTransformModule(newModule);
                break;
            case 'component':
                registerComponentModule(newModule);
                break;
            case 'locale':
                registerLocale(newModule);
                break;
            case 'apiMethod':
                var name = newModule.name;
                exports.apiMethodRegistry[name] = newModule.fn;
                break;
            default:
                throw new Error('Invalid module was attempted to be registered!');
        }
    }
};

/**
 * Get registered module using trace object or trace type
 *
 * @param {object||string} trace
 *  trace object with prop 'type' or trace type as a string
 * @return {object}
 *  module object corresponding to trace type
 */
exports.getModule = function(trace) {
    var _module = exports.modules[getTraceType(trace)];
    if(!_module) return false;
    return _module._module;
};

/**
 * Determine if this trace type is in a given category
 *
 * @param {object||string} traceType
 *  a trace (object) or trace type (string)
 * @param {string} category
 *  category in question
 * @return {boolean}
 */
exports.traceIs = function(traceType, category) {
    traceType = getTraceType(traceType);

    // old plot.ly workspace hack, nothing to see here
    if(traceType === 'various') return false;

    var _module = exports.modules[traceType];

    if(!_module) {
        if(traceType && traceType !== 'area') {
            Loggers.log('Unrecognized trace type ' + traceType + '.');
        }

        _module = exports.modules[basePlotAttributes.type.dflt];
    }

    return !!_module.categories[category];
};

/**
 * Determine if this trace has a transform of the given type and return
 * array of matching indices.
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {array}
 *  array of matching indices. If none found, returns []
 */
exports.getTransformIndices = function(data, type) {
    var indices = [];
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            indices.push(i);
        }
    }
    return indices;
};

/**
 * Determine if this trace has a transform of the given type
 *
 * @param {object} data
 *  a trace object (member of data or fullData)
 * @param {string} type
 *  type of trace to test
 * @return {boolean}
 */
exports.hasTransform = function(data, type) {
    var transforms = data.transforms || [];
    for(var i = 0; i < transforms.length; i++) {
        if(transforms[i].type === type) {
            return true;
        }
    }
    return false;
};

/**
 * Retrieve component module method. Falls back on noop if either the
 * module or the method is missing, so the result can always be safely called
 *
 * @param {string} name
 *  name of component (as declared in component module)
 * @param {string} method
 *  name of component module method
 * @return {function}
 */
exports.getComponentMethod = function(name, method) {
    var _module = exports.componentsRegistry[name];

    if(!_module) return noop;
    return _module[method] || noop;
};

/**
 * Call registered api method.
 *
 * @param {string} name : api method name
 * @param {...array} args : arguments passed to api method
 * @return {any} : returns api method output
 */
exports.call = function() {
    var name = arguments[0];
    var args = [].slice.call(arguments, 1);
    return exports.apiMethodRegistry[name].apply(null, args);
};

function registerTraceModule(_module) {
    var thisType = _module.name;
    var categoriesIn = _module.categories;
    var meta = _module.meta;

    if(exports.modules[thisType]) {
        Loggers.log('Type ' + thisType + ' already registered');
        return;
    }

    if(!exports.subplotsRegistry[_module.basePlotModule.name]) {
        registerSubplot(_module.basePlotModule);
    }

    var categoryObj = {};
    for(var i = 0; i < categoriesIn.length; i++) {
        categoryObj[categoriesIn[i]] = true;
        exports.allCategories[categoriesIn[i]] = true;
    }

    exports.modules[thisType] = {
        _module: _module,
        categories: categoryObj
    };

    if(meta && Object.keys(meta).length) {
        exports.modules[thisType].meta = meta;
    }

    exports.allTypes.push(thisType);

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTrace(componentName, thisType);
    }

    /*
     * Collect all trace layout attributes in one place for easier lookup later
     * but don't merge them into the base schema as it would confuse the docs
     * (at least after https://github.com/plotly/documentation/issues/202 gets done!)
     */
    if(_module.layoutAttributes) {
        extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
    }
}

function registerSubplot(_module) {
    var plotType = _module.name;

    if(exports.subplotsRegistry[plotType]) {
        Loggers.log('Plot type ' + plotType + ' already registered.');
        return;
    }

    // relayout array handling will look for component module methods with this
    // name and won't find them because this is a subplot module... but that
    // should be fine, it will just fall back on redrawing the plot.
    findArrayRegexps(_module);

    // not sure what's best for the 'cartesian' type at this point
    exports.subplotsRegistry[plotType] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToSubplot(componentName, _module.name);
    }
}

function registerComponentModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Component module *name* must be a string.');
    }

    var name = _module.name;
    exports.componentsRegistry[name] = _module;

    if(_module.layoutAttributes) {
        if(_module.layoutAttributes._isLinkedToArray) {
            pushUnique(exports.layoutArrayContainers, name);
        }
        findArrayRegexps(_module);
    }

    for(var traceType in exports.modules) {
        mergeComponentAttrsToTrace(name, traceType);
    }

    for(var subplotName in exports.subplotsRegistry) {
        mergeComponentAttrsToSubplot(name, subplotName);
    }

    for(var transformType in exports.transformsRegistry) {
        mergeComponentAttrsToTransform(name, transformType);
    }

    if(_module.schema && _module.schema.layout) {
        extendDeepAll(baseLayoutAttributes, _module.schema.layout);
    }
}

function registerTransformModule(_module) {
    if(typeof _module.name !== 'string') {
        throw new Error('Transform module *name* must be a string.');
    }

    var prefix = 'Transform module ' + _module.name;
    var hasTransform = typeof _module.transform === 'function';
    var hasCalcTransform = typeof _module.calcTransform === 'function';

    if(!hasTransform && !hasCalcTransform) {
        throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
    }
    if(hasTransform && hasCalcTransform) {
        Loggers.log([
            prefix + ' has both a *transform* and *calcTransform* methods.',
            'Please note that all *transform* methods are executed',
            'before all *calcTransform* methods.'
        ].join(' '));
    }
    if(!isPlainObject(_module.attributes)) {
        Loggers.log(prefix + ' registered without an *attributes* object.');
    }
    if(typeof _module.supplyDefaults !== 'function') {
        Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
    }

    exports.transformsRegistry[_module.name] = _module;

    for(var componentName in exports.componentsRegistry) {
        mergeComponentAttrsToTransform(componentName, _module.name);
    }
}

function registerLocale(_module) {
    var locale = _module.name;
    var baseLocale = locale.split('-')[0];

    var newDict = _module.dictionary;
    var newFormat = _module.format;
    var hasDict = newDict && Object.keys(newDict).length;
    var hasFormat = newFormat && Object.keys(newFormat).length;

    var locales = exports.localeRegistry;

    var localeObj = locales[locale];
    if(!localeObj) locales[locale] = localeObj = {};

    // Should we use this dict for the base locale?
    // In case we're overwriting a previous dict for this locale, check
    // whether the base matches the full locale dict now. If we're not
    // overwriting, locales[locale] is undefined so this just checks if
    // baseLocale already had a dict or not.
    // Same logic for dateFormats
    if(baseLocale !== locale) {
        var baseLocaleObj = locales[baseLocale];
        if(!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};

        if(hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
            baseLocaleObj.dictionary = newDict;
        }
        if(hasFormat && baseLocaleObj.format === localeObj.format) {
            baseLocaleObj.format = newFormat;
        }
    }

    if(hasDict) localeObj.dictionary = newDict;
    if(hasFormat) localeObj.format = newFormat;
}

function findArrayRegexps(_module) {
    if(_module.layoutAttributes) {
        var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
        if(arrayAttrRegexps) {
            for(var i = 0; i < arrayAttrRegexps.length; i++) {
                pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
            }
        }
    }
}

function mergeComponentAttrsToTrace(componentName, traceType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.traces) return;

    var traceAttrs = componentSchema.traces[traceType];
    if(traceAttrs) {
        extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
    }
}

function mergeComponentAttrsToTransform(componentName, transformType) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.transforms) return;

    var transformAttrs = componentSchema.transforms[transformType];
    if(transformAttrs) {
        extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
    }
}

function mergeComponentAttrsToSubplot(componentName, subplotName) {
    var componentSchema = exports.componentsRegistry[componentName].schema;
    if(!componentSchema || !componentSchema.subplots) return;

    var subplotModule = exports.subplotsRegistry[subplotName];
    var subplotAttrs = subplotModule.layoutAttributes;
    var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
    if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];

    var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
    if(subplotAttrs && componentLayoutAttrs) {
        extendDeepAll(subplotAttrs, componentLayoutAttrs);
    }
}

function getTraceType(traceType) {
    if(typeof traceType === 'object') traceType = traceType.type;
    return traceType;
}

},{"./lib/extend":157,"./lib/is_plain_object":166,"./lib/loggers":169,"./lib/noop":173,"./lib/push_unique":177,"./plots/attributes":203,"./plots/layout_attributes":236}],255:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../lib');

var extendFlat = Lib.extendFlat;
var extendDeep = Lib.extendDeep;

// Put default plotTile layouts here
function cloneLayoutOverride(tileClass) {
    var override;

    switch(tileClass) {
        case 'themes__thumb':
            override = {
                autosize: true,
                width: 150,
                height: 150,
                title: '',
                showlegend: false,
                margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},
                annotations: []
            };
            break;

        case 'thumbnail':
            override = {
                title: '',
                hidesources: true,
                showlegend: false,
                borderwidth: 0,
                bordercolor: '',
                margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},
                annotations: []
            };
            break;

        default:
            override = {};
    }


    return override;
}

function keyIsAxis(keyName) {
    var types = ['xaxis', 'yaxis', 'zaxis'];
    return (types.indexOf(keyName.slice(0, 5)) > -1);
}


module.exports = function clonePlot(graphObj, options) {

    // Polar plot compatibility
    if(graphObj.framework && graphObj.framework.isPolar) {
        graphObj = graphObj.framework.getConfig();
    }

    var i;
    var oldData = graphObj.data;
    var oldLayout = graphObj.layout;
    var newData = extendDeep([], oldData);
    var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
    var context = graphObj._context || {};

    if(options.width) newLayout.width = options.width;
    if(options.height) newLayout.height = options.height;

    if(options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
        // kill annotations
        newLayout.annotations = [];
        var keys = Object.keys(newLayout);

        for(i = 0; i < keys.length; i++) {
            if(keyIsAxis(keys[i])) {
                newLayout[keys[i]].title = '';
            }
        }

        // kill colorbar and pie labels
        for(i = 0; i < newData.length; i++) {
            var trace = newData[i];
            trace.showscale = false;
            if(trace.marker) trace.marker.showscale = false;
            if(trace.type === 'pie') trace.textposition = 'none';
        }
    }

    if(Array.isArray(options.annotations)) {
        for(i = 0; i < options.annotations.length; i++) {
            newLayout.annotations.push(options.annotations[i]);
        }
    }

    // TODO: does this scene modification really belong here?
    // If we still need it, can it move into the gl3d module?
    var sceneIds = Object.keys(newLayout).filter(function(key) {
        return key.match(/^scene\d*$/);
    });
    if(sceneIds.length) {
        var axesImageOverride = {};
        if(options.tileClass === 'thumbnail') {
            axesImageOverride = {
                title: '',
                showaxeslabels: false,
                showticklabels: false,
                linetickenable: false
            };
        }
        for(i = 0; i < sceneIds.length; i++) {
            var scene = newLayout[sceneIds[i]];

            if(!scene.xaxis) {
                scene.xaxis = {};
            }

            if(!scene.yaxis) {
                scene.yaxis = {};
            }

            if(!scene.zaxis) {
                scene.zaxis = {};
            }

            extendFlat(scene.xaxis, axesImageOverride);
            extendFlat(scene.yaxis, axesImageOverride);
            extendFlat(scene.zaxis, axesImageOverride);

            // TODO what does this do?
            scene._scene = null;
        }
    }

    var gd = document.createElement('div');
    if(options.tileClass) gd.className = options.tileClass;

    var plotTile = {
        gd: gd,
        td: gd, // for external (image server) compatibility
        layout: newLayout,
        data: newData,
        config: {
            staticPlot: (options.staticPlot === undefined) ?
                true :
                options.staticPlot,
            plotGlPixelRatio: (options.plotGlPixelRatio === undefined) ?
                2 :
                options.plotGlPixelRatio,
            displaylogo: options.displaylogo || false,
            showLink: options.showLink || false,
            showTips: options.showTips || false,
            mapboxAccessToken: context.mapboxAccessToken
        }
    };

    if(options.setBackground !== 'transparent') {
        plotTile.config.setBackground = options.setBackground || 'opaque';
    }

    // attaching the default Layout the gd, so you can grab it later
    plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);

    return plotTile;
};

},{"../lib":164}],256:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var toImage = require('../plot_api/to_image');
var Lib = require('../lib'); // for isIE
var fileSaver = require('./filesaver');

/**
 * @param {object} gd figure Object
 * @param {object} opts option object
 * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
 * @param opts.width width of snapshot in px
 * @param opts.height height of snapshot in px
 * @param opts.filename name of file excluding extension
 */
function downloadImage(gd, opts) {

    // check for undefined opts
    opts = opts || {};

    // default to png
    opts.format = opts.format || 'png';

    return new Promise(function(resolve, reject) {
        if(gd._snapshotInProgress) {
            reject(new Error('Snapshotting already in progress.'));
        }

        // see comments within svgtoimg for additional
        //   discussion of problems with IE
        //   can now draw to canvas, but CORS tainted canvas
        //   does not allow toDataURL
        //   svg format will work though
        if(Lib.isIE() && opts.format !== 'svg') {
            reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'));
        }

        gd._snapshotInProgress = true;
        var promise = toImage(gd, opts);

        var filename = opts.filename || gd.fn || 'newplot';
        filename += '.' + opts.format;

        promise.then(function(result) {
            gd._snapshotInProgress = false;
            return fileSaver(result, filename);
        }).then(function(name) {
            resolve(name);
        }).catch(function(err) {
            gd._snapshotInProgress = false;
            reject(err);
        });
    });
}

module.exports = downloadImage;

},{"../lib":164,"../plot_api/to_image":199,"./filesaver":257}],257:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/*
* substantial portions of this code from FileSaver.js
* https://github.com/eligrey/FileSaver.js
* License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20160328
*
* By Eli Grey, http://eligrey.com
* License: MIT
*   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/

'use strict';

var fileSaver = function(url, name) {
    var saveLink = document.createElement('a');
    var canUseSaveLink = 'download' in saveLink;
    var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
    var promise = new Promise(function(resolve, reject) {
        // IE <10 is explicitly unsupported
        if(typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) {
            reject(new Error('IE < 10 unsupported'));
        }

        // First try a.download, then web filesystem, then object URLs
        if(isSafari) {
            // Safari doesn't allow downloading of blob urls
            document.location.href = 'data:application/octet-stream' + url.slice(url.search(/[,;]/));
            resolve(name);
        }

        if(!name) {
            name = 'download';
        }

        if(canUseSaveLink) {
            saveLink.href = url;
            saveLink.download = name;
            document.body.appendChild(saveLink);
            saveLink.click();
            document.body.removeChild(saveLink);
            resolve(name);
        }

        // IE 10+ (native saveAs)
        if(typeof navigator !== 'undefined' && navigator.msSaveBlob) {
            // At this point we are only dealing with a SVG encoded as
            // a data URL (since IE only supports SVG)
            var encoded = url.split(/^data:image\/svg\+xml,/)[1];
            var svg = decodeURIComponent(encoded);
            navigator.msSaveBlob(new Blob([svg]), name);
            resolve(name);
        }

        reject(new Error('download error'));
    });

    return promise;
};

module.exports = fileSaver;

},{}],258:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

exports.getDelay = function(fullLayout) {
    if(!fullLayout._has) return 0;

    return (
        fullLayout._has('gl3d') ||
        fullLayout._has('gl2d') ||
        fullLayout._has('mapbox')
    ) ? 500 : 0;
};

exports.getRedrawFunc = function(gd) {
    var fullLayout = gd._fullLayout || {};
    var hasPolar = fullLayout._has && fullLayout._has('polar');
    var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r;

    // do not work for legacy polar
    if(hasLegacyPolar) return;

    return function() {
        (gd.calcdata || []).forEach(function(d) {
            if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
        });
    };
};

},{}],259:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var helpers = require('./helpers');

var Snapshot = {
    getDelay: helpers.getDelay,
    getRedrawFunc: helpers.getRedrawFunc,
    clone: require('./cloneplot'),
    toSVG: require('./tosvg'),
    svgToImg: require('./svgtoimg'),
    toImage: require('./toimage'),
    downloadImage: require('./download')
};

module.exports = Snapshot;

},{"./cloneplot":255,"./download":256,"./helpers":258,"./svgtoimg":260,"./toimage":261,"./tosvg":262}],260:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../lib');
var EventEmitter = require('events').EventEmitter;

function svgToImg(opts) {
    var ev = opts.emitter || new EventEmitter();

    var promise = new Promise(function(resolve, reject) {
        var Image = window.Image;
        var svg = opts.svg;
        var format = opts.format || 'png';

        // IE only support svg
        if(Lib.isIE() && format !== 'svg') {
            var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.');
            reject(ieSvgError);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                return ev.emit('error', ieSvgError);
            } else {
                return promise;
            }
        }

        var canvas = opts.canvas;
        var scale = opts.scale || 1;
        var w0 = opts.width || 300;
        var h0 = opts.height || 150;
        var w1 = scale * w0;
        var h1 = scale * h0;

        var ctx = canvas.getContext('2d');
        var img = new Image();

        // for Safari support, eliminate createObjectURL
        //  this decision could cause problems if content
        //  is not restricted to svg
        var url = 'data:image/svg+xml,' + encodeURIComponent(svg);

        canvas.width = w1;
        canvas.height = h1;

        img.onload = function() {
            var imgData;

            // don't need to draw to canvas if svg
            //  save some time and also avoid failure on IE
            if(format !== 'svg') {
                ctx.drawImage(img, 0, 0, w1, h1);
            }

            switch(format) {
                case 'jpeg':
                    imgData = canvas.toDataURL('image/jpeg');
                    break;
                case 'png':
                    imgData = canvas.toDataURL('image/png');
                    break;
                case 'webp':
                    imgData = canvas.toDataURL('image/webp');
                    break;
                case 'svg':
                    imgData = url;
                    break;
                default:
                    var errorMsg = 'Image format is not jpeg, png, svg or webp.';
                    reject(new Error(errorMsg));
                    // eventually remove the ev
                    //  in favor of promises
                    if(!opts.promise) {
                        return ev.emit('error', errorMsg);
                    }
            }
            resolve(imgData);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                ev.emit('success', imgData);
            }
        };

        img.onerror = function(err) {
            reject(err);
            // eventually remove the ev
            //  in favor of promises
            if(!opts.promise) {
                return ev.emit('error', err);
            }
        };

        img.src = url;
    });

    // temporary for backward compatibility
    //  move to only Promise in 2.0.0
    //  and eliminate the EventEmitter
    if(opts.promise) {
        return promise;
    }

    return ev;
}

module.exports = svgToImg;

},{"../lib":164,"events":8}],261:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var EventEmitter = require('events').EventEmitter;

var Registry = require('../registry');
var Lib = require('../lib');

var helpers = require('./helpers');
var clonePlot = require('./cloneplot');
var toSVG = require('./tosvg');
var svgToImg = require('./svgtoimg');

/**
 * @param {object} gd figure Object
 * @param {object} opts option object
 * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
 */
function toImage(gd, opts) {

    // first clone the GD so we can operate in a clean environment
    var ev = new EventEmitter();

    var clone = clonePlot(gd, {format: 'png'});
    var clonedGd = clone.gd;

    // put the cloned div somewhere off screen before attaching to DOM
    clonedGd.style.position = 'absolute';
    clonedGd.style.left = '-5000px';
    document.body.appendChild(clonedGd);

    function wait() {
        var delay = helpers.getDelay(clonedGd._fullLayout);

        setTimeout(function() {
            var svg = toSVG(clonedGd);

            var canvas = document.createElement('canvas');
            canvas.id = Lib.randstr();

            ev = svgToImg({
                format: opts.format,
                width: clonedGd._fullLayout.width,
                height: clonedGd._fullLayout.height,
                canvas: canvas,
                emitter: ev,
                svg: svg
            });

            ev.clean = function() {
                if(clonedGd) document.body.removeChild(clonedGd);
            };

        }, delay);
    }

    var redrawFunc = helpers.getRedrawFunc(clonedGd);

    Registry.call('plot', clonedGd, clone.data, clone.layout, clone.config)
        .then(redrawFunc)
        .then(wait)
        .catch(function(err) {
            ev.emit('error', err);
        });


    return ev;
}

module.exports = toImage;

},{"../lib":164,"../registry":254,"./cloneplot":255,"./helpers":258,"./svgtoimg":260,"./tosvg":262,"events":8}],262:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Lib = require('../lib');
var Drawing = require('../components/drawing');
var Color = require('../components/color');

var xmlnsNamespaces = require('../constants/xmlns_namespaces');
var DOUBLEQUOTE_REGEX = /"/g;
var DUMMY_SUB = 'TOBESTRIPPED';
var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g');

function htmlEntityDecode(s) {
    var hiddenDiv = d3.select('body').append('div').style({display: 'none'}).html('');
    var replaced = s.replace(/(&[^;]*;)/gi, function(d) {
        if(d === '&lt;') { return '&#60;'; } // special handling for brackets
        if(d === '&rt;') { return '&#62;'; }
        if(d.indexOf('<') !== -1 || d.indexOf('>') !== -1) { return ''; }
        return hiddenDiv.html(d).text(); // everything else, let the browser decode it to unicode
    });
    hiddenDiv.remove();
    return replaced;
}

function xmlEntityEncode(str) {
    return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&amp;');
}

module.exports = function toSVG(gd, format, scale) {
    var fullLayout = gd._fullLayout;
    var svg = fullLayout._paper;
    var toppaper = fullLayout._toppaper;
    var width = fullLayout.width;
    var height = fullLayout.height;
    var i;

    // make background color a rect in the svg, then revert after scraping
    // all other alterations have been dealt with by properly preparing the svg
    // in the first place... like setting cursors with css classes so we don't
    // have to remove them, and providing the right namespaces in the svg to
    // begin with
    svg.insert('rect', ':first-child')
        .call(Drawing.setRect, 0, 0, width, height)
        .call(Color.fill, fullLayout.paper_bgcolor);

    // subplot-specific to-SVG methods
    // which notably add the contents of the gl-container
    // into the main svg node
    var basePlotModules = fullLayout._basePlotModules || [];
    for(i = 0; i < basePlotModules.length; i++) {
        var _module = basePlotModules[i];

        if(_module.toSVG) _module.toSVG(gd);
    }

    // add top items above them assumes everything in toppaper is either
    // a group or a defs, and if it's empty (like hoverlayer) we can ignore it.
    if(toppaper) {
        var nodes = toppaper.node().childNodes;

        // make copy of nodes as childNodes prop gets mutated in loop below
        var topGroups = Array.prototype.slice.call(nodes);

        for(i = 0; i < topGroups.length; i++) {
            var topGroup = topGroups[i];

            if(topGroup.childNodes.length) svg.node().appendChild(topGroup);
        }
    }

    // remove draglayer for Adobe Illustrator compatibility
    if(fullLayout._draggers) {
        fullLayout._draggers.remove();
    }

    // in case the svg element had an explicit background color, remove this
    // we want the rect to get the color so it's the right size; svg bg will
    // fill whatever container it's displayed in regardless of plot size.
    svg.node().style.background = '';

    svg.selectAll('text')
        .attr({'data-unformatted': null, 'data-math': null})
        .each(function() {
            var txt = d3.select(this);

            // hidden text is pre-formatting mathjax, the browser ignores it
            // but in a static plot it's useless and it can confuse batik
            // we've tried to standardize on display:none but make sure we still
            // catch visibility:hidden if it ever arises
            if(this.style.visibility === 'hidden' || this.style.display === 'none') {
                txt.remove();
                return;
            }
            else {
                // clear other visibility/display values to default
                // to not potentially confuse non-browser SVG implementations
                txt.style({visibility: null, display: null});
            }

            // Font family styles break things because of quotation marks,
            // so we must remove them *after* the SVG DOM has been serialized
            // to a string (browsers convert singles back)
            var ff = this.style.fontFamily;
            if(ff && ff.indexOf('"') !== -1) {
                txt.style('font-family', ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
            }
        });

    svg.selectAll('.point,.scatterpts').each(function() {
        var pt = d3.select(this);
        var fill = this.style.fill;

        // similar to font family styles above,
        // we must remove " after the SVG DOM has been serialized
        if(fill && fill.indexOf('url(') !== -1) {
            pt.style('fill', fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
        }
    });

    if(format === 'pdf' || format === 'eps') {
        // these formats make the extra line MathJax adds around symbols look super thick in some cases
        // it looks better if this is removed entirely.
        svg.selectAll('#MathJax_SVG_glyphs path')
            .attr('stroke-width', 0);
    }

    // fix for IE namespacing quirk?
    // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie
    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns', xmlnsNamespaces.svg);
    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns:xlink', xmlnsNamespaces.xlink);

    if(format === 'svg' && scale) {
        svg.attr('width', scale * width);
        svg.attr('height', scale * height);
        svg.attr('viewBox', '0 0 ' + width + ' ' + height);
    }

    var s = new window.XMLSerializer().serializeToString(svg.node());
    s = htmlEntityDecode(s);
    s = xmlEntityEncode(s);

    // Fix quotations around font strings and gradient URLs
    s = s.replace(DUMMY_REGEX, '\'');

    // IE is very strict, so we will need to clean
    //  svg with the following regex
    //  yes this is messy, but do not know a better way
    // Even with this IE will not work due to tainted canvas
    //  see https://github.com/kangax/fabric.js/issues/1957
    //      http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10
    // Leave here just in case the CORS/tainted IE issue gets resolved
    if(Lib.isIE()) {
        // replace double quote with single quote
        s = s.replace(/"/gi, '\'');
        // url in svg are single quoted
        //   since we changed double to single
        //   we'll need to change these to double-quoted
        s = s.replace(/(\('#)([^']*)('\))/gi, '(\"#$2\")');
        // font names with spaces will be escaped single-quoted
        //   we'll need to change these to double-quoted
        s = s.replace(/(\\')/gi, '\"');
    }

    return s;
};

},{"../components/color":43,"../components/drawing":68,"../constants/xmlns_namespaces":147,"../lib":164,"d3":6}],263:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');

exports.formatPiePercent = function formatPiePercent(v, separators) {
    var vRounded = (v * 100).toPrecision(3);
    if(vRounded.lastIndexOf('.') !== -1) {
        vRounded = vRounded.replace(/[.]?0+$/, '');
    }
    return Lib.numSeparate(vRounded, separators) + '%';
};

exports.formatPieValue = function formatPieValue(v, separators) {
    var vRounded = v.toPrecision(10);
    if(vRounded.lastIndexOf('.') !== -1) {
        vRounded = vRounded.replace(/[.]?0+$/, '');
    }
    return Lib.numSeparate(vRounded, separators);
};

exports.getFirstFilled = function getFirstFilled(array, indices) {
    if(!Array.isArray(array)) return;
    for(var i = 0; i < indices.length; i++) {
        var v = array[indices[i]];
        if(v || v === 0) return v;
    }
};

exports.castOption = function castOption(item, indices) {
    if(Array.isArray(item)) return exports.getFirstFilled(item, indices);
    else if(item) return item;
};

},{"../../lib":164}],264:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Color = require('../../components/color');
var castOption = require('./helpers').castOption;

module.exports = function styleOne(s, pt, trace) {
    var line = trace.marker.line;
    var lineColor = castOption(line.color, pt.pts) || Color.defaultLine;
    var lineWidth = castOption(line.width, pt.pts) || 0;

    s.style({'stroke-width': lineWidth})
        .call(Color.fill, pt.color)
        .call(Color.stroke, lineColor);
};

},{"../../components/color":43,"./helpers":263}],265:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');


// arrayOk attributes, merge them into calcdata array
module.exports = function arraysToCalcdata(cd, trace) {

    // so each point knows which index it originally came from
    for(var i = 0; i < cd.length; i++) cd[i].i = i;

    Lib.mergeArray(trace.text, cd, 'tx');
    Lib.mergeArray(trace.hovertext, cd, 'htx');
    Lib.mergeArray(trace.customdata, cd, 'data');
    Lib.mergeArray(trace.textposition, cd, 'tp');
    if(trace.textfont) {
        Lib.mergeArray(trace.textfont.size, cd, 'ts');
        Lib.mergeArray(trace.textfont.color, cd, 'tc');
        Lib.mergeArray(trace.textfont.family, cd, 'tf');
    }

    var marker = trace.marker;
    if(marker) {
        Lib.mergeArray(marker.size, cd, 'ms');
        Lib.mergeArray(marker.opacity, cd, 'mo');
        Lib.mergeArray(marker.symbol, cd, 'mx');
        Lib.mergeArray(marker.color, cd, 'mc');

        var markerLine = marker.line;
        if(marker.line) {
            Lib.mergeArray(markerLine.color, cd, 'mlc');
            Lib.mergeArray(markerLine.width, cd, 'mlw');
        }

        var markerGradient = marker.gradient;
        if(markerGradient && markerGradient.type !== 'none') {
            Lib.mergeArray(markerGradient.type, cd, 'mgt');
            Lib.mergeArray(markerGradient.color, cd, 'mgc');
        }
    }
};

},{"../../lib":164}],266:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var colorAttributes = require('../../components/colorscale/color_attributes');
var colorbarAttrs = require('../../components/colorbar/attributes');
var fontAttrs = require('../../plots/font_attributes');
var dash = require('../../components/drawing/attributes').dash;

var Drawing = require('../../components/drawing');
var constants = require('./constants');
var extendFlat = require('../../lib/extend').extendFlat;

module.exports = {
    x: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    x0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        
    },
    dx: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    y: {
        valType: 'data_array',
        editType: 'calc+clearAxisTypes',
        
    },
    y0: {
        valType: 'any',
        dflt: 0,
        
        editType: 'calc+clearAxisTypes',
        
    },
    dy: {
        valType: 'number',
        dflt: 1,
        
        editType: 'calc',
        
    },
    text: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'calc',
        
    },
    hovertext: {
        valType: 'string',
        
        dflt: '',
        arrayOk: true,
        editType: 'style',
        
    },
    mode: {
        valType: 'flaglist',
        flags: ['lines', 'markers', 'text'],
        extras: ['none'],
        
        editType: 'calc',
        
    },
    hoveron: {
        valType: 'flaglist',
        flags: ['points', 'fills'],
        
        editType: 'style',
        
    },
    line: {
        color: {
            valType: 'color',
            
            editType: 'style',
            
        },
        width: {
            valType: 'number',
            min: 0,
            dflt: 2,
            
            editType: 'style',
            
        },
        shape: {
            valType: 'enumerated',
            values: ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv'],
            dflt: 'linear',
            
            editType: 'plot',
            
        },
        smoothing: {
            valType: 'number',
            min: 0,
            max: 1.3,
            dflt: 1,
            
            editType: 'plot',
            
        },
        dash: extendFlat({}, dash, {editType: 'style'}),
        simplify: {
            valType: 'boolean',
            dflt: true,
            
            editType: 'plot',
            
        },
        editType: 'plot'
    },

    connectgaps: {
        valType: 'boolean',
        dflt: false,
        
        editType: 'calc',
        
    },
    cliponaxis: {
        valType: 'boolean',
        dflt: true,
        
        editType: 'plot',
        
    },

    fill: {
        valType: 'enumerated',
        values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'],
        dflt: 'none',
        
        editType: 'calc',
        
    },
    fillcolor: {
        valType: 'color',
        
        editType: 'style',
        
    },
    marker: extendFlat({
        symbol: {
            valType: 'enumerated',
            values: Drawing.symbolList,
            dflt: 'circle',
            arrayOk: true,
            
            editType: 'style',
            
        },
        opacity: {
            valType: 'number',
            min: 0,
            max: 1,
            arrayOk: true,
            
            editType: 'style',
            
        },
        size: {
            valType: 'number',
            min: 0,
            dflt: 6,
            arrayOk: true,
            
            editType: 'calcIfAutorange',
            
        },
        maxdisplayed: {
            valType: 'number',
            min: 0,
            dflt: 0,
            
            editType: 'plot',
            
        },
        sizeref: {
            valType: 'number',
            dflt: 1,
            
            editType: 'calc',
            
        },
        sizemin: {
            valType: 'number',
            min: 0,
            dflt: 0,
            
            editType: 'calc',
            
        },
        sizemode: {
            valType: 'enumerated',
            values: ['diameter', 'area'],
            dflt: 'diameter',
            
            editType: 'calc',
            
        },

        showscale: {
            valType: 'boolean',
            
            dflt: false,
            editType: 'calc',
            
        },
        colorbar: colorbarAttrs,

        line: extendFlat({
            width: {
                valType: 'number',
                min: 0,
                arrayOk: true,
                
                editType: 'style',
                
            },
            editType: 'calc'
        },
            colorAttributes('marker.line')
        ),
        gradient: {
            type: {
                valType: 'enumerated',
                values: ['radial', 'horizontal', 'vertical', 'none'],
                arrayOk: true,
                dflt: 'none',
                
                editType: 'calc',
                
            },
            color: {
                valType: 'color',
                arrayOk: true,
                
                editType: 'calc',
                
            },
            editType: 'calc'
        },
        editType: 'calc'
    },
        colorAttributes('marker')
    ),
    selected: {
        marker: {
            opacity: {
                valType: 'number',
                min: 0,
                max: 1,
                
                editType: 'style',
                
            },
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            size: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        textfont: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'style'
    },
    unselected: {
        marker: {
            opacity: {
                valType: 'number',
                min: 0,
                max: 1,
                
                editType: 'style',
                
            },
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            size: {
                valType: 'number',
                min: 0,
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        textfont: {
            color: {
                valType: 'color',
                
                editType: 'style',
                
            },
            editType: 'style'
        },
        editType: 'style'
    },

    textposition: {
        valType: 'enumerated',
        values: [
            'top left', 'top center', 'top right',
            'middle left', 'middle center', 'middle right',
            'bottom left', 'bottom center', 'bottom right'
        ],
        dflt: 'middle center',
        arrayOk: true,
        
        editType: 'calc',
        
    },
    textfont: fontAttrs({
        editType: 'calc',
        colorEditType: 'style',
        arrayOk: true,
        
    }),

    r: {
        valType: 'data_array',
        editType: 'calc',
        
    },
    t: {
        valType: 'data_array',
        editType: 'calc',
        
    }
};

},{"../../components/colorbar/attributes":44,"../../components/colorscale/color_attributes":51,"../../components/drawing":68,"../../components/drawing/attributes":67,"../../lib/extend":157,"../../plots/font_attributes":232,"./constants":272}],267:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');
var isArrayOrTypedArray = require('../../lib').isArrayOrTypedArray;

var Axes = require('../../plots/cartesian/axes');
var BADNUM = require('../../constants/numerical').BADNUM;

var subTypes = require('./subtypes');
var calcColorscale = require('./colorscale_calc');
var arraysToCalcdata = require('./arrays_to_calcdata');
var calcSelection = require('./calc_selection');

function calc(gd, trace) {
    var xa = Axes.getFromId(gd, trace.xaxis || 'x');
    var ya = Axes.getFromId(gd, trace.yaxis || 'y');
    var x = xa.makeCalcdata(trace, 'x');
    var y = ya.makeCalcdata(trace, 'y');
    var serieslen = trace._length;
    var cd = new Array(serieslen);

    var ppad = calcMarkerSize(trace, serieslen);
    calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);

    for(var i = 0; i < serieslen; i++) {
        cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ?
            {x: x[i], y: y[i]} :
            {x: BADNUM, y: BADNUM};

        if(trace.ids) {
            cd[i].id = String(trace.ids[i]);
        }
    }

    arraysToCalcdata(cd, trace);
    calcColorscale(trace);
    calcSelection(cd, trace);

    gd.firstscatter = false;
    return cd;
}

function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) {
    var serieslen = trace._length;

    // cancel minimum tick spacings (only applies to bars and boxes)
    xa._minDtick = 0;
    ya._minDtick = 0;

    // check whether bounds should be tight, padded, extended to zero...
    // most cases both should be padded on both ends, so start with that.
    var xOptions = {padded: true};
    var yOptions = {padded: true};

    if(ppad) {
        xOptions.ppad = yOptions.ppad = ppad;
    }

    // TODO: text size

    // include zero (tight) and extremes (padded) if fill to zero
    // (unless the shape is closed, then it's just filling the shape regardless)
    if(((trace.fill === 'tozerox') ||
            ((trace.fill === 'tonextx') && gd.firstscatter)) &&
            ((x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]))) {
        xOptions.tozero = true;
    }

    // if no error bars, markers or text, or fill to y=0 remove x padding
    else if(!(trace.error_y || {}).visible && (
            ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 ||
            (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace))
        )) {
        xOptions.padded = false;
        xOptions.ppad = 0;
    }

    // now check for y - rather different logic, though still mostly padded both ends
    // include zero (tight) and extremes (padded) if fill to zero
    // (unless the shape is closed, then it's just filling the shape regardless)
    if(((trace.fill === 'tozeroy') || ((trace.fill === 'tonexty') && gd.firstscatter)) &&
            ((x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]))) {
        yOptions.tozero = true;
    }

    // tight y: any x fill
    else if(['tonextx', 'tozerox'].indexOf(trace.fill) !== -1) {
        yOptions.padded = false;
    }

    Axes.expand(xa, x, xOptions);
    Axes.expand(ya, y, yOptions);
}

function calcMarkerSize(trace, serieslen) {
    if(!subTypes.hasMarkers(trace)) return;

    // Treat size like x or y arrays --- Run d2c
    // this needs to go before ppad computation
    var marker = trace.marker;
    var sizeref = 1.6 * (trace.marker.sizeref || 1);
    var markerTrans;

    if(trace.marker.sizemode === 'area') {
        markerTrans = function(v) {
            return Math.max(Math.sqrt((v || 0) / sizeref), 3);
        };
    } else {
        markerTrans = function(v) {
            return Math.max((v || 0) / sizeref, 3);
        };
    }

    if(isArrayOrTypedArray(marker.size)) {
        // I tried auto-type but category and dates dont make much sense.
        var ax = {type: 'linear'};
        Axes.setConvert(ax);

        var s = ax.makeCalcdata(trace.marker, 'size');

        var sizeOut = new Array(serieslen);
        for(var i = 0; i < serieslen; i++) {
            sizeOut[i] = markerTrans(s[i]);
        }
        return sizeOut;

    } else {
        return markerTrans(marker.size);
    }
}

module.exports = {
    calc: calc,
    calcMarkerSize: calcMarkerSize,
    calcAxisExpansion: calcAxisExpansion
};

},{"../../constants/numerical":145,"../../lib":164,"../../plots/cartesian/axes":206,"./arrays_to_calcdata":265,"./calc_selection":268,"./colorscale_calc":271,"./subtypes":288,"fast-isnumeric":9}],268:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');

module.exports = function calcSelection(cd, trace) {
    if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
        Lib.tagSelected(cd, trace);
    }
};

},{"../../lib":164}],269:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// remove opacity for any trace that has a fill or is filled to
module.exports = function cleanData(fullData) {
    for(var i = 0; i < fullData.length; i++) {
        var tracei = fullData[i];
        if(tracei.type !== 'scatter') continue;

        var filli = tracei.fill;
        if(filli === 'none' || filli === 'toself') continue;

        tracei.opacity = undefined;

        if(filli === 'tonexty' || filli === 'tonextx') {
            for(var j = i - 1; j >= 0; j--) {
                var tracej = fullData[j];

                if((tracej.type === 'scatter') &&
                        (tracej.xaxis === tracei.xaxis) &&
                        (tracej.yaxis === tracei.yaxis)) {
                    tracej.opacity = undefined;
                    break;
                }
            }
        }
    }
};

},{}],270:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');
var Plots = require('../../plots/plots');
var Colorscale = require('../../components/colorscale');
var drawColorbar = require('../../components/colorbar/draw');


module.exports = function colorbar(gd, cd) {
    var trace = cd[0].trace,
        marker = trace.marker,
        cbId = 'cb' + trace.uid;

    gd._fullLayout._infolayer.selectAll('.' + cbId).remove();

    // TODO make Colorbar.draw support multiple colorbar per trace

    if((marker === undefined) || !marker.showscale) {
        Plots.autoMargin(gd, cbId);
        return;
    }

    var vals = marker.color,
        cmin = marker.cmin,
        cmax = marker.cmax;

    if(!isNumeric(cmin)) cmin = Lib.aggNums(Math.min, null, vals);
    if(!isNumeric(cmax)) cmax = Lib.aggNums(Math.max, null, vals);

    var cb = cd[0].t.cb = drawColorbar(gd, cbId);
    var sclFunc = Colorscale.makeColorScaleFunc(
        Colorscale.extractScale(
            marker.colorscale,
            cmin,
            cmax
        ),
        { noNumericCheck: true }
    );

    cb.fillcolor(sclFunc)
        .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254})
        .options(marker.colorbar)();
};

},{"../../components/colorbar/draw":47,"../../components/colorscale":58,"../../lib":164,"../../plots/plots":245,"fast-isnumeric":9}],271:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var hasColorscale = require('../../components/colorscale/has_colorscale');
var calcColorscale = require('../../components/colorscale/calc');

var subTypes = require('./subtypes');


module.exports = function calcMarkerColorscale(trace) {
    if(subTypes.hasLines(trace) && hasColorscale(trace, 'line')) {
        calcColorscale(trace, trace.line.color, 'line', 'c');
    }

    if(subTypes.hasMarkers(trace)) {
        if(hasColorscale(trace, 'marker')) {
            calcColorscale(trace, trace.marker.color, 'marker', 'c');
        }
        if(hasColorscale(trace, 'marker.line')) {
            calcColorscale(trace, trace.marker.line.color, 'marker.line', 'c');
        }
    }
};

},{"../../components/colorscale/calc":50,"../../components/colorscale/has_colorscale":57,"./subtypes":288}],272:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

module.exports = {
    PTS_LINESONLY: 20,

    // fixed parameters of clustering and clipping algorithms

    // fraction of clustering tolerance "so close we don't even consider it a new point"
    minTolerance: 0.2,
    // how fast does clustering tolerance increase as you get away from the visible region
    toleranceGrowth: 10,

    // number of viewport sizes away from the visible region
    // at which we clip all lines to the perimeter
    maxScreensAway: 20
};

},{}],273:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Registry = require('../../registry');

var attributes = require('./attributes');
var constants = require('./constants');
var subTypes = require('./subtypes');
var handleXYDefaults = require('./xy_defaults');
var handleMarkerDefaults = require('./marker_defaults');
var handleLineDefaults = require('./line_defaults');
var handleLineShapeDefaults = require('./line_shape_defaults');
var handleTextDefaults = require('./text_defaults');
var handleFillColorDefaults = require('./fillcolor_defaults');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleXYDefaults(traceIn, traceOut, layout, coerce),
        // TODO: default mode by orphan points...
        defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('mode', defaultMode);

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
        handleLineShapeDefaults(traceIn, traceOut, coerce);
        coerce('connectgaps');
        coerce('line.simplify');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce);
    }

    var dfltHoverOn = [];

    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
        coerce('cliponaxis');
        coerce('marker.maxdisplayed');
        dfltHoverOn.push('points');
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
        if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
    }

    if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
        dfltHoverOn.push('fills');
    }
    coerce('hoveron', dfltHoverOn.join('+') || 'points');

    var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'});
    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'});

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

},{"../../lib":164,"../../registry":254,"./attributes":266,"./constants":272,"./fillcolor_defaults":275,"./line_defaults":279,"./line_shape_defaults":281,"./marker_defaults":284,"./subtypes":288,"./text_defaults":289,"./xy_defaults":290}],274:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');

/** Fill hover 'pointData' container with 'correct' hover text value
 *
 * - If trace hoverinfo contains a 'text' flag and hovertext is not set,
 *   the text elements will be seen in the hover labels.
 *
 * - If trace hoverinfo contains a 'text' flag and hovertext is set,
 *   hovertext takes precedence over text
 *   i.e. the hoverinfo elements will be seen in the hover labels
 *
 *  @param {object} calcPt
 *  @param {object} trace
 *  @param {object || array} contOut (mutated here)
 */
module.exports = function fillHoverText(calcPt, trace, contOut) {
    var fill = Array.isArray(contOut) ?
        function(v) { contOut.push(v); } :
        function(v) { contOut.text = v; };

    var htx = Lib.extractOption(calcPt, trace, 'htx', 'hovertext');
    if(isValid(htx)) return fill(htx);

    var tx = Lib.extractOption(calcPt, trace, 'tx', 'text');
    if(isValid(tx)) return fill(tx);
};

// accept all truthy values and 0 (which gets cast to '0' in the hover labels)
function isValid(v) {
    return v || v === 0;
}

},{"../../lib":164}],275:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = require('../../components/color');
var isArrayOrTypedArray = require('../../lib').isArrayOrTypedArray;

module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) {
    var inheritColorFromMarker = false;

    if(traceOut.marker) {
        // don't try to inherit a color array
        var markerColor = traceOut.marker.color,
            markerLineColor = (traceOut.marker.line || {}).color;

        if(markerColor && !isArrayOrTypedArray(markerColor)) {
            inheritColorFromMarker = markerColor;
        }
        else if(markerLineColor && !isArrayOrTypedArray(markerLineColor)) {
            inheritColorFromMarker = markerLineColor;
        }
    }

    coerce('fillcolor', Color.addOpacity(
        (traceOut.line || {}).color ||
        inheritColorFromMarker ||
        defaultColor, 0.5
    ));
};

},{"../../components/color":43,"../../lib":164}],276:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = require('../../components/color');
var subtypes = require('./subtypes');


module.exports = function getTraceColor(trace, di) {
    var lc, tc;

    // TODO: text modes

    if(trace.mode === 'lines') {
        lc = trace.line.color;
        return (lc && Color.opacity(lc)) ?
            lc : trace.fillcolor;
    }
    else if(trace.mode === 'none') {
        return trace.fill ? trace.fillcolor : '';
    }
    else {
        var mc = di.mcc || (trace.marker || {}).color,
            mlc = di.mlcc || ((trace.marker || {}).line || {}).color;

        tc = (mc && Color.opacity(mc)) ? mc :
            (mlc && Color.opacity(mlc) &&
                (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : '';

        if(tc) {
            // make sure the points aren't TOO transparent
            if(Color.opacity(tc) < 0.3) {
                return Color.addOpacity(tc, 0.3);
            }
            else return tc;
        }
        else {
            lc = (trace.line || {}).color;
            return (lc && Color.opacity(lc) &&
                subtypes.hasLines(trace) && trace.line.width) ?
                    lc : trace.fillcolor;
        }
    }
};

},{"../../components/color":43,"./subtypes":288}],277:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var Fx = require('../../components/fx');
var Registry = require('../../registry');
var getTraceColor = require('./get_trace_color');
var Color = require('../../components/color');
var fillHoverText = require('./fill_hover_text');

module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var xpx = xa.c2p(xval);
    var ypx = ya.c2p(yval);
    var pt = [xpx, ypx];
    var hoveron = trace.hoveron || '';
    var minRad = (trace.mode.indexOf('markers') !== -1) ? 3 : 0.5;

    // look for points to hover on first, then take fills only if we
    // didn't find a point
    if(hoveron.indexOf('points') !== -1) {
        var dx = function(di) {
            // dx and dy are used in compare modes - here we want to always
            // prioritize the closest data point, at least as long as markers are
            // the same size or nonexistent, but still try to prioritize small markers too.
            var rad = Math.max(3, di.mrc || 0);
            var kink = 1 - 1 / rad;
            var dxRaw = Math.abs(xa.c2p(di.x) - xpx);
            var d = (dxRaw < rad) ? (kink * dxRaw / rad) : (dxRaw - rad + kink);
            return d;
        };
        var dy = function(di) {
            var rad = Math.max(3, di.mrc || 0);
            var kink = 1 - 1 / rad;
            var dyRaw = Math.abs(ya.c2p(di.y) - ypx);
            return (dyRaw < rad) ? (kink * dyRaw / rad) : (dyRaw - rad + kink);
        };
        var dxy = function(di) {
            // scatter points: d.mrc is the calculated marker radius
            // adjust the distance so if you're inside the marker it
            // always will show up regardless of point size, but
            // prioritize smaller points
            var rad = Math.max(minRad, di.mrc || 0);
            var dx = xa.c2p(di.x) - xpx;
            var dy = ya.c2p(di.y) - ypx;
            return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad);
        };
        var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);

        Fx.getClosest(cd, distfn, pointData);

        // skip the rest (for this trace) if we didn't find a close point
        if(pointData.index !== false) {

            // the closest data point
            var di = cd[pointData.index];
            var xc = xa.c2p(di.x, true);
            var yc = ya.c2p(di.y, true);
            var rad = di.mrc || 1;

            Lib.extendFlat(pointData, {
                color: getTraceColor(trace, di),

                x0: xc - rad,
                x1: xc + rad,
                xLabelVal: di.x,

                y0: yc - rad,
                y1: yc + rad,
                yLabelVal: di.y,

                spikeDistance: dxy(di)
            });

            fillHoverText(di, trace, pointData);
            Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);

            return [pointData];
        }
    }

    // even if hoveron is 'fills', only use it if we have polygons too
    if(hoveron.indexOf('fills') !== -1 && trace._polygons) {
        var polygons = trace._polygons;
        var polygonsIn = [];
        var inside = false;
        var xmin = Infinity;
        var xmax = -Infinity;
        var ymin = Infinity;
        var ymax = -Infinity;

        var i, j, polygon, pts, xCross, x0, x1, y0, y1;

        for(i = 0; i < polygons.length; i++) {
            polygon = polygons[i];
            // TODO: this is not going to work right for curved edges, it will
            // act as though they're straight. That's probably going to need
            // the elements themselves to capture the events. Worth it?
            if(polygon.contains(pt)) {
                inside = !inside;
                // TODO: need better than just the overall bounding box
                polygonsIn.push(polygon);
                ymin = Math.min(ymin, polygon.ymin);
                ymax = Math.max(ymax, polygon.ymax);
            }
        }

        if(inside) {
            // constrain ymin/max to the visible plot, so the label goes
            // at the middle of the piece you can see
            ymin = Math.max(ymin, 0);
            ymax = Math.min(ymax, ya._length);

            // find the overall left-most and right-most points of the
            // polygon(s) we're inside at their combined vertical midpoint.
            // This is where we will draw the hover label.
            // Note that this might not be the vertical midpoint of the
            // whole trace, if it's disjoint.
            var yAvg = (ymin + ymax) / 2;
            for(i = 0; i < polygonsIn.length; i++) {
                pts = polygonsIn[i].pts;
                for(j = 1; j < pts.length; j++) {
                    y0 = pts[j - 1][1];
                    y1 = pts[j][1];
                    if((y0 > yAvg) !== (y1 >= yAvg)) {
                        x0 = pts[j - 1][0];
                        x1 = pts[j][0];
                        if(y1 - y0) {
                            xCross = x0 + (x1 - x0) * (yAvg - y0) / (y1 - y0);
                            xmin = Math.min(xmin, xCross);
                            xmax = Math.max(xmax, xCross);
                        }
                    }
                }
            }

            // constrain xmin/max to the visible plot now too
            xmin = Math.max(xmin, 0);
            xmax = Math.min(xmax, xa._length);

            // get only fill or line color for the hover color
            var color = Color.defaultLine;
            if(Color.opacity(trace.fillcolor)) color = trace.fillcolor;
            else if(Color.opacity((trace.line || {}).color)) {
                color = trace.line.color;
            }

            Lib.extendFlat(pointData, {
                // never let a 2D override 1D type as closest point
                // also: no spikeDistance, it's not allowed for fills
                distance: pointData.maxHoverDistance,
                x0: xmin,
                x1: xmax,
                y0: yAvg,
                y1: yAvg,
                color: color
            });

            delete pointData.index;

            if(trace.text && !Array.isArray(trace.text)) {
                pointData.text = String(trace.text);
            }
            else pointData.text = trace.name;

            return [pointData];
        }
    }
};

},{"../../components/color":43,"../../components/fx":85,"../../lib":164,"../../registry":254,"./fill_hover_text":274,"./get_trace_color":276}],278:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Scatter = {};

var subtypes = require('./subtypes');
Scatter.hasLines = subtypes.hasLines;
Scatter.hasMarkers = subtypes.hasMarkers;
Scatter.hasText = subtypes.hasText;
Scatter.isBubble = subtypes.isBubble;

// traces with < this many points are by default shown
// with points and lines, > just get lines
Scatter.attributes = require('./attributes');
Scatter.supplyDefaults = require('./defaults');
Scatter.cleanData = require('./clean_data');
Scatter.calc = require('./calc').calc;
Scatter.arraysToCalcdata = require('./arrays_to_calcdata');
Scatter.plot = require('./plot');
Scatter.colorbar = require('./colorbar');
Scatter.style = require('./style').style;
Scatter.styleOnSelect = require('./style').styleOnSelect;
Scatter.hoverPoints = require('./hover');
Scatter.selectPoints = require('./select');
Scatter.animatable = true;

Scatter.moduleType = 'trace';
Scatter.name = 'scatter';
Scatter.basePlotModule = require('../../plots/cartesian');
Scatter.categories = ['cartesian', 'svg', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend', 'scatter-like', 'draggedPts'];
Scatter.meta = {
    
};

module.exports = Scatter;

},{"../../plots/cartesian":217,"./arrays_to_calcdata":265,"./attributes":266,"./calc":267,"./clean_data":269,"./colorbar":270,"./defaults":273,"./hover":277,"./plot":285,"./select":286,"./style":287,"./subtypes":288}],279:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isArrayOrTypedArray = require('../../lib').isArrayOrTypedArray;
var hasColorscale = require('../../components/colorscale/has_colorscale');
var colorscaleDefaults = require('../../components/colorscale/defaults');

module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
    var markerColor = (traceIn.marker || {}).color;

    coerce('line.color', defaultColor);

    if(hasColorscale(traceIn, 'line')) {
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
    }
    else {
        var lineColorDflt = (isArrayOrTypedArray(markerColor) ? false : markerColor) || defaultColor;
        coerce('line.color', lineColorDflt);
    }

    coerce('line.width');
    if(!(opts || {}).noDash) coerce('line.dash');
};

},{"../../components/colorscale/defaults":53,"../../components/colorscale/has_colorscale":57,"../../lib":164}],280:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var BADNUM = require('../../constants/numerical').BADNUM;
var Lib = require('../../lib');
var segmentsIntersect = Lib.segmentsIntersect;
var constrain = Lib.constrain;
var constants = require('./constants');


module.exports = function linePoints(d, opts) {
    var xa = opts.xaxis;
    var ya = opts.yaxis;
    var simplify = opts.simplify;
    var connectGaps = opts.connectGaps;
    var baseTolerance = opts.baseTolerance;
    var shape = opts.shape;
    var linear = shape === 'linear';
    var segments = [];
    var minTolerance = constants.minTolerance;
    var pts = new Array(d.length);
    var pti = 0;

    var i;

    // pt variables are pixel coordinates [x,y] of one point
    // these four are the outputs of clustering on a line
    var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;

    // "this" is the next point we're considering adding to the cluster
    var thisPt;

    // did we encounter the high point first, then a low point, or vice versa?
    var clusterHighFirst;

    // the first two points in the cluster determine its unit vector
    // so the second is always in the "High" direction
    var clusterUnitVector;

    // the pixel delta from clusterStartPt
    var thisVector;

    // val variables are (signed) pixel distances along the cluster vector
    var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;

    // deviation variables are (signed) pixel distances normal to the cluster vector
    var clusterMinDeviation, clusterMaxDeviation, thisDeviation;

    if(!simplify) {
        baseTolerance = minTolerance = -1;
    }

    // turn one calcdata point into pixel coordinates
    function getPt(index) {
        var di = d[index];
        var x = xa.c2p(di.x);
        var y = ya.c2p(di.y);
        if(x === BADNUM || y === BADNUM) return di.intoCenter || false;
        return [x, y];
    }

    // if we're off-screen, increase tolerance over baseTolerance
    function getTolerance(pt) {
        var xFrac = pt[0] / xa._length;
        var yFrac = pt[1] / ya._length;
        return (1 + constants.toleranceGrowth * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance;
    }

    function ptDist(pt1, pt2) {
        var dx = pt1[0] - pt2[0];
        var dy = pt1[1] - pt2[1];
        return Math.sqrt(dx * dx + dy * dy);
    }

    // last bit of filtering: clip paths that are VERY far off-screen
    // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF)

    var maxScreensAway = constants.maxScreensAway;

    // find the intersections between the segment from pt1 to pt2
    // and the large rectangle maxScreensAway around the viewport
    // if one of pt1 and pt2 is inside and the other outside, there
    // will be only one intersection.
    // if both are outside there will be 0 or 2 intersections
    // (or 1 if it's right at a corner - we'll treat that like 0)
    // returns an array of intersection pts
    var xEdge0 = -xa._length * maxScreensAway;
    var xEdge1 = xa._length * (1 + maxScreensAway);
    var yEdge0 = -ya._length * maxScreensAway;
    var yEdge1 = ya._length * (1 + maxScreensAway);
    var edges = [
        [xEdge0, yEdge0, xEdge1, yEdge0],
        [xEdge1, yEdge0, xEdge1, yEdge1],
        [xEdge1, yEdge1, xEdge0, yEdge1],
        [xEdge0, yEdge1, xEdge0, yEdge0]
    ];
    var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;

    // for linear line shape, edge intersections should be linearly interpolated
    // spline uses this too, which isn't precisely correct but is actually pretty
    // good, because Catmull-Rom weights far-away points less in creating the curvature
    function getLinearEdgeIntersections(pt1, pt2) {
        var out = [];
        var ptCount = 0;
        for(var i = 0; i < 4; i++) {
            var edge = edges[i];
            var ptInt = segmentsIntersect(pt1[0], pt1[1], pt2[0], pt2[1],
                edge[0], edge[1], edge[2], edge[3]);
            if(ptInt && (!ptCount ||
                Math.abs(ptInt.x - out[0][0]) > 1 ||
                Math.abs(ptInt.y - out[0][1]) > 1
            )) {
                ptInt = [ptInt.x, ptInt.y];
                // if we have 2 intersections, make sure the closest one to pt1 comes first
                if(ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);
                else out.push(ptInt);
                ptCount++;
            }
        }
        return out;
    }

    function onlyConstrainedPoint(pt) {
        if(pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
            return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
        }
    }

    function sameEdge(pt1, pt2) {
        if(pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
        if(pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
    }

    // for line shapes hv and vh, movement in the two dimensions is decoupled,
    // so all we need to do is constrain each dimension independently
    function getHVEdgeIntersections(pt1, pt2) {
        var out = [];
        var ptInt1 = onlyConstrainedPoint(pt1);
        var ptInt2 = onlyConstrainedPoint(pt2);
        if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;

        if(ptInt1) out.push(ptInt1);
        if(ptInt2) out.push(ptInt2);
        return out;
    }

    // hvh and vhv we sometimes have to move one of the intersection points
    // out BEYOND the clipping rect, by a maximum of a factor of 2, so that
    // the midpoint line is drawn in the right place
    function getABAEdgeIntersections(dim, limit0, limit1) {
        return function(pt1, pt2) {
            var ptInt1 = onlyConstrainedPoint(pt1);
            var ptInt2 = onlyConstrainedPoint(pt2);

            var out = [];
            if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;

            if(ptInt1) out.push(ptInt1);
            if(ptInt2) out.push(ptInt2);

            var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) -
                ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
            if(midShift) {
                var ptToAlter;
                if(ptInt1 && ptInt2) {
                    ptToAlter = (midShift > 0 === ptInt1[dim] > ptInt2[dim]) ? ptInt1 : ptInt2;
                }
                else ptToAlter = ptInt1 || ptInt2;

                ptToAlter[dim] += midShift;
            }

            return out;
        };
    }

    var getEdgeIntersections;
    if(shape === 'linear' || shape === 'spline') {
        getEdgeIntersections = getLinearEdgeIntersections;
    }
    else if(shape === 'hv' || shape === 'vh') {
        getEdgeIntersections = getHVEdgeIntersections;
    }
    else if(shape === 'hvh') getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);
    else if(shape === 'vhv') getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);

    // a segment pt1->pt2 entirely outside the nearby region:
    // find the corner it gets closest to touching
    function getClosestCorner(pt1, pt2) {
        var dx = pt2[0] - pt1[0];
        var m = (pt2[1] - pt1[1]) / dx;
        var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;

        if(b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];
        else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
    }

    function updateEdge(pt) {
        var x = pt[0];
        var y = pt[1];
        var xSame = x === pts[pti - 1][0];
        var ySame = y === pts[pti - 1][1];
        // duplicate point?
        if(xSame && ySame) return;
        if(pti > 1) {
            // backtracking along an edge?
            var xSame2 = x === pts[pti - 2][0];
            var ySame2 = y === pts[pti - 2][1];
            if(xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
                if(ySame2) pti--; // backtracking exactly - drop prev pt and don't add
                else pts[pti - 1] = pt; // not exact: replace the prev pt
            }
            else if(ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
                if(xSame2) pti--;
                else pts[pti - 1] = pt;
            }
            else pts[pti++] = pt;
        }
        else pts[pti++] = pt;
    }

    function updateEdgesForReentry(pt) {
        // if we're outside the nearby region and going back in,
        // we may need to loop around a corner point
        if(pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
            updateEdge([lastXEdge, lastYEdge]);
        }
        updateEdge(pt);
        lastFarPt = null;
        lastXEdge = lastYEdge = 0;
    }

    function addPt(pt) {
        // Are we more than maxScreensAway off-screen any direction?
        // if so, clip to this box, but in such a way that on-screen
        // drawing is unchanged
        xEdge = (pt[0] < xEdge0) ? xEdge0 : (pt[0] > xEdge1) ? xEdge1 : 0;
        yEdge = (pt[1] < yEdge0) ? yEdge0 : (pt[1] > yEdge1) ? yEdge1 : 0;
        if(xEdge || yEdge) {
            // to get fills right - if first point is far, push it toward the
            // screen in whichever direction(s) are far
            if(!pti) {
                pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
            }
            else if(lastFarPt) {
                // both this point and the last are outside the nearby region
                // check if we're crossing the nearby region
                var intersections = getEdgeIntersections(lastFarPt, pt);
                if(intersections.length > 1) {
                    updateEdgesForReentry(intersections[0]);
                    pts[pti++] = intersections[1];
                }
            }
            // we're leaving the nearby region - add the point where we left it
            else {
                edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
                pts[pti++] = edgePt;
            }

            var lastPt = pts[pti - 1];
            if(xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
                // we've gone out beyond a new corner: add the corner too
                // so that the next point will take the right winding
                if(lastFarPt) {
                    if(lastXEdge !== xEdge && lastYEdge !== yEdge) {
                        if(lastXEdge && lastYEdge) {
                            // we've gone around to an opposite corner - we
                            // need to add the correct extra corner
                            // in order to get the right winding
                            updateEdge(getClosestCorner(lastFarPt, pt));
                        }
                        else {
                            // we're coming from a far edge - the extra corner
                            // we need is determined uniquely by the sectors
                            updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
                        }
                    }
                    else if(lastXEdge && lastYEdge) {
                        updateEdge([lastXEdge, lastYEdge]);
                    }
                }
                updateEdge([xEdge, yEdge]);
            }
            else if((lastXEdge - xEdge) && (lastYEdge - yEdge)) {
                // we're coming from an edge or far corner to an edge - again the
                // extra corner we need is uniquely determined by the sectors
                updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
            }
            lastFarPt = pt;
            lastXEdge = xEdge;
            lastYEdge = yEdge;
        }
        else {
            if(lastFarPt) {
                // this point is in range but the previous wasn't: add its entry pt first
                updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
            }

            pts[pti++] = pt;
        }
    }

    // loop over ALL points in this trace
    for(i = 0; i < d.length; i++) {
        clusterStartPt = getPt(i);
        if(!clusterStartPt) continue;

        pti = 0;
        lastFarPt = null;
        addPt(clusterStartPt);

        // loop over one segment of the trace
        for(i++; i < d.length; i++) {
            clusterHighPt = getPt(i);
            if(!clusterHighPt) {
                if(connectGaps) continue;
                else break;
            }

            // can't decimate if nonlinear line shape
            // TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
            // but spline would be verrry awkward to decimate
            if(!linear) {
                addPt(clusterHighPt);
                continue;
            }

            clusterRefDist = ptDist(clusterHighPt, clusterStartPt);

            if(clusterRefDist < getTolerance(clusterHighPt) * minTolerance) continue;

            clusterUnitVector = [
                (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
                (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
            ];

            clusterLowPt = clusterStartPt;
            clusterHighVal = clusterRefDist;
            clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
            clusterHighFirst = false;
            clusterEndPt = clusterHighPt;

            // loop over one cluster of points that collapse onto one line
            for(i++; i < d.length; i++) {
                thisPt = getPt(i);
                if(!thisPt) {
                    if(connectGaps) continue;
                    else break;
                }
                thisVector = [
                    thisPt[0] - clusterStartPt[0],
                    thisPt[1] - clusterStartPt[1]
                ];
                // cross product (or dot with normal to the cluster vector)
                thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
                clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
                clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);

                if(clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt)) break;

                clusterEndPt = thisPt;
                thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];

                if(thisVal > clusterHighVal) {
                    clusterHighVal = thisVal;
                    clusterHighPt = thisPt;
                    clusterHighFirst = false;
                } else if(thisVal < clusterLowVal) {
                    clusterLowVal = thisVal;
                    clusterLowPt = thisPt;
                    clusterHighFirst = true;
                }
            }

            // insert this cluster into pts
            // we've already inserted the start pt, now check if we have high and low pts
            if(clusterHighFirst) {
                addPt(clusterHighPt);
                if(clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
            } else {
                if(clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
                if(clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
            }
            // and finally insert the end pt
            addPt(clusterEndPt);

            // have we reached the end of this segment?
            if(i >= d.length || !thisPt) break;

            // otherwise we have an out-of-cluster point to insert as next clusterStartPt
            addPt(thisPt);
            clusterStartPt = thisPt;
        }

        // to get fills right - repeat what we did at the start
        if(lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);

        segments.push(pts.slice(0, pti));
    }

    return segments;
};

},{"../../constants/numerical":145,"../../lib":164,"./constants":272}],281:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


// common to 'scatter' and 'scatterternary'
module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) {
    var shape = coerce('line.shape');
    if(shape === 'spline') coerce('line.smoothing');
};

},{}],282:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = function linkTraces(gd, plotinfo, cdscatter) {
    var trace, i;
    var prevtrace = null;

    for(i = 0; i < cdscatter.length; ++i) {
        trace = cdscatter[i][0].trace;

        // Note: The check which ensures all cdscatter here are for the same axis and
        // are either cartesian or scatterternary has been removed. This code assumes
        // the passed scattertraces have been filtered to the proper plot types and
        // the proper subplots.
        if(trace.visible === true) {
            trace._nexttrace = null;

            if(['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1) {
                trace._prevtrace = prevtrace;

                if(prevtrace) {
                    prevtrace._nexttrace = trace;
                }
            }

            prevtrace = trace;
        } else {
            trace._prevtrace = trace._nexttrace = null;
        }
    }
};

},{}],283:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');


// used in the drawing step for 'scatter' and 'scattegeo' and
// in the convert step for 'scatter3d'
module.exports = function makeBubbleSizeFn(trace) {
    var marker = trace.marker,
        sizeRef = marker.sizeref || 1,
        sizeMin = marker.sizemin || 0;

    // for bubble charts, allow scaling the provided value linearly
    // and by area or diameter.
    // Note this only applies to the array-value sizes

    var baseFn = (marker.sizemode === 'area') ?
            function(v) { return Math.sqrt(v / sizeRef); } :
            function(v) { return v / sizeRef; };

    // TODO add support for position/negative bubbles?
    // TODO add 'sizeoffset' attribute?
    return function(v) {
        var baseSize = baseFn(v / 2);

        // don't show non-numeric and negative sizes
        return (isNumeric(baseSize) && (baseSize > 0)) ?
            Math.max(baseSize, sizeMin) :
            0;
    };
};

},{"fast-isnumeric":9}],284:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Color = require('../../components/color');
var hasColorscale = require('../../components/colorscale/has_colorscale');
var colorscaleDefaults = require('../../components/colorscale/defaults');

var subTypes = require('./subtypes');

/*
 * opts: object of flags to control features not all marker users support
 *   noLine: caller does not support marker lines
 *   gradient: caller supports gradients
 *   noSelect: caller does not support selected/unselected attribute containers
 */
module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
    var isBubble = subTypes.isBubble(traceIn),
        lineColor = (traceIn.line || {}).color,
        defaultMLC;

    opts = opts || {};

    // marker.color inherit from line.color (even if line.color is an array)
    if(lineColor) defaultColor = lineColor;

    coerce('marker.symbol');
    coerce('marker.opacity', isBubble ? 0.7 : 1);
    coerce('marker.size');

    coerce('marker.color', defaultColor);
    if(hasColorscale(traceIn, 'marker')) {
        colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'});
    }

    if(!opts.noSelect) {
        coerce('selected.marker.color');
        coerce('unselected.marker.color');
        coerce('selected.marker.size');
        coerce('unselected.marker.size');
    }

    if(!opts.noLine) {
        // if there's a line with a different color than the marker, use
        // that line color as the default marker line color
        // (except when it's an array)
        // mostly this is for transparent markers to behave nicely
        if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) {
            defaultMLC = lineColor;
        }
        else if(isBubble) defaultMLC = Color.background;
        else defaultMLC = Color.defaultLine;

        coerce('marker.line.color', defaultMLC);
        if(hasColorscale(traceIn, 'marker.line')) {
            colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'});
        }

        coerce('marker.line.width', isBubble ? 1 : 0);
    }

    if(isBubble) {
        coerce('marker.sizeref');
        coerce('marker.sizemin');
        coerce('marker.sizemode');
    }

    if(opts.gradient) {
        var gradientType = coerce('marker.gradient.type');
        if(gradientType !== 'none') {
            coerce('marker.gradient.color');
        }
    }
};

},{"../../components/color":43,"../../components/colorscale/defaults":53,"../../components/colorscale/has_colorscale":57,"./subtypes":288}],285:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');

var Registry = require('../../registry');
var Lib = require('../../lib');
var Drawing = require('../../components/drawing');

var subTypes = require('./subtypes');
var linePoints = require('./line_points');
var linkTraces = require('./link_traces');
var polygonTester = require('../../lib/polygon').tester;

module.exports = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) {
    var i, uids, join, onComplete;

    // If transition config is provided, then it is only a partial replot and traces not
    // updated are removed.
    var isFullReplot = !transitionOpts;
    var hasTransition = !!transitionOpts && transitionOpts.duration > 0;

    join = scatterLayer.selectAll('g.trace')
        .data(cdscatter, function(d) { return d[0].trace.uid; });

    // Append new traces:
    join.enter().append('g')
        .attr('class', function(d) {
            return 'trace scatter trace' + d[0].trace.uid;
        })
        .style('stroke-miterlimit', 2);

    // After the elements are created but before they've been draw, we have to perform
    // this extra step of linking the traces. This allows appending of fill layers so that
    // the z-order of fill layers is correct.
    linkTraces(gd, plotinfo, cdscatter);

    createFills(gd, scatterLayer, plotinfo);

    // Sort the traces, once created, so that the ordering is preserved even when traces
    // are shown and hidden. This is needed since we're not just wiping everything out
    // and recreating on every update.
    for(i = 0, uids = {}; i < cdscatter.length; i++) {
        uids[cdscatter[i][0].trace.uid] = i;
    }

    scatterLayer.selectAll('g.trace').sort(function(a, b) {
        var idx1 = uids[a[0].trace.uid];
        var idx2 = uids[b[0].trace.uid];
        return idx1 > idx2 ? 1 : -1;
    });

    if(hasTransition) {
        if(makeOnCompleteCallback) {
            // If it was passed a callback to register completion, make a callback. If
            // this is created, then it must be executed on completion, otherwise the
            // pos-transition redraw will not execute:
            onComplete = makeOnCompleteCallback();
        }

        var transition = d3.transition()
            .duration(transitionOpts.duration)
            .ease(transitionOpts.easing)
            .each('end', function() {
                onComplete && onComplete();
            })
            .each('interrupt', function() {
                onComplete && onComplete();
            });

        transition.each(function() {
            // Must run the selection again since otherwise enters/updates get grouped together
            // and these get executed out of order. Except we need them in order!
            scatterLayer.selectAll('g.trace').each(function(d, i) {
                plotOne(gd, i, plotinfo, d, cdscatter, this, transitionOpts);
            });
        });
    } else {
        scatterLayer.selectAll('g.trace').each(function(d, i) {
            plotOne(gd, i, plotinfo, d, cdscatter, this, transitionOpts);
        });
    }

    if(isFullReplot) {
        join.exit().remove();
    }

    // remove paths that didn't get used
    scatterLayer.selectAll('path:not([d])').remove();
};

function createFills(gd, scatterLayer, plotinfo) {
    var trace;

    scatterLayer.selectAll('g.trace').each(function(d) {
        var tr = d3.select(this);

        // Loop only over the traces being redrawn:
        trace = d[0].trace;

        // make the fill-to-next path now for the NEXT trace, so it shows
        // behind both lines.
        if(trace._nexttrace) {
            trace._nextFill = tr.select('.js-fill.js-tonext');
            if(!trace._nextFill.size()) {

                // If there is an existing tozero fill, we must insert this *after* that fill:
                var loc = ':first-child';
                if(tr.select('.js-fill.js-tozero').size()) {
                    loc += ' + *';
                }

                trace._nextFill = tr.insert('path', loc).attr('class', 'js-fill js-tonext');
            }
        } else {
            tr.selectAll('.js-fill.js-tonext').remove();
            trace._nextFill = null;
        }

        if(trace.fill && (trace.fill.substr(0, 6) === 'tozero' || trace.fill === 'toself' ||
                (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace))) {
            trace._ownFill = tr.select('.js-fill.js-tozero');
            if(!trace._ownFill.size()) {
                trace._ownFill = tr.insert('path', ':first-child').attr('class', 'js-fill js-tozero');
            }
        } else {
            tr.selectAll('.js-fill.js-tozero').remove();
            trace._ownFill = null;
        }

        tr.selectAll('.js-fill').call(Drawing.setClipUrl, plotinfo.layerClipId);
    });
}

function plotOne(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) {
    var join, i;

    // Since this has been reorganized and we're executing this on individual traces,
    // we need to pass it the full list of cdscatter as well as this trace's index (idx)
    // since it does an internal n^2 loop over comparisons with other traces:
    selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll);

    var hasTransition = !!transitionOpts && transitionOpts.duration > 0;

    function transition(selection) {
        return hasTransition ? selection.transition() : selection;
    }

    var xa = plotinfo.xaxis,
        ya = plotinfo.yaxis;

    var trace = cdscatter[0].trace,
        line = trace.line,
        tr = d3.select(element);

    // error bars are at the bottom
    Registry.getComponentMethod('errorbars', 'plot')(tr, plotinfo, transitionOpts);

    if(trace.visible !== true) return;

    transition(tr).style('opacity', trace.opacity);

    // BUILD LINES AND FILLS
    var ownFillEl3, tonext;
    var ownFillDir = trace.fill.charAt(trace.fill.length - 1);
    if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = '';

    // store node for tweaking by selectPoints
    if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr;

    var prevRevpath = '';
    var prevPolygons = [];
    var prevtrace = trace._prevtrace;

    if(prevtrace) {
        prevRevpath = prevtrace._prevRevpath || '';
        tonext = prevtrace._nextFill;
        prevPolygons = prevtrace._polygons;
    }

    var thispath,
        thisrevpath,
        // fullpath is all paths for this curve, joined together straight
        // across gaps, for filling
        fullpath = '',
        // revpath is fullpath reversed, for fill-to-next
        revpath = '',
        // functions for converting a point array to a path
        pathfn, revpathbase, revpathfn,
        // variables used before and after the data join
        pt0, lastSegment, pt1, thisPolygons;

    // initialize line join data / method
    var segments = [],
        makeUpdate = Lib.noop;

    ownFillEl3 = trace._ownFill;

    if(subTypes.hasLines(trace) || trace.fill !== 'none') {

        if(tonext) {
            // This tells .style which trace to use for fill information:
            tonext.datum(cdscatter);
        }

        if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) {
            pathfn = Drawing.steps(line.shape);
            revpathbase = Drawing.steps(
                line.shape.split('').reverse().join('')
            );
        }
        else if(line.shape === 'spline') {
            pathfn = revpathbase = function(pts) {
                var pLast = pts[pts.length - 1];
                if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) {
                    // identical start and end points: treat it as a
                    // closed curve so we don't get a kink
                    return Drawing.smoothclosed(pts.slice(1), line.smoothing);
                }
                else {
                    return Drawing.smoothopen(pts, line.smoothing);
                }
            };
        }
        else {
            pathfn = revpathbase = function(pts) {
                return 'M' + pts.join('L');
            };
        }

        revpathfn = function(pts) {
            // note: this is destructive (reverses pts in place) so can't use pts after this
            return revpathbase(pts.reverse());
        };

        segments = linePoints(cdscatter, {
            xaxis: xa,
            yaxis: ya,
            connectGaps: trace.connectgaps,
            baseTolerance: Math.max(line.width || 1, 3) / 4,
            shape: line.shape,
            simplify: line.simplify
        });

        // since we already have the pixel segments here, use them to make
        // polygons for hover on fill
        // TODO: can we skip this if hoveron!=fills? That would mean we
        // need to redraw when you change hoveron...
        thisPolygons = trace._polygons = new Array(segments.length);
        for(i = 0; i < segments.length; i++) {
            trace._polygons[i] = polygonTester(segments[i]);
        }

        if(segments.length) {
            pt0 = segments[0][0];
            lastSegment = segments[segments.length - 1];
            pt1 = lastSegment[lastSegment.length - 1];
        }

        makeUpdate = function(isEnter) {
            return function(pts) {
                thispath = pathfn(pts);
                thisrevpath = revpathfn(pts);
                if(!fullpath) {
                    fullpath = thispath;
                    revpath = thisrevpath;
                }
                else if(ownFillDir) {
                    fullpath += 'L' + thispath.substr(1);
                    revpath = thisrevpath + ('L' + revpath.substr(1));
                }
                else {
                    fullpath += 'Z' + thispath;
                    revpath = thisrevpath + 'Z' + revpath;
                }

                if(subTypes.hasLines(trace) && pts.length > 1) {
                    var el = d3.select(this);

                    // This makes the coloring work correctly:
                    el.datum(cdscatter);

                    if(isEnter) {
                        transition(el.style('opacity', 0)
                            .attr('d', thispath)
                            .call(Drawing.lineGroupStyle))
                                .style('opacity', 1);
                    } else {
                        var sel = transition(el);
                        sel.attr('d', thispath);
                        Drawing.singleLineStyle(cdscatter, sel);
                    }
                }
            };
        };
    }

    var lineJoin = tr.selectAll('.js-line').data(segments);

    transition(lineJoin.exit())
        .style('opacity', 0)
        .remove();

    lineJoin.each(makeUpdate(false));

    lineJoin.enter().append('path')
        .classed('js-line', true)
        .style('vector-effect', 'non-scaling-stroke')
        .call(Drawing.lineGroupStyle)
        .each(makeUpdate(true));

    Drawing.setClipUrl(lineJoin, plotinfo.layerClipId);

    function clearFill(selection) {
        transition(selection).attr('d', 'M0,0Z');
    }

    if(segments.length) {
        if(ownFillEl3) {
            if(pt0 && pt1) {
                if(ownFillDir) {
                    if(ownFillDir === 'y') {
                        pt0[1] = pt1[1] = ya.c2p(0, true);
                    }
                    else if(ownFillDir === 'x') {
                        pt0[0] = pt1[0] = xa.c2p(0, true);
                    }

                    // fill to zero: full trace path, plus extension of
                    // the endpoints to the appropriate axis
                    // For the sake of animations, wrap the points around so that
                    // the points on the axes are the first two points. Otherwise
                    // animations get a little crazy if the number of points changes.
                    transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1))
                        .call(Drawing.singleFillStyle);
                } else {
                    // fill to self: just join the path to itself
                    transition(ownFillEl3).attr('d', fullpath + 'Z')
                        .call(Drawing.singleFillStyle);
                }
            }
        }
        else if(tonext) {
            if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevRevpath) {
                // fill to next: full trace path, plus the previous path reversed
                if(trace.fill === 'tonext') {
                    // tonext: for use by concentric shapes, like manually constructed
                    // contours, we just add the two paths closed on themselves.
                    // This makes strange results if one path is *not* entirely
                    // inside the other, but then that is a strange usage.
                    transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z')
                        .call(Drawing.singleFillStyle);
                }
                else {
                    // tonextx/y: for now just connect endpoints with lines. This is
                    // the correct behavior if the endpoints are at the same value of
                    // y/x, but if they *aren't*, we should ideally do more complicated
                    // things depending on whether the new endpoint projects onto the
                    // existing curve or off the end of it
                    transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z')
                        .call(Drawing.singleFillStyle);
                }
                trace._polygons = trace._polygons.concat(prevPolygons);
            }
            else {
                clearFill(tonext);
                trace._polygons = null;
            }
        }
        trace._prevRevpath = revpath;
        trace._prevPolygons = thisPolygons;
    }
    else {
        if(ownFillEl3) clearFill(ownFillEl3);
        else if(tonext) clearFill(tonext);
        trace._polygons = trace._prevRevpath = trace._prevPolygons = null;
    }


    function visFilter(d) {
        return d.filter(function(v) { return v.vis; });
    }

    function keyFunc(d) {
        return d.id;
    }

    // Returns a function if the trace is keyed, otherwise returns undefined
    function getKeyFunc(trace) {
        if(trace.ids) {
            return keyFunc;
        }
    }

    function hideFilter() {
        return false;
    }

    function makePoints(d) {
        var join, selection, hasNode;

        var trace = d[0].trace;
        var s = d3.select(this);
        var showMarkers = subTypes.hasMarkers(trace);
        var showText = subTypes.hasText(trace);

        var keyFunc = getKeyFunc(trace);
        var markerFilter = hideFilter;
        var textFilter = hideFilter;

        if(showMarkers) {
            markerFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : Lib.identity;
        }

        if(showText) {
            textFilter = (trace.marker.maxdisplayed || trace._needsCull) ? visFilter : Lib.identity;
        }

        // marker points

        selection = s.selectAll('path.point');

        join = selection.data(markerFilter, keyFunc);

        var enter = join.enter().append('path')
            .classed('point', true);

        if(hasTransition) {
            enter
                .call(Drawing.pointStyle, trace, gd)
                .call(Drawing.translatePoints, xa, ya)
                .style('opacity', 0)
                .transition()
                .style('opacity', 1);
        }

        join.order();

        var styleFns;
        if(showMarkers) {
            styleFns = Drawing.makePointStyleFns(trace);
        }

        join.each(function(d) {
            var el = d3.select(this);
            var sel = transition(el);
            hasNode = Drawing.translatePoint(d, sel, xa, ya);

            if(hasNode) {
                Drawing.singlePointStyle(d, sel, trace, styleFns, gd);

                if(plotinfo.layerClipId) {
                    Drawing.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar);
                }

                if(trace.customdata) {
                    el.classed('plotly-customdata', d.data !== null && d.data !== undefined);
                }
            } else {
                sel.remove();
            }
        });

        if(hasTransition) {
            join.exit().transition()
                .style('opacity', 0)
                .remove();
        } else {
            join.exit().remove();
        }

        // text points
        selection = s.selectAll('g');
        join = selection.data(textFilter, keyFunc);

        // each text needs to go in its own 'g' in case
        // it gets converted to mathjax
        join.enter().append('g').classed('textpoint', true).append('text');

        join.order();

        join.each(function(d) {
            var g = d3.select(this);
            var sel = transition(g.select('text'));
            hasNode = Drawing.translatePoint(d, sel, xa, ya);

            if(hasNode) {
                if(plotinfo.layerClipId) {
                    Drawing.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar);
                }
            } else {
                g.remove();
            }
        });

        join.selectAll('text')
            .call(Drawing.textPointStyle, trace, gd)
            .each(function(d) {
                // This just *has* to be totally custom becuase of SVG text positioning :(
                // It's obviously copied from translatePoint; we just can't use that
                var x = xa.c2p(d.x);
                var y = ya.c2p(d.y);

                d3.select(this).selectAll('tspan.line').each(function() {
                    transition(d3.select(this)).attr({x: x, y: y});
                });
            });

        join.exit().remove();
    }

    // NB: selectAll is evaluated on instantiation:
    var pointSelection = tr.selectAll('.points');

    // Join with new data
    join = pointSelection.data([cdscatter]);

    // Transition existing, but don't defer this to an async .transition since
    // there's no timing involved:
    pointSelection.each(makePoints);

    join.enter().append('g')
        .classed('points', true)
        .each(makePoints);

    join.exit().remove();

    // lastly, clip points groups of `cliponaxis !== false` traces
    // on `plotinfo._hasClipOnAxisFalse === true` subplots
    join.each(function(d) {
        var hasClipOnAxisFalse = d[0].trace.cliponaxis === false;
        Drawing.setClipUrl(d3.select(this), hasClipOnAxisFalse ? null : plotinfo.layerClipId);
    });
}

function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) {
    var xa = plotinfo.xaxis,
        ya = plotinfo.yaxis,
        xr = d3.extent(Lib.simpleMap(xa.range, xa.r2c)),
        yr = d3.extent(Lib.simpleMap(ya.range, ya.r2c));

    var trace = cdscatter[0].trace;
    if(!subTypes.hasMarkers(trace)) return;
    // if marker.maxdisplayed is used, select a maximum of
    // mnum markers to show, from the set that are in the viewport
    var mnum = trace.marker.maxdisplayed;

    // TODO: remove some as we get away from the viewport?
    if(mnum === 0) return;

    var cd = cdscatter.filter(function(v) {
            return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1];
        }),
        inc = Math.ceil(cd.length / mnum),
        tnum = 0;
    cdscatterAll.forEach(function(cdj, j) {
        var tracei = cdj[0].trace;
        if(subTypes.hasMarkers(tracei) &&
                tracei.marker.maxdisplayed > 0 && j < idx) {
            tnum++;
        }
    });

    // if multiple traces use maxdisplayed, stagger which markers we
    // display this formula offsets successive traces by 1/3 of the
    // increment, adding an extra small amount after each triplet so
    // it's not quite periodic
    var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1);

    // for error bars: save in cd which markers to show
    // so we don't have to repeat this
    cdscatter.forEach(function(v) { delete v.vis; });
    cd.forEach(function(v, i) {
        if(Math.round((i + i0) % inc) === 0) v.vis = true;
    });
}

},{"../../components/drawing":68,"../../lib":164,"../../lib/polygon":176,"../../registry":254,"./line_points":280,"./link_traces":282,"./subtypes":288,"d3":6}],286:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var subtypes = require('./subtypes');

module.exports = function selectPoints(searchInfo, polygon) {
    var cd = searchInfo.cd,
        xa = searchInfo.xaxis,
        ya = searchInfo.yaxis,
        selection = [],
        trace = cd[0].trace,
        i,
        di,
        x,
        y;

    var hasOnlyLines = (!subtypes.hasMarkers(trace) && !subtypes.hasText(trace));
    if(hasOnlyLines) return [];

    if(polygon === false) { // clear selection
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    }
    else {
        for(i = 0; i < cd.length; i++) {
            di = cd[i];
            x = xa.c2p(di.x);
            y = ya.c2p(di.y);

            if(polygon.contains([x, y])) {
                selection.push({
                    pointNumber: i,
                    x: xa.c2d(di.x),
                    y: ya.c2d(di.y)
                });
                di.selected = 1;
            } else {
                di.selected = 0;
            }
        }
    }

    return selection;
};

},{"./subtypes":288}],287:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var d3 = require('d3');
var Drawing = require('../../components/drawing');
var Registry = require('../../registry');

function style(gd, cd) {
    var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.scatter');

    s.style('opacity', function(d) {
        return d[0].trace.opacity;
    });

    s.selectAll('g.points').each(function(d) {
        var sel = d3.select(this);
        var trace = d.trace || d[0].trace;
        stylePoints(sel, trace, gd);
    });

    s.selectAll('g.trace path.js-line')
        .call(Drawing.lineGroupStyle);

    s.selectAll('g.trace path.js-fill')
        .call(Drawing.fillGroupStyle);

    Registry.getComponentMethod('errorbars', 'style')(s);
}

function stylePoints(sel, trace, gd) {
    Drawing.pointStyle(sel.selectAll('path.point'), trace, gd);
    Drawing.textPointStyle(sel.selectAll('text'), trace, gd);
}

function styleOnSelect(gd, cd) {
    var s = cd[0].node3;
    var trace = cd[0].trace;

    if(trace.selectedpoints) {
        Drawing.selectedPointStyle(s.selectAll('path.point'), trace);
        Drawing.selectedTextStyle(s.selectAll('text'), trace);
    } else {
        stylePoints(s, trace, gd);
    }
}

module.exports = {
    style: style,
    stylePoints: stylePoints,
    styleOnSelect: styleOnSelect
};

},{"../../components/drawing":68,"../../registry":254,"d3":6}],288:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');

module.exports = {
    hasLines: function(trace) {
        return trace.visible && trace.mode &&
            trace.mode.indexOf('lines') !== -1;
    },

    hasMarkers: function(trace) {
        return trace.visible && (
            (trace.mode && trace.mode.indexOf('markers') !== -1) ||
            // until splom implements 'mode'
            trace.type === 'splom'
        );
    },

    hasText: function(trace) {
        return trace.visible && trace.mode &&
            trace.mode.indexOf('text') !== -1;
    },

    isBubble: function(trace) {
        return Lib.isPlainObject(trace.marker) &&
            Lib.isArrayOrTypedArray(trace.marker.size);
    }
};

},{"../../lib":164}],289:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Lib = require('../../lib');

/*
 * opts: object of flags to control features not all text users support
 *   noSelect: caller does not support selected/unselected attribute containers
 */
module.exports = function(traceIn, traceOut, layout, coerce, opts) {
    opts = opts || {};

    coerce('textposition');
    Lib.coerceFont(coerce, 'textfont', layout.font);

    if(!opts.noSelect) {
        coerce('selected.textfont.color');
        coerce('unselected.textfont.color');
    }
};

},{"../../lib":164}],290:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Registry = require('../../registry');


module.exports = function handleXYDefaults(traceIn, traceOut, layout, coerce) {
    var len,
        x = coerce('x'),
        y = coerce('y');

    var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
    handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);

    if(x) {
        if(y) {
            len = Math.min(x.length, y.length);
        }
        else {
            len = x.length;
            coerce('y0');
            coerce('dy');
        }
    }
    else {
        if(!y) return 0;

        len = traceOut.y.length;
        coerce('x0');
        coerce('dx');
    }

    traceOut._length = len;

    return len;
};

},{"../../registry":254}],291:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterAttrs = require('../scatter/attributes');
var plotAttrs = require('../../plots/attributes');
var colorAttributes = require('../../components/colorscale/color_attributes');
var dash = require('../../components/drawing/attributes').dash;

var extendFlat = require('../../lib/extend').extendFlat;
var overrideAll = require('../../plot_api/edit_types').overrideAll;

var scatterMarkerAttrs = scatterAttrs.marker,
    scatterLineAttrs = scatterAttrs.line,
    scatterMarkerLineAttrs = scatterMarkerAttrs.line;

module.exports = overrideAll({
    lon: {
        valType: 'data_array',
        
    },
    lat: {
        valType: 'data_array',
        
    },

    locations: {
        valType: 'data_array',
        
    },
    locationmode: {
        valType: 'enumerated',
        values: ['ISO-3', 'USA-states', 'country names'],
        
        dflt: 'ISO-3',
        
    },

    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    textfont: scatterAttrs.textfont,
    textposition: scatterAttrs.textposition,

    line: {
        color: scatterLineAttrs.color,
        width: scatterLineAttrs.width,
        dash: dash
    },
    connectgaps: scatterAttrs.connectgaps,

    marker: extendFlat({
        symbol: scatterMarkerAttrs.symbol,
        opacity: scatterMarkerAttrs.opacity,
        size: scatterMarkerAttrs.size,
        sizeref: scatterMarkerAttrs.sizeref,
        sizemin: scatterMarkerAttrs.sizemin,
        sizemode: scatterMarkerAttrs.sizemode,
        showscale: scatterMarkerAttrs.showscale,
        colorbar: scatterMarkerAttrs.colorbar,
        line: extendFlat({
            width: scatterMarkerLineAttrs.width
        },
            colorAttributes('marker.line')
        ),
        gradient: scatterMarkerAttrs.gradient
    },
        colorAttributes('marker')
    ),

    fill: {
        valType: 'enumerated',
        values: ['none', 'toself'],
        dflt: 'none',
        
        
    },
    fillcolor: scatterAttrs.fillcolor,

    selected: scatterAttrs.selected,
    unselected: scatterAttrs.unselected,

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['lon', 'lat', 'location', 'text', 'name']
    })
}, 'calc', 'nested');

},{"../../components/colorscale/color_attributes":51,"../../components/drawing/attributes":67,"../../lib/extend":157,"../../plot_api/edit_types":191,"../../plots/attributes":203,"../scatter/attributes":266}],292:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var isNumeric = require('fast-isnumeric');
var BADNUM = require('../../constants/numerical').BADNUM;

var calcMarkerColorscale = require('../scatter/colorscale_calc');
var arraysToCalcdata = require('../scatter/arrays_to_calcdata');
var calcSelection = require('../scatter/calc_selection');

var _ = require('../../lib')._;

module.exports = function calc(gd, trace) {
    var hasLocationData = Array.isArray(trace.locations);
    var len = hasLocationData ? trace.locations.length : trace._length;
    var calcTrace = new Array(len);

    for(var i = 0; i < len; i++) {
        var calcPt = calcTrace[i] = {};

        if(hasLocationData) {
            var loc = trace.locations[i];
            calcPt.loc = typeof loc === 'string' ? loc : null;
        } else {
            var lon = trace.lon[i];
            var lat = trace.lat[i];

            if(isNumeric(lon) && isNumeric(lat)) calcPt.lonlat = [+lon, +lat];
            else calcPt.lonlat = [BADNUM, BADNUM];
        }
    }

    arraysToCalcdata(calcTrace, trace);
    calcMarkerColorscale(trace);
    calcSelection(calcTrace, trace);

    if(len) {
        calcTrace[0].t = {
            labels: {
                lat: _(gd, 'lat:') + ' ',
                lon: _(gd, 'lon:') + ' '
            }
        };
    }

    return calcTrace;
};

},{"../../constants/numerical":145,"../../lib":164,"../scatter/arrays_to_calcdata":265,"../scatter/calc_selection":268,"../scatter/colorscale_calc":271,"fast-isnumeric":9}],293:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var scatterGeoAttrs = require('../scattergeo/attributes');
var scatterAttrs = require('../scatter/attributes');
var mapboxAttrs = require('../../plots/mapbox/layout_attributes');
var plotAttrs = require('../../plots/attributes');
var colorbarAttrs = require('../../components/colorbar/attributes');

var extendFlat = require('../../lib/extend').extendFlat;
var overrideAll = require('../../plot_api/edit_types').overrideAll;

var lineAttrs = scatterGeoAttrs.line;
var markerAttrs = scatterGeoAttrs.marker;

module.exports = overrideAll({
    lon: scatterGeoAttrs.lon,
    lat: scatterGeoAttrs.lat,

    // locations
    // locationmode

    mode: extendFlat({}, scatterAttrs.mode, {
        dflt: 'markers',
        
    }),

    text: extendFlat({}, scatterAttrs.text, {
        
    }),
    hovertext: extendFlat({}, scatterAttrs.hovertext, {
        
    }),

    line: {
        color: lineAttrs.color,
        width: lineAttrs.width

        // TODO
        // dash: dash
    },

    connectgaps: scatterAttrs.connectgaps,

    marker: {
        symbol: {
            valType: 'string',
            dflt: 'circle',
            
            arrayOk: true,
            
        },
        opacity: markerAttrs.opacity,
        size: markerAttrs.size,
        sizeref: markerAttrs.sizeref,
        sizemin: markerAttrs.sizemin,
        sizemode: markerAttrs.sizemode,
        color: markerAttrs.color,
        colorscale: markerAttrs.colorscale,
        cauto: markerAttrs.cauto,
        cmax: markerAttrs.cmax,
        cmin: markerAttrs.cmin,
        autocolorscale: markerAttrs.autocolorscale,
        reversescale: markerAttrs.reversescale,
        showscale: markerAttrs.showscale,
        colorbar: colorbarAttrs,

        // line
    },

    fill: scatterGeoAttrs.fill,
    fillcolor: scatterAttrs.fillcolor,

    textfont: mapboxAttrs.layers.symbol.textfont,
    textposition: mapboxAttrs.layers.symbol.textposition,

    selected: {
        marker: scatterAttrs.selected.marker
    },
    unselected: {
        marker: scatterAttrs.unselected.marker
    },

    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
        flags: ['lon', 'lat', 'text', 'name']
    })
}, 'calc', 'nested');

},{"../../components/colorbar/attributes":44,"../../lib/extend":157,"../../plot_api/edit_types":191,"../../plots/attributes":203,"../../plots/mapbox/layout_attributes":241,"../scatter/attributes":266,"../scattergeo/attributes":291}],294:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var isNumeric = require('fast-isnumeric');

var Lib = require('../../lib');
var BADNUM = require('../../constants/numerical').BADNUM;
var geoJsonUtils = require('../../lib/geojson_utils');

var Colorscale = require('../../components/colorscale');
var Drawing = require('../../components/drawing');
var makeBubbleSizeFn = require('../scatter/make_bubble_size_func');
var subTypes = require('../scatter/subtypes');
var convertTextOpts = require('../../plots/mapbox/convert_text_opts');

module.exports = function convert(calcTrace) {
    var trace = calcTrace[0].trace;

    var isVisible = (trace.visible === true);
    var hasFill = (trace.fill !== 'none');
    var hasLines = subTypes.hasLines(trace);
    var hasMarkers = subTypes.hasMarkers(trace);
    var hasText = subTypes.hasText(trace);
    var hasCircles = (hasMarkers && trace.marker.symbol === 'circle');
    var hasSymbols = (hasMarkers && trace.marker.symbol !== 'circle');

    var fill = initContainer();
    var line = initContainer();
    var circle = initContainer();
    var symbol = initContainer();

    var opts = {
        fill: fill,
        line: line,
        circle: circle,
        symbol: symbol
    };

    // early return if not visible or placeholder
    if(!isVisible) return opts;

    // fill layer and line layer use the same coords
    var lineCoords;
    if(hasFill || hasLines) {
        lineCoords = geoJsonUtils.calcTraceToLineCoords(calcTrace);
    }

    if(hasFill) {
        fill.geojson = geoJsonUtils.makePolygon(lineCoords);
        fill.layout.visibility = 'visible';

        Lib.extendFlat(fill.paint, {
            'fill-color': trace.fillcolor
        });
    }

    if(hasLines) {
        line.geojson = geoJsonUtils.makeLine(lineCoords);
        line.layout.visibility = 'visible';

        Lib.extendFlat(line.paint, {
            'line-width': trace.line.width,
            'line-color': trace.line.color,
            'line-opacity': trace.opacity
        });

        // TODO convert line.dash into line-dasharray
    }

    if(hasCircles) {
        var circleOpts = makeCircleOpts(calcTrace);
        circle.geojson = circleOpts.geojson;
        circle.layout.visibility = 'visible';

        Lib.extendFlat(circle.paint, {
            'circle-color': circleOpts.mcc,
            'circle-radius': circleOpts.mrc,
            'circle-opacity': circleOpts.mo
        });
    }

    if(hasSymbols || hasText) {
        symbol.geojson = makeSymbolGeoJSON(calcTrace);

        Lib.extendFlat(symbol.layout, {
            visibility: 'visible',
            'icon-image': '{symbol}-15',
            'text-field': '{text}'
        });

        if(hasSymbols) {
            Lib.extendFlat(symbol.layout, {
                'icon-size': trace.marker.size / 10
            });

            Lib.extendFlat(symbol.paint, {
                'icon-opacity': trace.opacity * trace.marker.opacity,

                // TODO does not work ??
                'icon-color': trace.marker.color
            });
        }

        if(hasText) {
            var iconSize = (trace.marker || {}).size,
                textOpts = convertTextOpts(trace.textposition, iconSize);

            // all data-driven below !!

            Lib.extendFlat(symbol.layout, {
                'text-size': trace.textfont.size,
                'text-anchor': textOpts.anchor,
                'text-offset': textOpts.offset

                // TODO font family
                // 'text-font': symbol.textfont.family.split(', '),
            });

            Lib.extendFlat(symbol.paint, {
                'text-color': trace.textfont.color,
                'text-opacity': trace.opacity
            });
        }
    }

    return opts;
};

function initContainer() {
    return {
        geojson: geoJsonUtils.makeBlank(),
        layout: { visibility: 'none' },
        paint: {}
    };
}

function makeCircleOpts(calcTrace) {
    var trace = calcTrace[0].trace;
    var marker = trace.marker;
    var selectedpoints = trace.selectedpoints;
    var arrayColor = Lib.isArrayOrTypedArray(marker.color);
    var arraySize = Lib.isArrayOrTypedArray(marker.size);
    var arrayOpacity = Lib.isArrayOrTypedArray(marker.opacity);
    var i;

    function addTraceOpacity(o) { return trace.opacity * o; }

    function size2radius(s) { return s / 2; }

    var colorFn;
    if(arrayColor) {
        if(Colorscale.hasColorscale(trace, 'marker')) {
            colorFn = Colorscale.makeColorScaleFunc(
                 Colorscale.extractScale(marker.colorscale, marker.cmin, marker.cmax)
             );
        } else {
            colorFn = Lib.identity;
        }
    }

    var sizeFn;
    if(arraySize) {
        sizeFn = makeBubbleSizeFn(trace);
    }

    var opacityFn;
    if(arrayOpacity) {
        opacityFn = function(mo) {
            var mo2 = isNumeric(mo) ? +Lib.constrain(mo, 0, 1) : 0;
            return addTraceOpacity(mo2);
        };
    }

    var features = [];
    for(i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];
        var lonlat = calcPt.lonlat;

        if(isBADNUM(lonlat)) continue;

        var props = {};
        if(colorFn) props.mcc = calcPt.mcc = colorFn(calcPt.mc);
        if(sizeFn) props.mrc = calcPt.mrc = sizeFn(calcPt.ms);
        if(opacityFn) props.mo = opacityFn(calcPt.mo);
        if(selectedpoints) props.selected = calcPt.selected || 0;

        features.push({
            type: 'Feature',
            geometry: {type: 'Point', coordinates: lonlat},
            properties: props
        });
    }

    var fns;
    if(selectedpoints) {
        fns = Drawing.makeSelectedPointStyleFns(trace);

        for(i = 0; i < features.length; i++) {
            var d = features[i].properties;

            if(fns.selectedOpacityFn) {
                d.mo = addTraceOpacity(fns.selectedOpacityFn(d));
            }
            if(fns.selectedColorFn) {
                d.mcc = fns.selectedColorFn(d);
            }
            if(fns.selectedSizeFn) {
                d.mrc = fns.selectedSizeFn(d);
            }
        }
    }

    return {
        geojson: {type: 'FeatureCollection', features: features},
        mcc: arrayColor || (fns && fns.selectedColorFn) ?
            {type: 'identity', property: 'mcc'} :
            marker.color,
        mrc: arraySize || (fns && fns.selectedSizeFn) ?
            {type: 'identity', property: 'mrc'} :
            size2radius(marker.size),
        mo: arrayOpacity || (fns && fns.selectedOpacityFn) ?
            {type: 'identity', property: 'mo'} :
            addTraceOpacity(marker.opacity)
    };
}

function makeSymbolGeoJSON(calcTrace) {
    var trace = calcTrace[0].trace;

    var marker = trace.marker || {},
        symbol = marker.symbol,
        text = trace.text;

    var fillSymbol = (symbol !== 'circle') ?
            getFillFunc(symbol) :
            blankFillFunc;

    var fillText = subTypes.hasText(trace) ?
            getFillFunc(text) :
            blankFillFunc;

    var features = [];

    for(var i = 0; i < calcTrace.length; i++) {
        var calcPt = calcTrace[i];

        if(isBADNUM(calcPt.lonlat)) continue;

        features.push({
            type: 'Feature',
            geometry: {
                type: 'Point',
                coordinates: calcPt.lonlat
            },
            properties: {
                symbol: fillSymbol(calcPt.mx),
                text: fillText(calcPt.tx)
            }
        });
    }

    return {
        type: 'FeatureCollection',
        features: features
    };
}

function getFillFunc(attr) {
    if(Lib.isArrayOrTypedArray(attr)) {
        return function(v) { return v; };
    }
    else if(attr) {
        return function() { return attr; };
    }
    else {
        return blankFillFunc;
    }
}

function blankFillFunc() { return ''; }

// only need to check lon (OR lat)
function isBADNUM(lonlat) {
    return lonlat[0] === BADNUM;
}

},{"../../components/colorscale":58,"../../components/drawing":68,"../../constants/numerical":145,"../../lib":164,"../../lib/geojson_utils":160,"../../plots/mapbox/convert_text_opts":238,"../scatter/make_bubble_size_func":283,"../scatter/subtypes":288,"fast-isnumeric":9}],295:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');

var subTypes = require('../scatter/subtypes');
var handleMarkerDefaults = require('../scatter/marker_defaults');
var handleLineDefaults = require('../scatter/line_defaults');
var handleTextDefaults = require('../scatter/text_defaults');
var handleFillColorDefaults = require('../scatter/fillcolor_defaults');
var attributes = require('./attributes');

module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
    function coerce(attr, dflt) {
        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
    }

    var len = handleLonLatDefaults(traceIn, traceOut, coerce);
    if(!len) {
        traceOut.visible = false;
        return;
    }

    coerce('text');
    coerce('hovertext');
    coerce('mode');

    if(subTypes.hasLines(traceOut)) {
        handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noDash: true});
        coerce('connectgaps');
    }

    if(subTypes.hasMarkers(traceOut)) {
        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {noLine: true});

        // array marker.size and marker.color are only supported with circles

        var marker = traceOut.marker;
        // we need  mock marker.line object to make legends happy
        marker.line = {width: 0};

        if(marker.symbol !== 'circle') {
            if(Lib.isArrayOrTypedArray(marker.size)) marker.size = marker.size[0];
            if(Lib.isArrayOrTypedArray(marker.color)) marker.color = marker.color[0];
        }
    }

    if(subTypes.hasText(traceOut)) {
        handleTextDefaults(traceIn, traceOut, layout, coerce, {noSelect: true});
    }

    coerce('fill');
    if(traceOut.fill !== 'none') {
        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
    }

    Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
};

function handleLonLatDefaults(traceIn, traceOut, coerce) {
    var lon = coerce('lon') || [];
    var lat = coerce('lat') || [];
    var len = Math.min(lon.length, lat.length);
    traceOut._length = len;

    return len;
}

},{"../../lib":164,"../scatter/fillcolor_defaults":275,"../scatter/line_defaults":279,"../scatter/marker_defaults":284,"../scatter/subtypes":288,"../scatter/text_defaults":289,"./attributes":293}],296:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';


module.exports = function eventData(out, pt) {
    out.lon = pt.lon;
    out.lat = pt.lat;

    return out;
};

},{}],297:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/


'use strict';

var Fx = require('../../components/fx');
var Lib = require('../../lib');
var getTraceColor = require('../scatter/get_trace_color');
var fillHoverText = require('../scatter/fill_hover_text');
var BADNUM = require('../../constants/numerical').BADNUM;

module.exports = function hoverPoints(pointData, xval, yval) {
    var cd = pointData.cd;
    var trace = cd[0].trace;
    var xa = pointData.xa;
    var ya = pointData.ya;
    var subplot = pointData.subplot;

    // compute winding number about [-180, 180] globe
    var winding = (xval >= 0) ?
        Math.floor((xval + 180) / 360) :
        Math.ceil((xval - 180) / 360);

    // shift longitude to [-180, 180] to determine closest point
    var lonShift = winding * 360;
    var xval2 = xval - lonShift;

    function distFn(d) {
        var lonlat = d.lonlat;
        if(lonlat[0] === BADNUM) return Infinity;

        var lon = Lib.wrap180(lonlat[0]);
        var lat = lonlat[1];
        var pt = subplot.project([lon, lat]);
        var dx = pt.x - xa.c2p([xval2, lat]);
        var dy = pt.y - ya.c2p([lon, yval]);
        var rad = Math.max(3, d.mrc || 0);

        return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - 3 / rad);
    }

    Fx.getClosest(cd, distFn, pointData);

    // skip the rest (for this trace) if we didn't find a close point
    if(pointData.index === false) return;

    var di = cd[pointData.index];
    var lonlat = di.lonlat;
    var lonlatShifted = [Lib.wrap180(lonlat[0]) + lonShift, lonlat[1]];

    // shift labels back to original winded globe
    var xc = xa.c2p(lonlatShifted);
    var yc = ya.c2p(lonlatShifted);
    var rad = di.mrc || 1;

    pointData.x0 = xc - rad;
    pointData.x1 = xc + rad;
    pointData.y0 = yc - rad;
    pointData.y1 = yc + rad;

    pointData.color = getTraceColor(trace, di);
    pointData.extraText = getExtraText(trace, di, cd[0].t.labels);

    return [pointData];
};

function getExtraText(trace, di, labels) {
    var hoverinfo = di.hi || trace.hoverinfo;
    var parts = hoverinfo.split('+');
    var isAll = parts.indexOf('all') !== -1;
    var hasLon = parts.indexOf('lon') !== -1;
    var hasLat = parts.indexOf('lat') !== -1;
    var lonlat = di.lonlat;
    var text = [];

    // TODO should we use a mock axis to format hover?
    // If so, we'll need to make precision be zoom-level dependent
    function format(v) {
        return v + '\u00B0';
    }

    if(isAll || (hasLon && hasLat)) {
        text.push('(' + format(lonlat[0]) + ', ' + format(lonlat[1]) + ')');
    } else if(hasLon) {
        text.push(labels.lon + format(lonlat[0]));
    } else if(hasLat) {
        text.push(labels.lat + format(lonlat[1]));
    }

    if(isAll || parts.indexOf('text') !== -1) {
        fillHoverText(di, trace, text);
    }

    return text.join('<br>');
}

},{"../../components/fx":85,"../../constants/numerical":145,"../../lib":164,"../scatter/fill_hover_text":274,"../scatter/get_trace_color":276}],298:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';


var ScatterMapbox = {};

ScatterMapbox.attributes = require('./attributes');
ScatterMapbox.supplyDefaults = require('./defaults');
ScatterMapbox.colorbar = require('../scatter/colorbar');
ScatterMapbox.calc = require('../scattergeo/calc');
ScatterMapbox.plot = require('./plot');
ScatterMapbox.hoverPoints = require('./hover');
ScatterMapbox.eventData = require('./event_data');
ScatterMapbox.selectPoints = require('./select');

ScatterMapbox.style = function(_, cd) {
    if(cd) {
        var trace = cd[0].trace;
        trace._glTrace.update(cd);
    }
};

ScatterMapbox.moduleType = 'trace';
ScatterMapbox.name = 'scattermapbox';
ScatterMapbox.basePlotModule = require('../../plots/mapbox');
ScatterMapbox.categories = ['mapbox', 'gl', 'symbols', 'markerColorscale', 'showLegend', 'scatterlike'];
ScatterMapbox.meta = {
    
    
};

module.exports = ScatterMapbox;

},{"../../plots/mapbox":239,"../scatter/colorbar":270,"../scattergeo/calc":292,"./attributes":293,"./defaults":295,"./event_data":296,"./hover":297,"./plot":299,"./select":300}],299:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var convert = require('./convert');

function ScatterMapbox(subplot, uid) {
    this.subplot = subplot;
    this.uid = uid;

    this.sourceIds = {
        fill: uid + '-source-fill',
        line: uid + '-source-line',
        circle: uid + '-source-circle',
        symbol: uid + '-source-symbol'
    };

    this.layerIds = {
        fill: uid + '-layer-fill',
        line: uid + '-layer-line',
        circle: uid + '-layer-circle',
        symbol: uid + '-layer-symbol'
    };

    this.order = ['fill', 'line', 'circle', 'symbol'];

    // We could merge the 'fill' source with the 'line' source and
    // the 'circle' source with the 'symbol' source if ever having
    // for up-to 4 sources per 'scattermapbox' traces becomes a problem.
}

var proto = ScatterMapbox.prototype;

proto.addSource = function(k, opts) {
    this.subplot.map.addSource(this.sourceIds[k], {
        type: 'geojson',
        data: opts.geojson
    });
};

proto.setSourceData = function(k, opts) {
    this.subplot.map
        .getSource(this.sourceIds[k])
        .setData(opts.geojson);
};

proto.addLayer = function(k, opts) {
    this.subplot.map.addLayer({
        type: k,
        id: this.layerIds[k],
        source: this.sourceIds[k],
        layout: opts.layout,
        paint: opts.paint
    });
};

proto.update = function update(calcTrace) {
    var subplot = this.subplot;
    var optsAll = convert(calcTrace);

    for(var i = 0; i < this.order.length; i++) {
        var k = this.order[i];
        var opts = optsAll[k];

        subplot.setOptions(this.layerIds[k], 'setLayoutProperty', opts.layout);

        if(opts.layout.visibility === 'visible') {
            this.setSourceData(k, opts);
            subplot.setOptions(this.layerIds[k], 'setPaintProperty', opts.paint);
        }
    }

    // link ref for quick update during selections
    calcTrace[0].trace._glTrace = this;
};

proto.dispose = function dispose() {
    var map = this.subplot.map;

    for(var i = 0; i < this.order.length; i++) {
        var k = this.order[i];
        map.removeLayer(this.layerIds[k]);
        map.removeSource(this.sourceIds[k]);
    }
};

module.exports = function createScatterMapbox(subplot, calcTrace) {
    var trace = calcTrace[0].trace;
    var scatterMapbox = new ScatterMapbox(subplot, trace.uid);
    var optsAll = convert(calcTrace);

    for(var i = 0; i < scatterMapbox.order.length; i++) {
        var k = scatterMapbox.order[i];
        var opts = optsAll[k];

        scatterMapbox.addSource(k, opts);
        scatterMapbox.addLayer(k, opts);
    }

    // link ref for quick update during selections
    calcTrace[0].trace._glTrace = scatterMapbox;

    return scatterMapbox;
};

},{"./convert":294}],300:[function(require,module,exports){
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var Lib = require('../../lib');
var subtypes = require('../scatter/subtypes');
var BADNUM = require('../../constants/numerical').BADNUM;

module.exports = function selectPoints(searchInfo, polygon) {
    var cd = searchInfo.cd;
    var xa = searchInfo.xaxis;
    var ya = searchInfo.yaxis;
    var selection = [];
    var trace = cd[0].trace;
    var i;

    if(!subtypes.hasMarkers(trace)) return [];

    if(polygon === false) {
        for(i = 0; i < cd.length; i++) {
            cd[i].selected = 0;
        }
    } else {
        for(i = 0; i < cd.length; i++) {
            var di = cd[i];
            var lonlat = di.lonlat;

            if(lonlat[0] !== BADNUM) {
                var lonlat2 = [Lib.wrap180(lonlat[0]), lonlat[1]];
                var xy = [xa.c2p(lonlat2), ya.c2p(lonlat2)];

                if(polygon.contains(xy)) {
                    selection.push({
                        pointNumber: i,
                        lon: lonlat[0],
                        lat: lonlat[1]
                    });
                    di.selected = 1;
                } else {
                    di.selected = 0;
                }
            }
        }
    }

    return selection;
};

},{"../../constants/numerical":145,"../../lib":164,"../scatter/subtypes":288}]},{},[4])(4)
});