window.Bokeh = Bokeh = (function() { var define = undefined; return (function outer(modules, cache, entry) {
    function newRequire(name) {
        if (!cache[name]) {
            if (!modules[name]) {
                var err = new Error('Cannot find module \'' + name + '\'');
                err.code = 'MODULE_NOT_FOUND';
                throw err;
            }

            var m = cache[name] = {exports: {}};

            var moduleRequire = function foo(x) {
                var id = modules[name][1][x];
                return newRequire(id ? id : x);
            }
            moduleRequire.modules = newRequire.modules;

            modules[name][0].call(m.exports, moduleRequire, m, m.exports, outer, modules, cache, entry);
        }

        return cache[name].exports;
    }

    newRequire.modules = modules;

    var lastEntryResult = null;

    for (var i = 0; i < entry.length; i++) {
        lastEntryResult = newRequire(entry[i]);
    }

    return lastEntryResult;
})
({"api":[function(require,module,exports){
var _;

_ = require("underscore");

module.exports = {
  LinAlg: require("./api/linalg"),
  Charts: require("./api/charts"),
  Plotting: require("./api/plotting"),
  Document: require("./document").Document,
  sprintf: require("sprintf")
};

_.extend(module.exports, require("./api/models"));

},{"./api/charts":"api/charts","./api/linalg":"api/linalg","./api/models":"api/models","./api/plotting":"api/plotting","./document":"document","sprintf":"sprintf","underscore":"underscore"}],"api/charts":[function(require,module,exports){
var $, Document, _, bar, cumsum, embed, hexcolor2rgb, is_dark, models, num2hexcolor, palettes, pie, sprintf, sum;

_ = require("underscore");

$ = require("jquery");

sprintf = require("sprintf");

Document = require("../document").Document;

embed = require("../embed");

models = require("./models");

palettes = require("../palettes/palettes");

sum = function(array) {
  return array.reduce(((function(_this) {
    return function(a, b) {
      return a + b;
    };
  })(this)), 0);
};

cumsum = function(array) {
  var result;
  result = [];
  array.reduce((function(a, b, i) {
    return result[i] = a + b;
  }), 0);
  return result;
};

num2hexcolor = function(num) {
  return sprintf("#%06x", num);
};

hexcolor2rgb = function(color) {
  var b, g, r;
  r = parseInt(color.substr(1, 2), 16);
  g = parseInt(color.substr(3, 2), 16);
  b = parseInt(color.substr(5, 2), 16);
  return [r, g, b];
};

is_dark = function(arg) {
  var b, g, l, r;
  r = arg[0], g = arg[1], b = arg[2];
  l = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;
  return l >= 0.6;
};

pie = function(data, opts) {
  var angle_span, colors, cumulative_values, cx, cy, end_angle, end_angles, g1, g2, h1, half_angles, half_radius, hover, i, inner_radius, k, labels, normalized_values, outer_radius, palette, plot, r1, r2, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, source, start_angle, start_angles, text_angles, text_colors, text_cx, text_cy, to_cartesian, to_radians, tooltip, total_value, values, xdr, ydr;
  if (opts == null) {
    opts = {};
  }
  labels = [];
  values = [];
  for (i = k = 0, ref = Math.min(data.labels.length, data.values.length); 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
    if (data.values[i] > 0) {
      labels.push(data.labels[i]);
      values.push(data.values[i]);
    }
  }
  start_angle = (ref1 = opts.start_angle) != null ? ref1 : 0;
  end_angle = (ref2 = opts.end_angle) != null ? ref2 : start_angle + 2 * Math.PI;
  angle_span = Math.abs(end_angle - start_angle);
  to_radians = function(x) {
    return angle_span * x;
  };
  total_value = sum(values);
  normalized_values = values.map(function(v) {
    return v / total_value;
  });
  cumulative_values = cumsum(normalized_values);
  end_angles = cumulative_values.map(function(v) {
    return start_angle + to_radians(v);
  });
  start_angles = [start_angle].concat(end_angles.slice(0, -1));
  half_angles = _.zip(start_angles, end_angles).map((function(_this) {
    return function(arg) {
      var end, start;
      start = arg[0], end = arg[1];
      return (start + end) / 2;
    };
  })(this));
  if (opts.center == null) {
    cx = 0;
    cy = 0;
  } else if (_.isArray(opts.center)) {
    cx = opts.center[0];
    cy = opts.center[1];
  } else {
    cx = opts.center.x;
    cy = opts.center.y;
  }
  inner_radius = (ref3 = opts.inner_radius) != null ? ref3 : 0;
  outer_radius = (ref4 = opts.outer_radius) != null ? ref4 : 1;
  if (_.isArray(opts.palette)) {
    palette = opts.palette;
  } else {
    palette = palettes[(ref5 = opts.palette) != null ? ref5 : "Spectral11"].map(num2hexcolor);
  }
  colors = (function() {
    var m, ref6, results;
    results = [];
    for (i = m = 0, ref6 = normalized_values.length; 0 <= ref6 ? m < ref6 : m > ref6; i = 0 <= ref6 ? ++m : --m) {
      results.push(palette[i % palette.length]);
    }
    return results;
  })();
  text_colors = colors.map(function(c) {
    if (is_dark(hexcolor2rgb(c))) {
      return "white";
    } else {
      return "black";
    }
  });
  to_cartesian = function(r, alpha) {
    return [r * Math.cos(alpha), r * Math.sin(alpha)];
  };
  half_radius = (inner_radius + outer_radius) / 2;
  ref6 = _.unzip(half_angles.map((function(_this) {
    return function(half_angle) {
      return to_cartesian(half_radius, half_angle);
    };
  })(this))), text_cx = ref6[0], text_cy = ref6[1];
  text_cx = text_cx.map(function(x) {
    return x + cx;
  });
  text_cy = text_cy.map(function(y) {
    return y + cy;
  });
  text_angles = half_angles.map(function(a) {
    if (a >= Math.PI / 2 && a <= 3 * Math.PI / 2) {
      return a + Math.PI;
    } else {
      return a;
    }
  });
  source = new Bokeh.ColumnDataSource({
    data: {
      labels: labels,
      values: values,
      percentages: normalized_values.map((function(_this) {
        return function(v) {
          return sprintf("%.2f%%", v * 100);
        };
      })(this)),
      start_angles: start_angles,
      end_angles: end_angles,
      text_angles: text_angles,
      colors: colors,
      text_colors: text_colors,
      text_cx: text_cx,
      text_cy: text_cy
    }
  });
  g1 = new models.AnnularWedge({
    x: cx,
    y: cy,
    inner_radius: inner_radius,
    outer_radius: outer_radius,
    start_angle: {
      field: "start_angles"
    },
    end_angle: {
      field: "end_angles"
    },
    line_color: null,
    line_width: 1,
    fill_color: {
      field: "colors"
    }
  });
  h1 = new models.AnnularWedge({
    x: cx,
    y: cy,
    inner_radius: inner_radius,
    outer_radius: outer_radius,
    start_angle: {
      field: "start_angles"
    },
    end_angle: {
      field: "end_angles"
    },
    line_color: null,
    line_width: 1,
    fill_color: {
      field: "colors"
    },
    fill_alpha: 0.8
  });
  r1 = new models.GlyphRenderer({
    data_source: source,
    glyph: g1,
    hover_glyph: h1
  });
  g2 = new models.Text({
    x: {
      field: "text_cx"
    },
    y: {
      field: "text_cy"
    },
    text: {
      field: (ref7 = opts.slice_labels) != null ? ref7 : "labels"
    },
    angle: {
      field: "text_angles"
    },
    text_align: "center",
    text_baseline: "middle",
    text_color: {
      field: "text_colors"
    },
    text_font_size: "9pt"
  });
  r2 = new models.GlyphRenderer({
    data_source: source,
    glyph: g2
  });
  xdr = new models.DataRange1d({
    renderers: [r1],
    range_padding: 0.2
  });
  ydr = new models.DataRange1d({
    renderers: [r1],
    range_padding: 0.2
  });
  plot = new models.Plot({
    x_range: xdr,
    y_range: ydr
  });
  if (opts.width != null) {
    plot.plot_width = opts.width;
  }
  if (opts.height != null) {
    plot.plot_height = opts.height;
  }
  plot.add_renderers(r1, r2);
  tooltip = "<div>@labels</div><div><b>@values</b> (@percentages)</div>";
  hover = new models.HoverTool({
    renderers: [r1],
    tooltips: tooltip
  });
  plot.add_tools(hover);
  return plot;
};

bar = function(data, opts) {
  var anchor, attachment, bottom, column_names, columns, dy, g1, hover, i, j, k, label, labels, left, len, len1, len2, len3, len4, m, n, name, o, orientation, p, palette, plot, q, r, r1, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, renderers, right, row, rows, s, source, stacked, tooltip, top, v, xaxis, xdr, xformatter, yaxis, ydr;
  if (opts == null) {
    opts = {};
  }
  column_names = data[0];
  rows = data.slice(1);
  columns = (function() {
    var k, len, results;
    results = [];
    for (k = 0, len = column_names.length; k < len; k++) {
      name = column_names[k];
      results.push([]);
    }
    return results;
  })();
  for (k = 0, len = rows.length; k < len; k++) {
    row = rows[k];
    for (i = m = 0, len1 = row.length; m < len1; i = ++m) {
      v = row[i];
      columns[i].push(v);
    }
  }
  labels = _.map(columns[0], function(v) {
    return v.toString();
  });
  columns = columns.slice(1);
  yaxis = new models.CategoricalAxis();
  ydr = new models.FactorRange({
    factors: labels
  });
  if (opts.axis_number_format != null) {
    xformatter = new models.NumeralTickFormatter({
      format: opts.axis_number_format
    });
  } else {
    xformatter = new models.BasicTickFormatter();
  }
  xaxis = new models.LinearAxis({
    formatter: xformatter
  });
  xdr = new models.DataRange1d({
    start: 0
  });
  if (_.isArray(opts.palette)) {
    palette = opts.palette;
  } else {
    palette = palettes[(ref = opts.palette) != null ? ref : "Spectral11"].map(num2hexcolor);
  }
  stacked = (ref1 = opts.stacked) != null ? ref1 : false;
  orientation = (ref2 = opts.orientation) != null ? ref2 : "horizontal";
  renderers = [];
  if (stacked) {
    left = [];
    right = [];
    for (i = n = 0, ref3 = columns.length; 0 <= ref3 ? n < ref3 : n > ref3; i = 0 <= ref3 ? ++n : --n) {
      bottom = [];
      top = [];
      for (j = o = 0, len2 = labels.length; o < len2; j = ++o) {
        label = labels[j];
        if (i === 0) {
          left.push(0);
          right.push(columns[i][j]);
        } else {
          left[j] += columns[i - 1][j];
          right[j] += columns[i][j];
        }
        bottom.push(label + ":0");
        top.push(label + ":1");
      }
      source = new Bokeh.ColumnDataSource({
        data: {
          left: _.clone(left),
          right: _.clone(right),
          top: top,
          bottom: bottom,
          labels: labels,
          values: columns[i],
          columns: (function() {
            var len3, p, ref4, results;
            ref4 = columns[i];
            results = [];
            for (p = 0, len3 = ref4.length; p < len3; p++) {
              v = ref4[p];
              results.push(column_names[i + 1]);
            }
            return results;
          })()
        }
      });
      g1 = new models.Quad({
        left: {
          field: "left"
        },
        bottom: {
          field: "bottom"
        },
        right: {
          field: "right"
        },
        top: {
          field: "top"
        },
        line_color: null,
        fill_color: palette[i % palette.length]
      });
      r1 = new models.GlyphRenderer({
        data_source: source,
        glyph: g1
      });
      renderers.push(r1);
    }
  } else {
    dy = 1 / columns.length;
    for (i = p = 0, ref4 = columns.length; 0 <= ref4 ? p < ref4 : p > ref4; i = 0 <= ref4 ? ++p : --p) {
      left = [];
      right = [];
      bottom = [];
      top = [];
      for (j = q = 0, len3 = labels.length; q < len3; j = ++q) {
        label = labels[j];
        left.push(0);
        right.push(columns[i][j]);
        bottom.push(label + ":" + (i * dy));
        top.push(label + ":" + ((i + 1) * dy));
      }
      source = new Bokeh.ColumnDataSource({
        data: {
          left: left,
          right: right,
          top: top,
          bottom: bottom,
          labels: labels,
          values: columns[i],
          columns: (function() {
            var len4, ref5, results, s;
            ref5 = columns[i];
            results = [];
            for (s = 0, len4 = ref5.length; s < len4; s++) {
              v = ref5[s];
              results.push(column_names[i + 1]);
            }
            return results;
          })()
        }
      });
      g1 = new models.Quad({
        left: {
          field: "left"
        },
        bottom: {
          field: "bottom"
        },
        right: {
          field: "right"
        },
        top: {
          field: "top"
        },
        line_color: null,
        fill_color: palette[i % palette.length]
      });
      r1 = new models.GlyphRenderer({
        data_source: source,
        glyph: g1
      });
      renderers.push(r1);
    }
  }
  if (orientation === "vertical") {
    ref5 = [ydr, xdr], xdr = ref5[0], ydr = ref5[1];
    ref6 = [yaxis, xaxis], xaxis = ref6[0], yaxis = ref6[1];
    for (s = 0, len4 = renderers.length; s < len4; s++) {
      r = renderers[s];
      data = r.data_source.data;
      ref7 = [data.bottom, data.left], data.left = ref7[0], data.bottom = ref7[1];
      ref8 = [data.top, data.right], data.right = ref8[0], data.top = ref8[1];
    }
  }
  plot = new models.Plot({
    x_range: xdr,
    y_range: ydr
  });
  if (opts.width != null) {
    plot.plot_width = opts.width;
  }
  if (opts.height != null) {
    plot.plot_height = opts.height;
  }
  plot.add_renderers.apply(plot, renderers);
  plot.add_layout(yaxis, "left");
  plot.add_layout(xaxis, "below");
  tooltip = "<div>@labels</div><div>@columns:&nbsp<b>@values</b></div>";
  if (orientation === "horizontal") {
    anchor = "right_center";
    attachment = "horizontal";
  } else {
    anchor = "top_center";
    attachment = "vertical";
  }
  hover = new models.HoverTool({
    renderers: renderers,
    tooltips: tooltip,
    point_policy: "snap_to_data",
    anchor: anchor,
    attachment: attachment
  });
  plot.add_tools(hover);
  return plot;
};

module.exports = {
  pie: pie,
  bar: bar
};

},{"../document":"document","../embed":"embed","../palettes/palettes":"palettes/palettes","./models":"api/models","jquery":"jquery","sprintf":"sprintf","underscore":"underscore"}],"api/linalg":[function(require,module,exports){
"use strict";
function transpose(array) {
    var rows = array.length;
    var cols = array[0].length;
    var transposed = [];
    for (var j = 0; j < cols; j++) {
        transposed[j] = [];
        for (var i = 0; i < rows; i++) {
            transposed[j][i] = array[i][j];
        }
    }
    return transposed;
}
exports.transpose = transpose;
function linspace(start, stop, num) {
    if (num === void 0) { num = 100; }
    var step = (stop - start) / (num - 1);
    var array = new Array(num);
    for (var i = 0; i < num; i++) {
        array[i] = start + step * i;
    }
    return array;
}
exports.linspace = linspace;
function arange(start, stop, step) {
    if (step === void 0) { step = 1; }
    var num = Math.ceil((stop - start) / step);
    var array = new Array(num);
    for (var i = 0; i < num; i++) {
        array[i] = start + step * i;
    }
    return array;
}
exports.arange = arange;

},{}],"api/models":[function(require,module,exports){
module.exports = {
  Arrow: require("../models/annotations/arrow").Model,
  OpenHead: require("../models/annotations/arrow_head").OpenHead,
  NormalHead: require("../models/annotations/arrow_head").NormalHead,
  VeeHead: require("../models/annotations/arrow_head").VeeHead,
  BoxAnnotation: require("../models/annotations/box_annotation").Model,
  Label: require("../models/annotations/label").Model,
  LabelSet: require("../models/annotations/label_set").Model,
  Legend: require("../models/annotations/legend").Model,
  PolyAnnotation: require("../models/annotations/poly_annotation").Model,
  Span: require("../models/annotations/span").Model,
  Title: require("../models/annotations/title").Model,
  Tooltip: require("../models/annotations/tooltip").Model,
  Axis: require("../models/axes/axis").Model,
  ContinuousAxis: require("../models/axes/continuous_axis").Model,
  LinearAxis: require("../models/axes/linear_axis").Model,
  LogAxis: require("../models/axes/log_axis").Model,
  CategoricalAxis: require("../models/axes/categorical_axis").Model,
  DatetimeAxis: require("../models/axes/datetime_axis").Model,
  OpenURL: require("../models/callbacks/open_url").Model,
  CustomJS: require("../models/callbacks/customjs").Model,
  TickFormatter: require("../models/formatters/tick_formatter").Model,
  BasicTickFormatter: require("../models/formatters/basic_tick_formatter").Model,
  LogTickFormatter: require("../models/formatters/basic_tick_formatter").Model,
  CategoricalTickFormatter: require("../models/formatters/categorical_tick_formatter").Model,
  DatetimeTickFormatter: require("../models/formatters/datetime_tick_formatter").Model,
  FuncTickFormatter: require("../models/formatters/func_tick_formatter").Model,
  NumeralTickFormatter: require("../models/formatters/numeral_tick_formatter").Model,
  PrintfTickFormatter: require("../models/formatters/printf_tick_formatter").Model,
  Glyph: require("../models/glyphs/glyph").Model,
  AnnularWedge: require("../models/glyphs/annular_wedge").Model,
  Annulus: require("../models/glyphs/annulus").Model,
  Arc: require("../models/glyphs/arc").Model,
  Bezier: require("../models/glyphs/bezier").Model,
  Ellipse: require("../models/glyphs/ellipse").Model,
  ImageRGBA: require("../models/glyphs/image_rgba").Model,
  Image: require("../models/glyphs/image").Model,
  ImageURL: require("../models/glyphs/image_url").Model,
  Line: require("../models/glyphs/line").Model,
  MultiLine: require("../models/glyphs/multi_line").Model,
  Oval: require("../models/glyphs/oval").Model,
  Patch: require("../models/glyphs/patch").Model,
  Patches: require("../models/glyphs/patches").Model,
  Quad: require("../models/glyphs/quad").Model,
  Quadratic: require("../models/glyphs/quadratic").Model,
  Ray: require("../models/glyphs/ray").Model,
  Rect: require("../models/glyphs/rect").Model,
  Segment: require("../models/glyphs/segment").Model,
  Text: require("../models/glyphs/text").Model,
  Wedge: require("../models/glyphs/wedge").Model,
  Gear: require("../models/glyphs/gear").Model,
  Grid: require("../models/grids/grid").Model,
  ImageSource: require("../models/tiles/image_source").Model,
  LayoutDOM: require("../models/layouts/layout_dom").Model,
  Row: require("../models/layouts/row").Model,
  Column: require("../models/layouts/column").Model,
  Spacer: require("../models/layouts/spacer").Model,
  WidgetBox: require("../models/layouts/widget_box").Model,
  GMapPlot: require("../models/plots/gmap_plot").Model,
  LinearColorMapper: require("../models/mappers/linear_color_mapper").Model,
  Marker: require("../models/markers/marker").Model,
  Asterisk: require("../models/markers/asterisk").Model,
  Circle: require("../models/glyphs/circle").Model,
  CircleCross: require("../models/markers/circle_cross").Model,
  CircleX: require("../models/markers/circle_x").Model,
  Cross: require("../models/markers/cross").Model,
  Diamond: require("../models/markers/diamond").Model,
  DiamondCross: require("../models/markers/diamond_cross").Model,
  InvertedTriangle: require("../models/markers/inverted_triangle").Model,
  Square: require("../models/markers/square").Model,
  SquareCross: require("../models/markers/square_cross").Model,
  SquareX: require("../models/markers/square_x").Model,
  Triangle: require("../models/markers/triangle").Model,
  X: require("../models/markers/x").Model,
  Model: require("../model").Model,
  Plot: require("../models/plots/plot").Model,
  Range: require("../models/ranges/range").Model,
  Range1d: require("../models/ranges/range1d").Model,
  DataRange: require("../models/ranges/data_range").Model,
  DataRange1d: require("../models/ranges/data_range1d").Model,
  FactorRange: require("../models/ranges/factor_range").Model,
  Renderer: require("../models/renderers/renderer").Model,
  TileRenderer: require("../models/tiles/tile_renderer").Model,
  DynamicImageRenderer: require("../models/tiles/dynamic_image_renderer").Model,
  GlyphRenderer: require("../models/renderers/glyph_renderer").Model,
  GuideRenderer: require("../models/renderers/guide_renderer").Model,
  DataSource: require("../models/sources/data_source").Model,
  ColumnDataSource: require("../models/sources/column_data_source").Model,
  AjaxDataSource: require("../models/sources/ajax_data_source").Model,
  Ticker: require("../models/tickers/ticker").Model,
  ContinuousTicker: require("../models/tickers/continuous_ticker").Model,
  FixedTicker: require("../models/tickers/fixed_ticker").Model,
  AdaptiveTicker: require("../models/tickers/adaptive_ticker").Model,
  CompositeTicker: require("../models/tickers/composite_ticker").Model,
  SingleIntervalTicker: require("../models/tickers/single_interval_ticker").Model,
  DaysTicker: require("../models/tickers/days_ticker").Model,
  MonthsTicker: require("../models/tickers/months_ticker").Model,
  YearsTicker: require("../models/tickers/years_ticker").Model,
  BasicTicker: require("../models/tickers/basic_ticker").Model,
  LogTicker: require("../models/tickers/log_ticker").Model,
  CategoricalTicker: require("../models/tickers/categorical_ticker").Model,
  DatetimeTicker: require("../models/tickers/datetime_ticker").Model,
  TileSource: require("../models/tiles/tile_source").Model,
  MercatorTileSource: require("../models/tiles/mercator_tile_source").Model,
  TMSTileSource: require("../models/tiles/tms_tile_source").Model,
  WMTSTileSource: require("../models/tiles/wmts_tile_source").Model,
  QUADKEYTileSource: require("../models/tiles/quadkey_tile_source").Model,
  BBoxTileSource: require("../models/tiles/bbox_tile_source").Model,
  ToolbarBase: require("../models/tools/toolbar_base").Model,
  Toolbar: require("../models/tools/toolbar").Model,
  ToolbarBox: require("../models/tools/toolbar_box").Model,
  ToolEvents: require("../common/tool_events").Model,
  Tool: require("../models/tools/tool").Model,
  PanTool: require("../models/tools/gestures/pan_tool").Model,
  WheelZoomTool: require("../models/tools/gestures/wheel_zoom_tool").Model,
  SaveTool: require("../models/tools/actions/save_tool").Model,
  UndoTool: require("../models/tools/actions/undo_tool").Model,
  RedoTool: require("../models/tools/actions/redo_tool").Model,
  ResetTool: require("../models/tools/actions/reset_tool").Model,
  ResizeTool: require("../models/tools/gestures/resize_tool").Model,
  CrosshairTool: require("../models/tools/inspectors/crosshair_tool").Model,
  BoxZoomTool: require("../models/tools/gestures/box_zoom_tool").Model,
  BoxSelectTool: require("../models/tools/gestures/box_select_tool").Model,
  LassoSelectTool: require("../models/tools/gestures/lasso_select_tool").Model,
  PolySelectTool: require("../models/tools/gestures/poly_select_tool").Model,
  TapTool: require("../models/tools/gestures/tap_tool").Model,
  HoverTool: require("../models/tools/inspectors/hover_tool").Model,
  HelpTool: require("../models/tools/actions/help_tool").Model
};

},{"../common/tool_events":"common/tool_events","../model":"model","../models/annotations/arrow":"models/annotations/arrow","../models/annotations/arrow_head":"models/annotations/arrow_head","../models/annotations/box_annotation":"models/annotations/box_annotation","../models/annotations/label":"models/annotations/label","../models/annotations/label_set":"models/annotations/label_set","../models/annotations/legend":"models/annotations/legend","../models/annotations/poly_annotation":"models/annotations/poly_annotation","../models/annotations/span":"models/annotations/span","../models/annotations/title":"models/annotations/title","../models/annotations/tooltip":"models/annotations/tooltip","../models/axes/axis":"models/axes/axis","../models/axes/categorical_axis":"models/axes/categorical_axis","../models/axes/continuous_axis":"models/axes/continuous_axis","../models/axes/datetime_axis":"models/axes/datetime_axis","../models/axes/linear_axis":"models/axes/linear_axis","../models/axes/log_axis":"models/axes/log_axis","../models/callbacks/customjs":"models/callbacks/customjs","../models/callbacks/open_url":"models/callbacks/open_url","../models/formatters/basic_tick_formatter":"models/formatters/basic_tick_formatter","../models/formatters/categorical_tick_formatter":"models/formatters/categorical_tick_formatter","../models/formatters/datetime_tick_formatter":"models/formatters/datetime_tick_formatter","../models/formatters/func_tick_formatter":"models/formatters/func_tick_formatter","../models/formatters/numeral_tick_formatter":"models/formatters/numeral_tick_formatter","../models/formatters/printf_tick_formatter":"models/formatters/printf_tick_formatter","../models/formatters/tick_formatter":"models/formatters/tick_formatter","../models/glyphs/annular_wedge":"models/glyphs/annular_wedge","../models/glyphs/annulus":"models/glyphs/annulus","../models/glyphs/arc":"models/glyphs/arc","../models/glyphs/bezier":"models/glyphs/bezier","../models/glyphs/circle":"models/glyphs/circle","../models/glyphs/ellipse":"models/glyphs/ellipse","../models/glyphs/gear":"models/glyphs/gear","../models/glyphs/glyph":"models/glyphs/glyph","../models/glyphs/image":"models/glyphs/image","../models/glyphs/image_rgba":"models/glyphs/image_rgba","../models/glyphs/image_url":"models/glyphs/image_url","../models/glyphs/line":"models/glyphs/line","../models/glyphs/multi_line":"models/glyphs/multi_line","../models/glyphs/oval":"models/glyphs/oval","../models/glyphs/patch":"models/glyphs/patch","../models/glyphs/patches":"models/glyphs/patches","../models/glyphs/quad":"models/glyphs/quad","../models/glyphs/quadratic":"models/glyphs/quadratic","../models/glyphs/ray":"models/glyphs/ray","../models/glyphs/rect":"models/glyphs/rect","../models/glyphs/segment":"models/glyphs/segment","../models/glyphs/text":"models/glyphs/text","../models/glyphs/wedge":"models/glyphs/wedge","../models/grids/grid":"models/grids/grid","../models/layouts/column":"models/layouts/column","../models/layouts/layout_dom":"models/layouts/layout_dom","../models/layouts/row":"models/layouts/row","../models/layouts/spacer":"models/layouts/spacer","../models/layouts/widget_box":"models/layouts/widget_box","../models/mappers/linear_color_mapper":"models/mappers/linear_color_mapper","../models/markers/asterisk":"models/markers/asterisk","../models/markers/circle_cross":"models/markers/circle_cross","../models/markers/circle_x":"models/markers/circle_x","../models/markers/cross":"models/markers/cross","../models/markers/diamond":"models/markers/diamond","../models/markers/diamond_cross":"models/markers/diamond_cross","../models/markers/inverted_triangle":"models/markers/inverted_triangle","../models/markers/marker":"models/markers/marker","../models/markers/square":"models/markers/square","../models/markers/square_cross":"models/markers/square_cross","../models/markers/square_x":"models/markers/square_x","../models/markers/triangle":"models/markers/triangle","../models/markers/x":"models/markers/x","../models/plots/gmap_plot":"models/plots/gmap_plot","../models/plots/plot":"models/plots/plot","../models/ranges/data_range":"models/ranges/data_range","../models/ranges/data_range1d":"models/ranges/data_range1d","../models/ranges/factor_range":"models/ranges/factor_range","../models/ranges/range":"models/ranges/range","../models/ranges/range1d":"models/ranges/range1d","../models/renderers/glyph_renderer":"models/renderers/glyph_renderer","../models/renderers/guide_renderer":"models/renderers/guide_renderer","../models/renderers/renderer":"models/renderers/renderer","../models/sources/ajax_data_source":"models/sources/ajax_data_source","../models/sources/column_data_source":"models/sources/column_data_source","../models/sources/data_source":"models/sources/data_source","../models/tickers/adaptive_ticker":"models/tickers/adaptive_ticker","../models/tickers/basic_ticker":"models/tickers/basic_ticker","../models/tickers/categorical_ticker":"models/tickers/categorical_ticker","../models/tickers/composite_ticker":"models/tickers/composite_ticker","../models/tickers/continuous_ticker":"models/tickers/continuous_ticker","../models/tickers/datetime_ticker":"models/tickers/datetime_ticker","../models/tickers/days_ticker":"models/tickers/days_ticker","../models/tickers/fixed_ticker":"models/tickers/fixed_ticker","../models/tickers/log_ticker":"models/tickers/log_ticker","../models/tickers/months_ticker":"models/tickers/months_ticker","../models/tickers/single_interval_ticker":"models/tickers/single_interval_ticker","../models/tickers/ticker":"models/tickers/ticker","../models/tickers/years_ticker":"models/tickers/years_ticker","../models/tiles/bbox_tile_source":"models/tiles/bbox_tile_source","../models/tiles/dynamic_image_renderer":"models/tiles/dynamic_image_renderer","../models/tiles/image_source":"models/tiles/image_source","../models/tiles/mercator_tile_source":"models/tiles/mercator_tile_source","../models/tiles/quadkey_tile_source":"models/tiles/quadkey_tile_source","../models/tiles/tile_renderer":"models/tiles/tile_renderer","../models/tiles/tile_source":"models/tiles/tile_source","../models/tiles/tms_tile_source":"models/tiles/tms_tile_source","../models/tiles/wmts_tile_source":"models/tiles/wmts_tile_source","../models/tools/actions/help_tool":"models/tools/actions/help_tool","../models/tools/actions/redo_tool":"models/tools/actions/redo_tool","../models/tools/actions/reset_tool":"models/tools/actions/reset_tool","../models/tools/actions/save_tool":"models/tools/actions/save_tool","../models/tools/actions/undo_tool":"models/tools/actions/undo_tool","../models/tools/gestures/box_select_tool":"models/tools/gestures/box_select_tool","../models/tools/gestures/box_zoom_tool":"models/tools/gestures/box_zoom_tool","../models/tools/gestures/lasso_select_tool":"models/tools/gestures/lasso_select_tool","../models/tools/gestures/pan_tool":"models/tools/gestures/pan_tool","../models/tools/gestures/poly_select_tool":"models/tools/gestures/poly_select_tool","../models/tools/gestures/resize_tool":"models/tools/gestures/resize_tool","../models/tools/gestures/tap_tool":"models/tools/gestures/tap_tool","../models/tools/gestures/wheel_zoom_tool":"models/tools/gestures/wheel_zoom_tool","../models/tools/inspectors/crosshair_tool":"models/tools/inspectors/crosshair_tool","../models/tools/inspectors/hover_tool":"models/tools/inspectors/hover_tool","../models/tools/tool":"models/tools/tool","../models/tools/toolbar":"models/tools/toolbar","../models/tools/toolbar_base":"models/tools/toolbar_base","../models/tools/toolbar_box":"models/tools/toolbar_box"}],"api/plotting":[function(require,module,exports){
var $, BOKEH_ROOT, Document, Figure, _, _default_tools, _default_tooltips, _known_tools, _with_default, color, embed, figure, gridplot, models, show, sprintf,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  slice = [].slice;

_ = require("underscore");

$ = require("jquery");

sprintf = require("sprintf");

Document = require("../document").Document;

embed = require("../embed");

BOKEH_ROOT = require("../embed").BOKEH_ROOT;

models = require("./models");

_default_tooltips = [["index", "$index"], ["data (x, y)", "($x, $y)"], ["canvas (x, y)", "($sx, $sy)"]];

_default_tools = "pan,wheel_zoom,box_zoom,save,reset,help";

_known_tools = {
  pan: function(plot) {
    return new models.PanTool({
      plot: plot,
      dimensions: ["width", "height"]
    });
  },
  xpan: function(plot) {
    return new models.PanTool({
      plot: plot,
      dimensions: ["width"]
    });
  },
  ypan: function(plot) {
    return new models.PanTool({
      plot: plot,
      dimensions: ["height"]
    });
  },
  wheel_zoom: function(plot) {
    return new models.WheelZoomTool({
      plot: plot,
      dimensions: ["width", "height"]
    });
  },
  xwheel_zoom: function(plot) {
    return new models.WheelZoomTool({
      plot: plot,
      dimensions: ["width"]
    });
  },
  ywheel_zoom: function(plot) {
    return new models.WheelZoomTool({
      plot: plot,
      dimensions: ["height"]
    });
  },
  resize: function(plot) {
    return new models.ResizeTool({
      plot: plot
    });
  },
  click: function(plot) {
    return new models.TapTool({
      plot: plot,
      behavior: "inspect"
    });
  },
  tap: function(plot) {
    return new models.TapTool({
      plot: plot
    });
  },
  crosshair: function(plot) {
    return new models.CrosshairTool({
      plot: plot
    });
  },
  box_select: function(plot) {
    return new models.BoxSelectTool({
      plot: plot
    });
  },
  xbox_select: function(plot) {
    return new models.BoxSelectTool({
      plot: plot,
      dimensions: ['width']
    });
  },
  ybox_select: function(plot) {
    return new models.BoxSelectTool({
      plot: plot,
      dimensions: ['height']
    });
  },
  poly_select: function(plot) {
    return new models.PolySelectTool({
      plot: plot
    });
  },
  lasso_select: function(plot) {
    return new models.LassoSelectTool({
      plot: plot
    });
  },
  box_zoom: function(plot) {
    return new models.BoxZoomTool({
      plot: plot,
      dimensions: ['width', 'height']
    });
  },
  xbox_zoom: function(plot) {
    return new models.BoxZoomTool({
      plot: plot,
      dimensions: ['width']
    });
  },
  ybox_zoom: function(plot) {
    return new models.BoxZoomTool({
      plot: plot,
      dimensions: ['height']
    });
  },
  hover: function(plot) {
    return new models.HoverTool({
      plot: plot,
      tooltips: _default_tooltips
    });
  },
  save: function(plot) {
    return new models.SaveTool({
      plot: plot
    });
  },
  previewsave: function(plot) {
    return new models.SaveTool({
      plot: plot
    });
  },
  undo: function(plot) {
    return new models.UndoTool({
      plot: plot
    });
  },
  redo: function(plot) {
    return new models.RedoTool({
      plot: plot
    });
  },
  reset: function(plot) {
    return new models.ResetTool({
      plot: plot
    });
  },
  help: function(plot) {
    return new models.HelpTool({
      plot: plot
    });
  }
};

_with_default = function(value, default_value) {
  if (value === void 0) {
    return default_value;
  } else {
    return value;
  }
};

Figure = (function(superClass) {
  extend(Figure, superClass);

  function Figure(attributes, options) {
    var attrs, ref, ref1, ref2, ref3, ref4, ref5, tools, x_axis_label, x_axis_location, x_axis_type, x_minor_ticks, y_axis_label, y_axis_location, y_axis_type, y_minor_ticks;
    if (attributes == null) {
      attributes = {};
    }
    if (options == null) {
      options = {};
    }
    attrs = _.clone(attributes);
    tools = _with_default(attrs.tools, _default_tools);
    delete attrs.tools;
    attrs.x_range = this._get_range(attrs.x_range);
    attrs.y_range = this._get_range(attrs.y_range);
    x_axis_type = _.isUndefined(attrs.x_axis_type) ? "auto" : attrs.x_axis_type;
    y_axis_type = _.isUndefined(attrs.y_axis_type) ? "auto" : attrs.y_axis_type;
    delete attrs.x_axis_type;
    delete attrs.y_axis_type;
    x_minor_ticks = (ref = attrs.x_minor_ticks) != null ? ref : "auto";
    y_minor_ticks = (ref1 = attrs.y_minor_ticks) != null ? ref1 : "auto";
    delete attrs.x_minor_ticks;
    delete attrs.y_minor_ticks;
    x_axis_location = (ref2 = attrs.x_axis_location) != null ? ref2 : "below";
    y_axis_location = (ref3 = attrs.y_axis_location) != null ? ref3 : "left";
    delete attrs.x_axis_location;
    delete attrs.y_axis_location;
    x_axis_label = (ref4 = attrs.x_axis_label) != null ? ref4 : "";
    y_axis_label = (ref5 = attrs.y_axis_label) != null ? ref5 : "";
    delete attrs.x_axis_label;
    delete attrs.y_axis_label;
    if (!_.isUndefined(attrs.width)) {
      if (_.isUndefined(attrs.plot_width)) {
        attrs.plot_width = attrs.width;
      } else {
        throw new Error("both 'width' and 'plot_width' can't be given at the same time");
      }
      delete attrs.width;
    }
    if (!_.isUndefined(attrs.height)) {
      if (_.isUndefined(attrs.plot_height)) {
        attrs.plot_height = attrs.height;
      } else {
        throw new Error("both 'height' and 'plot_height' can't be given at the same time");
      }
      delete attrs.height;
    }
    Figure.__super__.constructor.call(this, attrs, options);
    this._process_guides(0, x_axis_type, x_axis_location, x_minor_ticks, x_axis_label);
    this._process_guides(1, y_axis_type, y_axis_location, y_minor_ticks, y_axis_label);
    this.add_tools.apply(this, this._process_tools(tools));
    this._legend = new models.Legend({
      plot: this
    });
    this.add_renderers(this._legend);
  }

  Object.defineProperty(Figure.prototype, "xgrid", {
    get: function() {
      return this.renderers.filter(function(r) {
        return r instanceof models.Grid && r.dimension === 0;
      })[0];
    }
  });

  Object.defineProperty(Figure.prototype, "ygrid", {
    get: function() {
      return this.renderers.filter(function(r) {
        return r instanceof models.Grid && r.dimension === 1;
      })[0];
    }
  });

  Object.defineProperty(Figure.prototype, "xaxis", {
    get: function() {
      return this.below.concat(this.above).filter(function(r) {
        return r instanceof models.Axis;
      })[0];
    }
  });

  Object.defineProperty(Figure.prototype, "yaxis", {
    get: function() {
      return this.left.concat(this.right).filter(function(r) {
        return r instanceof models.Axis;
      })[0];
    }
  });

  Figure.prototype.annular_wedge = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.AnnularWedge, "x,y,inner_radius,outer_radius,start_angle,end_angle", args);
  };

  Figure.prototype.annulus = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Annulus, "x,y,inner_radius,outer_radius", args);
  };

  Figure.prototype.arc = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Arc, "x,y,radius,start_angle,end_angle", args);
  };

  Figure.prototype.bezier = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Bezier, "x0,y0,x1,y1,cx0,cy0,cx1,cy1", args);
  };

  Figure.prototype.ellipse = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Ellipse, "x,y,width,height", args);
  };

  Figure.prototype.gear = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Gear, "x,y,module,teeth", args);
  };

  Figure.prototype.image = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Image, "color_mapper,image,rows,cols,x,y,dw,dh", args);
  };

  Figure.prototype.image_rgba = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.ImageRGBA, "image,rows,cols,x,y,dw,dh", args);
  };

  Figure.prototype.image_url = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.ImageURL, "url,x,y,w,h", args);
  };

  Figure.prototype.line = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Line, "x,y", args);
  };

  Figure.prototype.multi_line = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.MultiLine, "xs,ys", args);
  };

  Figure.prototype.oval = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Oval, "x,y,width,height", args);
  };

  Figure.prototype.patch = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Patch, "x,y", args);
  };

  Figure.prototype.patches = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Patches, "xs,ys", args);
  };

  Figure.prototype.quad = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Quad, "left,right,bottom,top", args);
  };

  Figure.prototype.quadratic = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Quadratic, "x0,y0,x1,y1,cx,cy", args);
  };

  Figure.prototype.ray = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Ray, "x,y,length", args);
  };

  Figure.prototype.rect = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Rect, "x,y,width,height", args);
  };

  Figure.prototype.segment = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Segment, "x0,y0,x1,y1", args);
  };

  Figure.prototype.text = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Text, "x,y,text", args);
  };

  Figure.prototype.wedge = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._glyph(models.Wedge, "x,y,radius,start_angle,end_angle", args);
  };

  Figure.prototype.asterisk = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.Asterisk, args);
  };

  Figure.prototype.circle = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.Circle, args);
  };

  Figure.prototype.circle_cross = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.CircleCross, args);
  };

  Figure.prototype.circle_x = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.CircleX, args);
  };

  Figure.prototype.cross = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.Cross, args);
  };

  Figure.prototype.diamond = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.Diamond, args);
  };

  Figure.prototype.diamond_cross = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.DiamondCross, args);
  };

  Figure.prototype.inverted_triangle = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.InvertedTriangle, args);
  };

  Figure.prototype.square = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.Square, args);
  };

  Figure.prototype.square_cross = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.SquareCross, args);
  };

  Figure.prototype.square_x = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.SquareX, args);
  };

  Figure.prototype.triangle = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.Triangle, args);
  };

  Figure.prototype.x = function() {
    var args;
    args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    return this._marker(models.X, args);
  };

  Figure.prototype._vectorable = ["fill_color", "fill_alpha", "line_color", "line_alpha", "line_width", "text_color", "text_alpha", "text_font_size"];

  Figure.prototype._default_color = "#1f77b4";

  Figure.prototype._default_alpha = 1.0;

  Figure.prototype._pop_colors_and_alpha = function(cls, attrs, prefix, default_color, default_alpha) {
    var _update_with, alpha, color, result;
    if (prefix == null) {
      prefix = "";
    }
    if (default_color == null) {
      default_color = this._default_color;
    }
    if (default_alpha == null) {
      default_alpha = this._default_alpha;
    }
    result = {};
    color = _with_default(attrs[prefix + "color"], default_color);
    alpha = _with_default(attrs[prefix + "alpha"], default_alpha);
    delete attrs[prefix + "color"];
    delete attrs[prefix + "alpha"];
    _update_with = function(name, default_value) {
      if (cls.prototype.props[name] != null) {
        result[name] = _with_default(attrs[prefix + name], default_value);
        return delete attrs[prefix + name];
      }
    };
    _update_with("fill_color", color);
    _update_with("line_color", color);
    _update_with("text_color", "black");
    _update_with("fill_alpha", alpha);
    _update_with("line_alpha", alpha);
    _update_with("text_alpha", alpha);
    return result;
  };

  Figure.prototype._find_uniq_name = function(data, name) {
    var i, new_name;
    i = 1;
    while (true) {
      new_name = name + "__" + i;
      if (data[new_name] != null) {
        i += 1;
      } else {
        return new_name;
      }
    }
  };

  Figure.prototype._fixup_values = function(cls, data, attrs) {
    var name, results, value;
    results = [];
    for (name in attrs) {
      value = attrs[name];
      results.push((function(_this) {
        return function(name, value) {
          var field, prop;
          prop = cls.prototype.props[name];
          if (prop != null) {
            if (prop.type.prototype.dataspec) {
              if (value != null) {
                if (_.isArray(value)) {
                  if (data[name] != null) {
                    if (data[name] !== value) {
                      field = _this._find_uniq_name(data, name);
                      data[field] = value;
                    } else {
                      field = name;
                    }
                  } else {
                    field = name;
                    data[field] = value;
                  }
                  return attrs[name] = {
                    field: field
                  };
                } else if (_.isNumber(value) || _.isString(value)) {
                  return attrs[name] = {
                    value: value
                  };
                }
              }
            }
          }
        };
      })(this)(name, value));
    }
    return results;
  };

  Figure.prototype._glyph = function(cls, params, args) {
    var _make_glyph, attrs, data, fn, glyph, glyph_ca, glyph_renderer, has_hglyph, has_sglyph, hglyph, hglyph_ca, i, j, k, legend, len, nsglyph, nsglyph_ca, opts, param, ref, ref1, sglyph, sglyph_ca, source;
    params = params.split(",");
    if (args.length === 1) {
      attrs = args[0];
      attrs = _.clone(attrs);
    } else {
      ref = args, args = 2 <= ref.length ? slice.call(ref, 0, j = ref.length - 1) : (j = 0, []), opts = ref[j++];
      attrs = _.clone(opts);
      fn = function(param, i) {
        return attrs[param] = args[i];
      };
      for (i = k = 0, len = params.length; k < len; i = ++k) {
        param = params[i];
        fn(param, i);
      }
    }
    legend = attrs.legend;
    delete attrs.legend;
    has_sglyph = _.any(_.keys(attrs), function(key) {
      return key.startsWith("selection_");
    });
    has_hglyph = _.any(_.keys(attrs), function(key) {
      return key.startsWith("hover_");
    });
    glyph_ca = this._pop_colors_and_alpha(cls, attrs);
    nsglyph_ca = this._pop_colors_and_alpha(cls, attrs, "nonselection_", void 0, 0.1);
    sglyph_ca = has_sglyph ? this._pop_colors_and_alpha(cls, attrs, "selection_") : {};
    hglyph_ca = has_hglyph ? this._pop_colors_and_alpha(cls, attrs, "hover_") : {};
    source = (ref1 = attrs.source) != null ? ref1 : new models.ColumnDataSource();
    data = _.clone(source.data);
    delete attrs.source;
    this._fixup_values(cls, data, glyph_ca);
    this._fixup_values(cls, data, nsglyph_ca);
    this._fixup_values(cls, data, sglyph_ca);
    this._fixup_values(cls, data, hglyph_ca);
    this._fixup_values(cls, data, attrs);
    source.data = data;
    _make_glyph = (function(_this) {
      return function(cls, attrs, extra_attrs) {
        return new cls(_.extend({}, attrs, extra_attrs));
      };
    })(this);
    glyph = _make_glyph(cls, attrs, glyph_ca);
    nsglyph = _make_glyph(cls, attrs, nsglyph_ca);
    sglyph = has_sglyph ? _make_glyph(cls, attrs, sglyph_ca) : null;
    hglyph = has_hglyph ? _make_glyph(cls, attrs, hglyph_ca) : null;
    glyph_renderer = new models.GlyphRenderer({
      data_source: source,
      glyph: glyph,
      nonselection_glyph: nsglyph,
      selection_glyph: sglyph,
      hover_glyph: hglyph
    });
    if (legend != null) {
      this._update_legend(legend, glyph_renderer);
    }
    this.add_renderers(glyph_renderer);
    return glyph_renderer;
  };

  Figure.prototype._marker = function(cls, args) {
    return this._glyph(cls, "x,y", args);
  };

  Figure.prototype._get_range = function(range) {
    if (range == null) {
      return new models.DataRange1d();
    }
    if (range instanceof models.Range) {
      return range;
    }
    if (_.isArray(range)) {
      if (_.all(function(x) {
        var j, len, results;
        results = [];
        for (j = 0, len = range.length; j < len; j++) {
          x = range[j];
          results.push(_.isString(x));
        }
        return results;
      })) {
        return new models.FactorRange({
          factors: range
        });
      }
      if (range.length === 2) {
        return new models.Range1d({
          start: range[0],
          end: range[1]
        });
      }
    }
  };

  Figure.prototype._process_guides = function(dim, axis_type, axis_location, minor_ticks, axis_label) {
    var axis, axiscls, grid, range;
    range = dim === 0 ? this.x_range : this.y_range;
    axiscls = this._get_axis_class(axis_type, range);
    if (axiscls != null) {
      if (axiscls === models.LogAxis) {
        if (dim === 0) {
          this.x_mapper_type = 'log';
        } else {
          this.y_mapper_type = 'log';
        }
      }
      axis = new axiscls();
      if (axis.ticker instanceof models.ContinuousTicker) {
        axis.ticker.num_minor_ticks = this._get_num_minor_ticks(axiscls, minor_ticks);
      }
      if (axis_label.length !== 0) {
        axis.axis_label = axis_label;
      }
      grid = new models.Grid({
        dimension: dim,
        ticker: axis.ticker
      });
      this.add_layout(axis, axis_location);
      return this.add_layout(grid);
    }
  };

  Figure.prototype._get_axis_class = function(axis_type, range) {
    if (axis_type == null) {
      return null;
    }
    if (axis_type === "linear") {
      return models.LinearAxis;
    }
    if (axis_type === "log") {
      return models.LogAxis;
    }
    if (axis_type === "datetime") {
      return models.DatetimeAxis;
    }
    if (axis_type === "auto") {
      if (range instanceof models.FactorRange) {
        return models.CategoricalAxis;
      } else {
        return models.LinearAxis;
      }
    }
  };

  Figure.prototype._get_num_minor_ticks = function(axis_class, num_minor_ticks) {
    if (_.isNumber(num_minor_ticks)) {
      if (num_minor_ticks <= 1) {
        throw new Error("num_minor_ticks must be > 1");
      }
      return num_minor_ticks;
    }
    if (num_minor_ticks == null) {
      return 0;
    }
    if (num_minor_ticks === 'auto') {
      if (axis_class === models.LogAxis) {
        return 10;
      }
      return 5;
    }
  };

  Figure.prototype._process_tools = function(tools) {
    var objs, tool;
    if (_.isString(tools)) {
      tools = tools.split(/\s*,\s*/);
    }
    objs = (function() {
      var j, len, results;
      results = [];
      for (j = 0, len = tools.length; j < len; j++) {
        tool = tools[j];
        if (_.isString(tool)) {
          results.push(_known_tools[tool](this));
        } else {
          results.push(tool);
        }
      }
      return results;
    }).call(this);
    return objs;
  };

  Figure.prototype._update_legend = function(legend_name, glyph_renderer) {
    var j, legends, len, name, ref, renderers;
    legends = _.clone(this._legend.legends);
    for (j = 0, len = legends.length; j < len; j++) {
      ref = legends[j], name = ref[0], renderers = ref[1];
      if (name === legend_name) {
        renderers.push(glyph_renderer);
        this._legend.legends = legends;
        return;
      }
    }
    legends.push([legend_name, [glyph_renderer]]);
    return this._legend.legends = legends;
  };

  return Figure;

})(models.Plot);

figure = function(attributes, options) {
  if (attributes == null) {
    attributes = {};
  }
  if (options == null) {
    options = {};
  }
  return new Figure(attributes, options);
};

show = function(obj, target) {
  var _obj, div, doc, j, len, multiple, views;
  multiple = _.isArray(obj);
  doc = new Document();
  if (!multiple) {
    doc.add_root(obj);
  } else {
    for (j = 0, len = obj.length; j < len; j++) {
      _obj = obj[j];
      doc.add_root(_obj);
    }
  }
  div = $("<div class=" + BOKEH_ROOT + ">");
  $(target != null ? target : "body").append(div);
  views = embed.add_document_standalone(doc, div);
  if (!multiple) {
    return views[obj.id];
  } else {
    return views;
  }
};

color = function(r, g, b) {
  return sprintf("#%02x%02x%02x", r, g, b);
};

gridplot = function(children, options) {
  var grid, item, j, k, l, layout, len, len1, len2, neighbor, row, row_children, row_tools, rows, sizing_mode, toolbar, toolbar_location, toolbar_sizing_mode, tools;
  if (options == null) {
    options = {};
  }
  toolbar_location = _.isUndefined(options.toolbar_location) ? 'above' : options.toolbar_location;
  sizing_mode = _.isUndefined(options.sizing_mode) ? 'fixed' : options.sizing_mode;
  toolbar_sizing_mode = options.sizing_mode === 'fixed' ? 'scale_width' : sizing_mode;
  tools = [];
  rows = [];
  for (j = 0, len = children.length; j < len; j++) {
    row = children[j];
    row_tools = [];
    row_children = [];
    for (k = 0, len1 = row.length; k < len1; k++) {
      item = row[k];
      if (item instanceof models.Plot) {
        row_tools = row_tools.concat(item.toolbar.tools);
        item.toolbar_location = null;
      }
      if (item === null) {
        for (l = 0, len2 = row.length; l < len2; l++) {
          neighbor = row[l];
          if (neighbor instanceof models.Plot) {
            break;
          }
        }
        item = new models.Spacer({
          width: neighbor.plot_width,
          height: neighbor.plot_height
        });
      }
      if (item instanceof models.LayoutDOM) {
        item.sizing_mode = sizing_mode;
        row_children.push(item);
      } else {
        throw new Error("only LayoutDOM items can be inserted into Grid");
      }
    }
    tools = tools.concat(row_tools);
    row = new models.Row({
      children: row_children,
      sizing_mode: sizing_mode
    });
    rows.push(row);
  }
  grid = new models.Column({
    children: rows,
    sizing_mode: sizing_mode
  });
  layout = (function() {
    if (toolbar_location) {
      toolbar = new models.ToolbarBox({
        tools: tools,
        sizing_mode: toolbar_sizing_mode,
        toolbar_location: toolbar_location
      });
      switch (toolbar_location) {
        case 'above':
          return new models.Column({
            children: [toolbar, grid],
            sizing_mode: sizing_mode
          });
        case 'below':
          return new models.Column({
            children: [grid, toolbar],
            sizing_mode: sizing_mode
          });
        case 'left':
          return new models.Row({
            children: [toolbar, grid],
            sizing_mode: sizing_mode
          });
        case 'right':
          return new models.Row({
            children: [grid, toolbar],
            sizing_mode: sizing_mode
          });
      }
    } else {
      return grid;
    }
  })();
  return layout;
};

module.exports = {
  Figure: Figure,
  figure: figure,
  show: show,
  color: color,
  gridplot: gridplot
};

},{"../document":"document","../embed":"embed","./models":"api/models","jquery":"jquery","sprintf":"sprintf","underscore":"underscore"}],"base":[function(require,module,exports){
var Models, _, _get_mod_cache, _mod_cache, index, locations, logger, make_cache, overrides,
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

logger = require("./core/logging").logger;

require("./core/util/underscore").patch();

locations = require("./common/models");

overrides = {};

make_cache = function(locations) {
  var mod, modname, name, ref, result, spec, subname, subspec, suffix;
  result = {};
  for (name in locations) {
    spec = locations[name];
    if (_.isArray(spec)) {
      subspec = spec[0];
      suffix = (ref = spec[1]) != null ? ref : "";
      for (subname in subspec) {
        mod = subspec[subname];
        modname = subname + suffix;
        result[modname] = mod;
      }
    } else {
      result[name] = spec;
    }
  }
  return result;
};

_mod_cache = null;

_get_mod_cache = function() {
  if (_mod_cache == null) {
    _mod_cache = make_cache(locations);
  }
  return _mod_cache;
};

Models = function(typename) {
  var mod, mod_cache;
  mod_cache = _get_mod_cache();
  if (overrides[typename]) {
    return overrides[typename];
  }
  mod = mod_cache[typename];
  if (mod == null) {
    throw new Error("Module `" + typename + "' does not exists. The problem may be two fold. Either a model was requested that's available in an extra bundle, e.g. a widget, or a custom model was requested, but it wasn't registered before first usage.");
  }
  return mod.Model;
};

Models.register = function(name, model) {
  return overrides[name] = model;
};

Models.unregister = function(name) {
  return delete overrides[name];
};

Models.register_locations = function(locations, force, errorFn) {
  var cache, mod_cache, module, name, results;
  if (force == null) {
    force = false;
  }
  if (errorFn == null) {
    errorFn = null;
  }
  mod_cache = _get_mod_cache();
  cache = make_cache(locations);
  results = [];
  for (name in cache) {
    if (!hasProp.call(cache, name)) continue;
    module = cache[name];
    if (force || !mod_cache.hasOwnProperty(name)) {
      results.push(mod_cache[name] = module);
    } else {
      results.push(typeof errorFn === "function" ? errorFn(name) : void 0);
    }
  }
  return results;
};

Models.registered_names = function() {
  return Object.keys(_get_mod_cache());
};

index = {};

module.exports = {
  overrides: overrides,
  index: index,
  Models: Models
};

},{"./common/models":"common/models","./core/logging":"core/logging","./core/util/underscore":"core/util/underscore","underscore":"underscore"}],"client":[function(require,module,exports){
var ClientConnection, ClientSession, DEFAULT_SERVER_WEBSOCKET_URL, DEFAULT_SESSION_ID, Document, HasProps, Message, ModelChangedEvent, Promise, RootAddedEvent, RootRemovedEvent, _, logger, message_handlers, pull_session, ref;

_ = require("underscore");

Promise = require("es6-promise").Promise;

HasProps = require("./core/has_props");

logger = require("./core/logging").logger;

ref = require("./document"), Document = ref.Document, ModelChangedEvent = ref.ModelChangedEvent, RootAddedEvent = ref.RootAddedEvent, RootRemovedEvent = ref.RootRemovedEvent;

DEFAULT_SERVER_WEBSOCKET_URL = "ws://localhost:5006/ws";

DEFAULT_SESSION_ID = "default";

Message = (function() {
  function Message(header1, metadata1, content1) {
    this.header = header1;
    this.metadata = metadata1;
    this.content = content1;
    this.buffers = [];
  }

  Message.assemble = function(header_json, metadata_json, content_json) {
    var content, e, error1, header, metadata;
    try {
      header = JSON.parse(header_json);
      metadata = JSON.parse(metadata_json);
      content = JSON.parse(content_json);
      return new Message(header, metadata, content);
    } catch (error1) {
      e = error1;
      logger.error("Failure parsing json " + e + " " + header_json + " " + metadata_json + " " + content_json, e);
      throw e;
    }
  };

  Message.create_header = function(msgtype, options) {
    var header;
    header = {
      'msgid': _.uniqueId(),
      'msgtype': msgtype
    };
    return _.extend(header, options);
  };

  Message.create = function(msgtype, header_options, content) {
    var header;
    if (content == null) {
      content = {};
    }
    header = Message.create_header(msgtype, header_options);
    return new Message(header, {}, content);
  };

  Message.prototype.send = function(socket) {
    var content_json, e, error1, header_json, metadata_json;
    try {
      header_json = JSON.stringify(this.header);
      metadata_json = JSON.stringify(this.metadata);
      content_json = JSON.stringify(this.content);
      socket.send(header_json);
      socket.send(metadata_json);
      return socket.send(content_json);
    } catch (error1) {
      e = error1;
      logger.error("Error sending ", this, e);
      throw e;
    }
  };

  Message.prototype.complete = function() {
    if ((this.header != null) && (this.metadata != null) && (this.content != null)) {
      if ('num_buffers' in this.header) {
        return this.buffers.length === this.header['num_buffers'];
      } else {
        return true;
      }
    } else {
      return false;
    }
  };

  Message.prototype.add_buffer = function(buffer) {
    return this.buffers.push(buffer);
  };

  Message.prototype._header_field = function(field) {
    if (field in this.header) {
      return this.header[field];
    } else {
      return null;
    }
  };

  Message.prototype.msgid = function() {
    return this._header_field('msgid');
  };

  Message.prototype.msgtype = function() {
    return this._header_field('msgtype');
  };

  Message.prototype.sessid = function() {
    return this._header_field('sessid');
  };

  Message.prototype.reqid = function() {
    return this._header_field('reqid');
  };

  Message.prototype.problem = function() {
    if (!('msgid' in this.header)) {
      return "No msgid in header";
    } else if (!('msgtype' in this.header)) {
      return "No msgtype in header";
    } else {
      return null;
    }
  };

  return Message;

})();

message_handlers = {
  'PATCH-DOC': function(connection, message) {
    return connection._for_session(function(session) {
      return session._handle_patch(message);
    });
  },
  'OK': function(connection, message) {
    return logger.debug("Unhandled OK reply to " + (message.reqid()));
  },
  'ERROR': function(connection, message) {
    return logger.error("Unhandled ERROR reply to " + (message.reqid()) + ": " + message.content['text']);
  }
};

ClientConnection = (function() {
  ClientConnection._connection_count = 0;

  function ClientConnection(url1, id, _on_have_session_hook, _on_closed_permanently_hook) {
    this.url = url1;
    this.id = id;
    this._on_have_session_hook = _on_have_session_hook;
    this._on_closed_permanently_hook = _on_closed_permanently_hook;
    this._number = ClientConnection._connection_count;
    ClientConnection._connection_count = this._number + 1;
    if (this.url == null) {
      this.url = DEFAULT_SERVER_WEBSOCKET_URL;
    }
    if (this.id == null) {
      this.id = DEFAULT_SESSION_ID;
    }
    logger.debug("Creating websocket " + this._number + " to '" + this.url + "' session '" + this.id + "'");
    this.socket = null;
    this.closed_permanently = false;
    this._fragments = [];
    this._partial = null;
    this._current_handler = null;
    this._pending_ack = null;
    this._pending_replies = {};
    this.session = null;
  }

  ClientConnection.prototype._for_session = function(f) {
    if (this.session !== null) {
      return f(this.session);
    }
  };

  ClientConnection.prototype.connect = function() {
    var error, error1, versioned_url;
    if (this.closed_permanently) {
      return Promise.reject(new Error("Cannot connect() a closed ClientConnection"));
    }
    if (this.socket != null) {
      return Promise.reject(new Error("Already connected"));
    }
    this._fragments = [];
    this._partial = null;
    this._pending_replies = {};
    this._current_handler = null;
    try {
      versioned_url = this.url + "?bokeh-protocol-version=1.0&bokeh-session-id=" + this.id;
      if (window.MozWebSocket != null) {
        this.socket = new MozWebSocket(versioned_url);
      } else {
        this.socket = new WebSocket(versioned_url);
      }
      return new Promise((function(_this) {
        return function(resolve, reject) {
          _this.socket.binarytype = "arraybuffer";
          _this.socket.onopen = function() {
            return _this._on_open(resolve, reject);
          };
          _this.socket.onmessage = function(event) {
            return _this._on_message(event);
          };
          _this.socket.onclose = function(event) {
            return _this._on_close(event);
          };
          return _this.socket.onerror = function() {
            return _this._on_error(reject);
          };
        };
      })(this));
    } catch (error1) {
      error = error1;
      logger.error("websocket creation failed to url: " + this.url);
      logger.error(" - " + error);
      return Promise.reject(error);
    }
  };

  ClientConnection.prototype.close = function() {
    if (!this.closed_permanently) {
      logger.debug("Permanently closing websocket connection " + this._number);
      this.closed_permanently = true;
      if (this.socket != null) {
        this.socket.close(1000, "close method called on ClientConnection " + this._number);
      }
      this._for_session(function(session) {
        return session._connection_closed();
      });
      if (this._on_closed_permanently_hook != null) {
        this._on_closed_permanently_hook();
        return this._on_closed_permanently_hook = null;
      }
    }
  };

  ClientConnection.prototype._schedule_reconnect = function(milliseconds) {
    var retry;
    retry = (function(_this) {
      return function() {
        if (true || _this.closed_permanently) {
          if (!_this.closed_permanently) {
            logger.info("Websocket connection " + _this._number + " disconnected, will not attempt to reconnect");
          }
        } else {
          logger.debug("Attempting to reconnect websocket " + _this._number);
          return _this.connect();
        }
      };
    })(this);
    return setTimeout(retry, milliseconds);
  };

  ClientConnection.prototype.send = function(message) {
    var e, error1;
    try {
      if (this.socket === null) {
        throw new Error("not connected so cannot send " + message);
      }
      return message.send(this.socket);
    } catch (error1) {
      e = error1;
      return logger.error("Error sending message ", e, message);
    }
  };

  ClientConnection.prototype.send_with_reply = function(message) {
    var promise;
    promise = new Promise((function(_this) {
      return function(resolve, reject) {
        _this._pending_replies[message.msgid()] = [resolve, reject];
        return _this.send(message);
      };
    })(this));
    return promise.then(function(message) {
      if (message.msgtype() === 'ERROR') {
        throw new Error("Error reply " + message.content['text']);
      } else {
        return message;
      }
    }, function(error) {
      throw error;
    });
  };

  ClientConnection.prototype._pull_doc_json = function() {
    var message, promise;
    message = Message.create('PULL-DOC-REQ', {});
    promise = this.send_with_reply(message);
    return promise.then(function(reply) {
      if (!('doc' in reply.content)) {
        throw new Error("No 'doc' field in PULL-DOC-REPLY");
      }
      return reply.content['doc'];
    }, function(error) {
      throw error;
    });
  };

  ClientConnection.prototype._repull_session_doc = function() {
    if (this.session === null) {
      logger.debug("Pulling session for first time");
    } else {
      logger.debug("Repulling session");
    }
    return this._pull_doc_json().then((function(_this) {
      return function(doc_json) {
        var document, patch, patch_message;
        if (_this.session === null) {
          if (_this.closed_permanently) {
            return logger.debug("Got new document after connection was already closed");
          } else {
            document = Document.from_json(doc_json);
            patch = Document._compute_patch_since_json(doc_json, document);
            if (patch.events.length > 0) {
              logger.debug("Sending " + patch.events.length + " changes from model construction back to server");
              patch_message = Message.create('PATCH-DOC', {}, patch);
              _this.send(patch_message);
            }
            _this.session = new ClientSession(_this, document, _this.id);
            logger.debug("Created a new session from new pulled doc");
            if (_this._on_have_session_hook != null) {
              _this._on_have_session_hook(_this.session);
              return _this._on_have_session_hook = null;
            }
          }
        } else {
          _this.session.document.replace_with_json(doc_json);
          return logger.debug("Updated existing session with new pulled doc");
        }
      };
    })(this), function(error) {
      throw error;
    })["catch"](function(error) {
      if (console.trace != null) {
        console.trace(error);
      }
      return logger.error("Failed to repull session " + error);
    });
  };

  ClientConnection.prototype._on_open = function(resolve, reject) {
    logger.info("Websocket connection " + this._number + " is now open");
    this._pending_ack = [resolve, reject];
    return this._current_handler = (function(_this) {
      return function(message) {
        return _this._awaiting_ack_handler(message);
      };
    })(this);
  };

  ClientConnection.prototype._on_message = function(event) {
    var e, error1;
    try {
      return this._on_message_unchecked(event);
    } catch (error1) {
      e = error1;
      return logger.error("Error handling message: " + e + ", " + event);
    }
  };

  ClientConnection.prototype._on_message_unchecked = function(event) {
    var msg, problem;
    if (this._current_handler == null) {
      logger.error("got a message but haven't set _current_handler");
    }
    if (event.data instanceof ArrayBuffer) {
      if ((this._partial != null) && !this._partial.complete()) {
        this._partial.add_buffer(event.data);
      } else {
        this._close_bad_protocol("Got binary from websocket but we were expecting text");
      }
    } else if (this._partial != null) {
      this._close_bad_protocol("Got text from websocket but we were expecting binary");
    } else {
      this._fragments.push(event.data);
      if (this._fragments.length === 3) {
        this._partial = Message.assemble(this._fragments[0], this._fragments[1], this._fragments[2]);
        this._fragments = [];
        problem = this._partial.problem();
        if (problem !== null) {
          this._close_bad_protocol(problem);
        }
      }
    }
    if ((this._partial != null) && this._partial.complete()) {
      msg = this._partial;
      this._partial = null;
      return this._current_handler(msg);
    }
  };

  ClientConnection.prototype._on_close = function(event) {
    var pop_pending, promise_funcs;
    logger.info("Lost websocket " + this._number + " connection, " + event.code + " (" + event.reason + ")");
    this.socket = null;
    if (this._pending_ack != null) {
      this._pending_ack[1](new Error("Lost websocket connection, " + event.code + " (" + event.reason + ")"));
      this._pending_ack = null;
    }
    pop_pending = function() {
      var promise_funcs, ref1, reqid;
      ref1 = this._pending_replies;
      for (reqid in ref1) {
        promise_funcs = ref1[reqid];
        delete this._pending_replies[reqid];
        return promise_funcs;
      }
      return null;
    };
    promise_funcs = pop_pending();
    while (promise_funcs !== null) {
      promise_funcs[1]("Disconnected");
      promise_funcs = pop_pending();
    }
    if (!this.closed_permanently) {
      return this._schedule_reconnect(2000);
    }
  };

  ClientConnection.prototype._on_error = function(reject) {
    logger.debug("Websocket error on socket  " + this._number);
    return reject(new Error("Could not open websocket"));
  };

  ClientConnection.prototype._close_bad_protocol = function(detail) {
    logger.error("Closing connection: " + detail);
    if (this.socket != null) {
      return this.socket.close(1002, detail);
    }
  };

  ClientConnection.prototype._awaiting_ack_handler = function(message) {
    if (message.msgtype() === "ACK") {
      this._current_handler = (function(_this) {
        return function(message) {
          return _this._steady_state_handler(message);
        };
      })(this);
      this._repull_session_doc();
      if (this._pending_ack != null) {
        this._pending_ack[0](this);
        return this._pending_ack = null;
      }
    } else {
      return this._close_bad_protocol("First message was not an ACK");
    }
  };

  ClientConnection.prototype._steady_state_handler = function(message) {
    var promise_funcs;
    if (message.reqid() in this._pending_replies) {
      promise_funcs = this._pending_replies[message.reqid()];
      delete this._pending_replies[message.reqid()];
      return promise_funcs[0](message);
    } else if (message.msgtype() in message_handlers) {
      return message_handlers[message.msgtype()](this, message);
    } else {
      return logger.debug("Doing nothing with message " + (message.msgtype()));
    }
  };

  return ClientConnection;

})();

ClientSession = (function() {
  function ClientSession(_connection, document1, id) {
    this._connection = _connection;
    this.document = document1;
    this.id = id;
    this._current_patch = null;
    this.document_listener = (function(_this) {
      return function(event) {
        return _this._document_changed(event);
      };
    })(this);
    this.document.on_change(this.document_listener);
  }

  ClientSession.prototype.close = function() {
    return this._connection.close();
  };

  ClientSession.prototype._connection_closed = function() {
    return this.document.remove_on_change(this.document_listener);
  };

  ClientSession.prototype.request_server_info = function() {
    var message, promise;
    message = Message.create('SERVER-INFO-REQ', {});
    promise = this._connection.send_with_reply(message);
    return promise.then(function(reply) {
      return reply.content;
    });
  };

  ClientSession.prototype.force_roundtrip = function() {
    return this.request_server_info().then(function(ignored) {
      return void 0;
    });
  };

  ClientSession.prototype._should_suppress_on_change = function(patch, event) {
    var event_json, i, j, k, l, len, len1, len2, len3, patch_new, ref1, ref2, ref3, ref4;
    if (event instanceof ModelChangedEvent) {
      ref1 = patch.content['events'];
      for (i = 0, len = ref1.length; i < len; i++) {
        event_json = ref1[i];
        if (event_json['kind'] === 'ModelChanged' && event_json['model']['id'] === event.model.id && event_json['attr'] === event.attr) {
          patch_new = event_json['new'];
          if (event.new_ instanceof HasProps) {
            if (typeof patch_new === 'object' && 'id' in patch_new && patch_new['id'] === event.new_.id) {
              return true;
            }
          } else if (_.isEqual(patch_new, event.new_)) {
            return true;
          }
        }
      }
    } else if (event instanceof RootAddedEvent) {
      ref2 = patch.content['events'];
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        event_json = ref2[j];
        if (event_json['kind'] === 'RootAdded' && event_json['model']['id'] === event.model.id) {
          return true;
        }
      }
    } else if (event instanceof RootRemovedEvent) {
      ref3 = patch.content['events'];
      for (k = 0, len2 = ref3.length; k < len2; k++) {
        event_json = ref3[k];
        if (event_json['kind'] === 'RootRemoved' && event_json['model']['id'] === event.model.id) {
          return true;
        }
      }
    } else if (event instanceof TitleChangedEvent) {
      ref4 = patch.content['events'];
      for (l = 0, len3 = ref4.length; l < len3; l++) {
        event_json = ref4[l];
        if (event_json['kind'] === 'TitleChanged' && event_json['title'] === event.title) {
          return true;
        }
      }
    }
    return false;
  };

  ClientSession.prototype._document_changed = function(event) {
    var patch;
    if ((this._current_patch != null) && this._should_suppress_on_change(this._current_patch, event)) {
      return;
    }
    if (event instanceof ModelChangedEvent && !(event.attr in event.model.serializable_attributes())) {
      return;
    }
    patch = Message.create('PATCH-DOC', {}, this.document.create_json_patch([event]));
    return this._connection.send(patch);
  };

  ClientSession.prototype._handle_patch = function(message) {
    this._current_patch = message;
    try {
      return this.document.apply_json_patch(message.content);
    } finally {
      this._current_patch = null;
    }
  };

  return ClientSession;

})();

pull_session = function(url, session_id) {
  var connection, promise, rejecter;
  rejecter = null;
  connection = null;
  promise = new Promise(function(resolve, reject) {
    connection = new ClientConnection(url, session_id, function(session) {
      var e, error1;
      try {
        return resolve(session);
      } catch (error1) {
        e = error1;
        logger.error("Promise handler threw an error, closing session " + error);
        session.close();
        throw e;
      }
    }, function() {
      return reject(new Error("Connection was closed before we successfully pulled a session"));
    });
    return connection.connect().then(function(whatever) {}, function(error) {
      logger.error("Failed to connect to Bokeh server " + error);
      throw error;
    });
  });
  promise.close = function() {
    return connection.close();
  };
  return promise;
};

module.exports = {
  pull_session: pull_session,
  DEFAULT_SERVER_WEBSOCKET_URL: DEFAULT_SERVER_WEBSOCKET_URL,
  DEFAULT_SESSION_ID: DEFAULT_SESSION_ID
};

},{"./core/has_props":"core/has_props","./core/logging":"core/logging","./document":"document","es6-promise":"es6-promise","underscore":"underscore"}],"common/build_views":[function(require,module,exports){
var _, build_views, jQueryUIPrefixer;

_ = require("underscore");

build_views = function(view_storage, view_models, options, view_types) {
  var created_views, i, i_model, j, key, len, len1, model, newmodels, to_remove, view_specific_option;
  if (view_types == null) {
    view_types = [];
  }
  created_views = [];
  newmodels = _.filter(view_models, function(x) {
    return !_.has(view_storage, x.id);
  });
  for (i_model = i = 0, len = newmodels.length; i < len; i_model = ++i) {
    model = newmodels[i_model];
    view_specific_option = _.extend({}, options, {
      'model': model
    });
    if (i_model < view_types.length) {
      view_storage[model.id] = new view_types[i_model](view_specific_option);
    } else {
      view_storage[model.id] = new model.default_view(view_specific_option);
    }
    view_storage[model.id].$el.find("*[class*='ui-']").each(function(idx, el) {
      return el.className = jQueryUIPrefixer(el);
    });
    created_views.push(view_storage[model.id]);
  }
  to_remove = _.difference(_.keys(view_storage), _.pluck(view_models, 'id'));
  for (j = 0, len1 = to_remove.length; j < len1; j++) {
    key = to_remove[j];
    view_storage[key].remove();
    delete view_storage[key];
  }
  return created_views;
};

jQueryUIPrefixer = function(el) {
  var classList, prefixedClassList;
  if (el.className == null) {
    return;
  }
  classList = el.className.split(" ");
  prefixedClassList = _.map(classList, function(a) {
    a = a.trim();
    if (a.indexOf("ui-") === 0) {
      return "bk-" + a;
    } else {
      return a;
    }
  });
  return prefixedClassList.join(" ");
};

build_views.jQueryUIPrefixer = jQueryUIPrefixer;

module.exports = build_views = build_views;

},{"underscore":"underscore"}],"common/hittest":[function(require,module,exports){
var HitTestResult, check_2_segments_intersect, create_hit_test_result, dist_2_pts, dist_to_segment, dist_to_segment_squared, nullreturner, point_in_poly, sqr, validate_bbox_coords;

point_in_poly = function(x, y, px, py) {
  var i, inside, j, ref, x1, x2, y1, y2;
  inside = false;
  x1 = px[px.length - 1];
  y1 = py[py.length - 1];
  for (i = j = 0, ref = px.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
    x2 = px[i];
    y2 = py[i];
    if ((y1 < y) !== (y2 < y)) {
      if (x1 + (y - y1) / (y2 - y1) * (x2 - x1) < x) {
        inside = !inside;
      }
    }
    x1 = x2;
    y1 = y2;
  }
  return inside;
};

nullreturner = function() {
  return null;
};

HitTestResult = (function() {
  function HitTestResult() {
    this['0d'] = {
      glyph: null,
      get_view: nullreturner,
      indices: []
    };
    this['1d'] = {
      indices: []
    };
    this['2d'] = {
      indices: []
    };
  }

  Object.defineProperty(HitTestResult.prototype, '_0d', {
    get: function() {
      return this['0d'];
    }
  });

  Object.defineProperty(HitTestResult.prototype, '_1d', {
    get: function() {
      return this['1d'];
    }
  });

  Object.defineProperty(HitTestResult.prototype, '_2d', {
    get: function() {
      return this['2d'];
    }
  });

  HitTestResult.prototype.is_empty = function() {
    return this._0d.indices.length === 0 && this._1d.indices.length === 0 && this._2d.indices.length === 0;
  };

  return HitTestResult;

})();

create_hit_test_result = function() {
  return new HitTestResult();
};

validate_bbox_coords = function(arg, arg1) {
  var ref, ref1, x0, x1, y0, y1;
  x0 = arg[0], x1 = arg[1];
  y0 = arg1[0], y1 = arg1[1];
  if (x0 > x1) {
    ref = [x1, x0], x0 = ref[0], x1 = ref[1];
  }
  if (y0 > y1) {
    ref1 = [y1, y0], y0 = ref1[0], y1 = ref1[1];
  }
  return {
    minX: x0,
    minY: y0,
    maxX: x1,
    maxY: y1
  };
};

sqr = function(x) {
  return x * x;
};

dist_2_pts = function(vx, vy, wx, wy) {
  return sqr(vx - wx) + sqr(vy - wy);
};

dist_to_segment_squared = function(p, v, w) {
  var l2, t;
  l2 = dist_2_pts(v.x, v.y, w.x, w.y);
  if (l2 === 0) {
    return dist_2_pts(p.x, p.y, v.x, v.y);
  }
  t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
  if (t < 0) {
    return dist_2_pts(p.x, p.y, v.x, v.y);
  }
  if (t > 1) {
    return dist_2_pts(p.x, p.y, w.x, w.y);
  }
  return dist_2_pts(p.x, p.y, v.x + t * (w.x - v.x), v.y + t * (w.y - v.y));
};

dist_to_segment = function(p, v, w) {
  return Math.sqrt(dist_to_segment_squared(p, v, w));
};

check_2_segments_intersect = function(l0_x0, l0_y0, l0_x1, l0_y1, l1_x0, l1_y0, l1_x1, l1_y1) {

  /* Check if 2 segments (l0 and l1) intersect. Returns a structure with
    the following attributes:
      * hit (boolean): whether the 2 segments intersect
      * x (float): x coordinate of the intersection point
      * y (float): y coordinate of the intersection point
   */
  var a, b, den, num1, num2, x, y;
  den = ((l1_y1 - l1_y0) * (l0_x1 - l0_x0)) - ((l1_x1 - l1_x0) * (l0_y1 - l0_y0));
  if (den === 0) {
    return {
      hit: false,
      x: null,
      y: null
    };
  } else {
    a = l0_y0 - l1_y0;
    b = l0_x0 - l1_x0;
    num1 = ((l1_x1 - l1_x0) * a) - ((l1_y1 - l1_y0) * b);
    num2 = ((l0_x1 - l0_x0) * a) - ((l0_y1 - l0_y0) * b);
    a = num1 / den;
    b = num2 / den;
    x = l0_x0 + (a * (l0_x1 - l0_x0));
    y = l0_y0 + (a * (l0_y1 - l0_y0));
    return {
      hit: (a > 0 && a < 1) && (b > 0 && b < 1),
      x: x,
      y: y
    };
  }
};

module.exports = {
  point_in_poly: point_in_poly,
  HitTestResult: HitTestResult,
  create_hit_test_result: create_hit_test_result,
  dist_2_pts: dist_2_pts,
  dist_to_segment: dist_to_segment,
  check_2_segments_intersect: check_2_segments_intersect,
  validate_bbox_coords: validate_bbox_coords
};

},{}],"common/models":[function(require,module,exports){
module.exports = {
  SelectionManager: require('./selection_manager'),
  Selector: require('./selector'),
  ToolEvents: require('./tool_events'),
  Arrow: require('../models/annotations/arrow'),
  BoxAnnotation: require('../models/annotations/box_annotation'),
  Label: require('../models/annotations/label'),
  LabelSet: require('../models/annotations/label_set'),
  Legend: require('../models/annotations/legend'),
  PolyAnnotation: require('../models/annotations/poly_annotation'),
  Span: require('../models/annotations/span'),
  Title: require('../models/annotations/title'),
  Tooltip: require('../models/annotations/tooltip'),
  OpenHead: require('../models/annotations/arrow_head').OpenHead,
  NormalHead: require('../models/annotations/arrow_head').NormalHead,
  VeeHead: require('../models/annotations/arrow_head').VeeHead,
  CategoricalAxis: require('../models/axes/categorical_axis'),
  DatetimeAxis: require('../models/axes/datetime_axis'),
  LinearAxis: require('../models/axes/linear_axis'),
  LogAxis: require('../models/axes/log_axis'),
  CustomJS: require('../models/callbacks/customjs'),
  OpenURL: require('../models/callbacks/open_url'),
  Canvas: require('../models/canvas/canvas'),
  CartesianFrame: require('../models/canvas/cartesian_frame'),
  BasicTickFormatter: require('../models/formatters/basic_tick_formatter'),
  CategoricalTickFormatter: require('../models/formatters/categorical_tick_formatter'),
  DatetimeTickFormatter: require('../models/formatters/datetime_tick_formatter'),
  LogTickFormatter: require('../models/formatters/log_tick_formatter'),
  FuncTickFormatter: require('../models/formatters/func_tick_formatter'),
  NumeralTickFormatter: require('../models/formatters/numeral_tick_formatter'),
  PrintfTickFormatter: require('../models/formatters/printf_tick_formatter'),
  AnnularWedge: require('../models/glyphs/annular_wedge'),
  Annulus: require('../models/glyphs/annulus'),
  Arc: require('../models/glyphs/arc'),
  Bezier: require('../models/glyphs/bezier'),
  Circle: require('../models/glyphs/circle'),
  Ellipse: require('../models/glyphs/ellipse'),
  Gear: require('../models/glyphs/gear'),
  HBar: require('../models/glyphs/hbar'),
  Image: require('../models/glyphs/image'),
  ImageRGBA: require('../models/glyphs/image_rgba'),
  ImageURL: require('../models/glyphs/image_url'),
  Line: require('../models/glyphs/line'),
  MultiLine: require('../models/glyphs/multi_line'),
  Oval: require('../models/glyphs/oval'),
  Patch: require('../models/glyphs/patch'),
  Patches: require('../models/glyphs/patches'),
  Quad: require('../models/glyphs/quad'),
  Quadratic: require('../models/glyphs/quadratic'),
  Ray: require('../models/glyphs/ray'),
  Rect: require('../models/glyphs/rect'),
  Segment: require('../models/glyphs/segment'),
  Text: require('../models/glyphs/text'),
  VBar: require('../models/glyphs/vbar'),
  Wedge: require('../models/glyphs/wedge'),
  Grid: require('../models/grids/grid'),
  Column: require('../models/layouts/column'),
  Row: require('../models/layouts/row'),
  Spacer: require('../models/layouts/spacer'),
  WidgetBox: require('../models/layouts/widget_box'),
  CategoricalMapper: require('../models/mappers/categorical_mapper'),
  GridMapper: require('../models/mappers/grid_mapper'),
  LinearColorMapper: require('../models/mappers/linear_color_mapper'),
  LinearMapper: require('../models/mappers/linear_mapper'),
  LogColorMapper: require('../models/mappers/log_color_mapper'),
  LogMapper: require('../models/mappers/log_mapper'),
  Transform: require('../models/transforms/transform'),
  Jitter: require('../models/transforms/jitter'),
  Interpolator: require('../models/transforms/interpolator'),
  LinearInterpolator: require('../models/transforms/linear_interpolator'),
  StepInterpolator: require('../models/transforms/step_interpolator'),
  Asterisk: require('../models/markers/asterisk'),
  CircleCross: require('../models/markers/circle_cross'),
  CircleX: require('../models/markers/circle_x'),
  Cross: require('../models/markers/cross'),
  Diamond: require('../models/markers/diamond'),
  DiamondCross: require('../models/markers/diamond_cross'),
  InvertedTriangle: require('../models/markers/inverted_triangle'),
  Square: require('../models/markers/square'),
  SquareCross: require('../models/markers/square_cross'),
  SquareX: require('../models/markers/square_x'),
  Triangle: require('../models/markers/triangle'),
  X: require('../models/markers/x'),
  Plot: require('../models/plots/plot'),
  GMapPlot: require('../models/plots/gmap_plot'),
  DataRange1d: require('../models/ranges/data_range1d'),
  FactorRange: require('../models/ranges/factor_range'),
  Range1d: require('../models/ranges/range1d'),
  GlyphRenderer: require('../models/renderers/glyph_renderer'),
  AjaxDataSource: require('../models/sources/ajax_data_source'),
  ColumnDataSource: require('../models/sources/column_data_source'),
  GeoJSONDataSource: require('../models/sources/geojson_data_source'),
  AdaptiveTicker: require('../models/tickers/adaptive_ticker'),
  BasicTicker: require('../models/tickers/basic_ticker'),
  CategoricalTicker: require('../models/tickers/categorical_ticker'),
  CompositeTicker: require('../models/tickers/composite_ticker'),
  ContinuousTicker: require('../models/tickers/continuous_ticker'),
  DatetimeTicker: require('../models/tickers/datetime_ticker'),
  DaysTicker: require('../models/tickers/days_ticker'),
  FixedTicker: require('../models/tickers/fixed_ticker'),
  LogTicker: require('../models/tickers/log_ticker'),
  MonthsTicker: require('../models/tickers/months_ticker'),
  SingleIntervalTicker: require('../models/tickers/single_interval_ticker'),
  YearsTicker: require('../models/tickers/years_ticker'),
  TileRenderer: require('../models/tiles/tile_renderer'),
  TileSource: require('../models/tiles/tile_source'),
  TMSTileSource: require('../models/tiles/tms_tile_source'),
  WMTSTileSource: require('../models/tiles/wmts_tile_source'),
  QUADKEYTileSource: require('../models/tiles/quadkey_tile_source'),
  BBoxTileSource: require('../models/tiles/bbox_tile_source'),
  DynamicImageRenderer: require('../models/tiles/dynamic_image_renderer'),
  ImageSource: require('../models/tiles/image_source'),
  Toolbar: require('../models/tools/toolbar'),
  ToolbarBox: require('../models/tools/toolbar_box'),
  ButtonTool: require('../models/tools/button_tool'),
  ActionTool: require('../models/tools/actions/action_tool'),
  SaveTool: require('../models/tools/actions/save_tool'),
  UndoTool: require('../models/tools/actions/undo_tool'),
  RedoTool: require('../models/tools/actions/redo_tool'),
  ResetTool: require('../models/tools/actions/reset_tool'),
  HelpTool: require('../models/tools/actions/help_tool'),
  BoxSelectTool: require('../models/tools/gestures/box_select_tool'),
  BoxZoomTool: require('../models/tools/gestures/box_zoom_tool'),
  GestureTool: require('../models/tools/gestures/gesture_tool'),
  LassoSelectTool: require('../models/tools/gestures/lasso_select_tool'),
  PanTool: require('../models/tools/gestures/pan_tool'),
  PolySelectTool: require('../models/tools/gestures/poly_select_tool'),
  SelectTool: require('../models/tools/gestures/select_tool'),
  ResizeTool: require('../models/tools/gestures/resize_tool'),
  TapTool: require('../models/tools/gestures/tap_tool'),
  WheelZoomTool: require('../models/tools/gestures/wheel_zoom_tool'),
  CrosshairTool: require('../models/tools/inspectors/crosshair_tool'),
  HoverTool: require('../models/tools/inspectors/hover_tool'),
  InspectTool: require('../models/tools/inspectors/inspect_tool')
};

},{"../models/annotations/arrow":"models/annotations/arrow","../models/annotations/arrow_head":"models/annotations/arrow_head","../models/annotations/box_annotation":"models/annotations/box_annotation","../models/annotations/label":"models/annotations/label","../models/annotations/label_set":"models/annotations/label_set","../models/annotations/legend":"models/annotations/legend","../models/annotations/poly_annotation":"models/annotations/poly_annotation","../models/annotations/span":"models/annotations/span","../models/annotations/title":"models/annotations/title","../models/annotations/tooltip":"models/annotations/tooltip","../models/axes/categorical_axis":"models/axes/categorical_axis","../models/axes/datetime_axis":"models/axes/datetime_axis","../models/axes/linear_axis":"models/axes/linear_axis","../models/axes/log_axis":"models/axes/log_axis","../models/callbacks/customjs":"models/callbacks/customjs","../models/callbacks/open_url":"models/callbacks/open_url","../models/canvas/canvas":"models/canvas/canvas","../models/canvas/cartesian_frame":"models/canvas/cartesian_frame","../models/formatters/basic_tick_formatter":"models/formatters/basic_tick_formatter","../models/formatters/categorical_tick_formatter":"models/formatters/categorical_tick_formatter","../models/formatters/datetime_tick_formatter":"models/formatters/datetime_tick_formatter","../models/formatters/func_tick_formatter":"models/formatters/func_tick_formatter","../models/formatters/log_tick_formatter":"models/formatters/log_tick_formatter","../models/formatters/numeral_tick_formatter":"models/formatters/numeral_tick_formatter","../models/formatters/printf_tick_formatter":"models/formatters/printf_tick_formatter","../models/glyphs/annular_wedge":"models/glyphs/annular_wedge","../models/glyphs/annulus":"models/glyphs/annulus","../models/glyphs/arc":"models/glyphs/arc","../models/glyphs/bezier":"models/glyphs/bezier","../models/glyphs/circle":"models/glyphs/circle","../models/glyphs/ellipse":"models/glyphs/ellipse","../models/glyphs/gear":"models/glyphs/gear","../models/glyphs/hbar":"models/glyphs/hbar","../models/glyphs/image":"models/glyphs/image","../models/glyphs/image_rgba":"models/glyphs/image_rgba","../models/glyphs/image_url":"models/glyphs/image_url","../models/glyphs/line":"models/glyphs/line","../models/glyphs/multi_line":"models/glyphs/multi_line","../models/glyphs/oval":"models/glyphs/oval","../models/glyphs/patch":"models/glyphs/patch","../models/glyphs/patches":"models/glyphs/patches","../models/glyphs/quad":"models/glyphs/quad","../models/glyphs/quadratic":"models/glyphs/quadratic","../models/glyphs/ray":"models/glyphs/ray","../models/glyphs/rect":"models/glyphs/rect","../models/glyphs/segment":"models/glyphs/segment","../models/glyphs/text":"models/glyphs/text","../models/glyphs/vbar":"models/glyphs/vbar","../models/glyphs/wedge":"models/glyphs/wedge","../models/grids/grid":"models/grids/grid","../models/layouts/column":"models/layouts/column","../models/layouts/row":"models/layouts/row","../models/layouts/spacer":"models/layouts/spacer","../models/layouts/widget_box":"models/layouts/widget_box","../models/mappers/categorical_mapper":"models/mappers/categorical_mapper","../models/mappers/grid_mapper":"models/mappers/grid_mapper","../models/mappers/linear_color_mapper":"models/mappers/linear_color_mapper","../models/mappers/linear_mapper":"models/mappers/linear_mapper","../models/mappers/log_color_mapper":"models/mappers/log_color_mapper","../models/mappers/log_mapper":"models/mappers/log_mapper","../models/markers/asterisk":"models/markers/asterisk","../models/markers/circle_cross":"models/markers/circle_cross","../models/markers/circle_x":"models/markers/circle_x","../models/markers/cross":"models/markers/cross","../models/markers/diamond":"models/markers/diamond","../models/markers/diamond_cross":"models/markers/diamond_cross","../models/markers/inverted_triangle":"models/markers/inverted_triangle","../models/markers/square":"models/markers/square","../models/markers/square_cross":"models/markers/square_cross","../models/markers/square_x":"models/markers/square_x","../models/markers/triangle":"models/markers/triangle","../models/markers/x":"models/markers/x","../models/plots/gmap_plot":"models/plots/gmap_plot","../models/plots/plot":"models/plots/plot","../models/ranges/data_range1d":"models/ranges/data_range1d","../models/ranges/factor_range":"models/ranges/factor_range","../models/ranges/range1d":"models/ranges/range1d","../models/renderers/glyph_renderer":"models/renderers/glyph_renderer","../models/sources/ajax_data_source":"models/sources/ajax_data_source","../models/sources/column_data_source":"models/sources/column_data_source","../models/sources/geojson_data_source":"models/sources/geojson_data_source","../models/tickers/adaptive_ticker":"models/tickers/adaptive_ticker","../models/tickers/basic_ticker":"models/tickers/basic_ticker","../models/tickers/categorical_ticker":"models/tickers/categorical_ticker","../models/tickers/composite_ticker":"models/tickers/composite_ticker","../models/tickers/continuous_ticker":"models/tickers/continuous_ticker","../models/tickers/datetime_ticker":"models/tickers/datetime_ticker","../models/tickers/days_ticker":"models/tickers/days_ticker","../models/tickers/fixed_ticker":"models/tickers/fixed_ticker","../models/tickers/log_ticker":"models/tickers/log_ticker","../models/tickers/months_ticker":"models/tickers/months_ticker","../models/tickers/single_interval_ticker":"models/tickers/single_interval_ticker","../models/tickers/years_ticker":"models/tickers/years_ticker","../models/tiles/bbox_tile_source":"models/tiles/bbox_tile_source","../models/tiles/dynamic_image_renderer":"models/tiles/dynamic_image_renderer","../models/tiles/image_source":"models/tiles/image_source","../models/tiles/quadkey_tile_source":"models/tiles/quadkey_tile_source","../models/tiles/tile_renderer":"models/tiles/tile_renderer","../models/tiles/tile_source":"models/tiles/tile_source","../models/tiles/tms_tile_source":"models/tiles/tms_tile_source","../models/tiles/wmts_tile_source":"models/tiles/wmts_tile_source","../models/tools/actions/action_tool":"models/tools/actions/action_tool","../models/tools/actions/help_tool":"models/tools/actions/help_tool","../models/tools/actions/redo_tool":"models/tools/actions/redo_tool","../models/tools/actions/reset_tool":"models/tools/actions/reset_tool","../models/tools/actions/save_tool":"models/tools/actions/save_tool","../models/tools/actions/undo_tool":"models/tools/actions/undo_tool","../models/tools/button_tool":"models/tools/button_tool","../models/tools/gestures/box_select_tool":"models/tools/gestures/box_select_tool","../models/tools/gestures/box_zoom_tool":"models/tools/gestures/box_zoom_tool","../models/tools/gestures/gesture_tool":"models/tools/gestures/gesture_tool","../models/tools/gestures/lasso_select_tool":"models/tools/gestures/lasso_select_tool","../models/tools/gestures/pan_tool":"models/tools/gestures/pan_tool","../models/tools/gestures/poly_select_tool":"models/tools/gestures/poly_select_tool","../models/tools/gestures/resize_tool":"models/tools/gestures/resize_tool","../models/tools/gestures/select_tool":"models/tools/gestures/select_tool","../models/tools/gestures/tap_tool":"models/tools/gestures/tap_tool","../models/tools/gestures/wheel_zoom_tool":"models/tools/gestures/wheel_zoom_tool","../models/tools/inspectors/crosshair_tool":"models/tools/inspectors/crosshair_tool","../models/tools/inspectors/hover_tool":"models/tools/inspectors/hover_tool","../models/tools/inspectors/inspect_tool":"models/tools/inspectors/inspect_tool","../models/tools/toolbar":"models/tools/toolbar","../models/tools/toolbar_box":"models/tools/toolbar_box","../models/transforms/interpolator":"models/transforms/interpolator","../models/transforms/jitter":"models/transforms/jitter","../models/transforms/linear_interpolator":"models/transforms/linear_interpolator","../models/transforms/step_interpolator":"models/transforms/step_interpolator","../models/transforms/transform":"models/transforms/transform","./selection_manager":"common/selection_manager","./selector":"common/selector","./tool_events":"common/tool_events"}],"common/selection_manager":[function(require,module,exports){
var HasProps, SelectionManager, Selector, _, hittest, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

HasProps = require("../core/has_props");

logger = require("../core/logging").logger;

Selector = require("./selector");

hittest = require("./hittest");

p = require("../core/properties");

SelectionManager = (function(superClass) {
  extend(SelectionManager, superClass);

  function SelectionManager() {
    return SelectionManager.__super__.constructor.apply(this, arguments);
  }

  SelectionManager.prototype.type = 'SelectionManager';

  SelectionManager.internal({
    source: [p.Any]
  });

  SelectionManager.prototype.initialize = function(attrs, options) {
    SelectionManager.__super__.initialize.call(this, attrs, options);
    this.selectors = {};
    this.inspectors = {};
    return this.last_inspection_was_empty = {};
  };

  SelectionManager.prototype.select = function(tool, renderer_view, geometry, final, append) {
    var indices, selector, source;
    if (append == null) {
      append = false;
    }
    source = this.get('source');
    if (source !== renderer_view.mget('data_source')) {
      logger.warn('select called with mis-matched data sources');
    }
    indices = renderer_view.hit_test(geometry);
    if (indices != null) {
      selector = this._get_selector(renderer_view);
      selector.update(indices, final, append);
      this.get('source').set({
        "selected": selector.get('indices')
      });
      source.trigger('select');
      source.trigger('select-' + renderer_view.mget('id'));
      return !indices.is_empty();
    } else {
      return false;
    }
  };

  SelectionManager.prototype.inspect = function(tool, renderer_view, geometry, data) {
    var indices, inspector, r_id, source;
    source = this.get('source');
    if (source !== renderer_view.mget('data_source')) {
      logger.warn('inspect called with mis-matched data sources');
    }
    indices = renderer_view.hit_test(geometry);
    if (indices != null) {
      r_id = renderer_view.model.id;
      if (indices.is_empty()) {
        if (this.last_inspection_was_empty[r_id] == null) {
          this.last_inspection_was_empty[r_id] = false;
        }
        if (this.last_inspection_was_empty[r_id]) {
          return;
        } else {
          this.last_inspection_was_empty[r_id] = true;
        }
      } else {
        this.last_inspection_was_empty[r_id] = false;
      }
      inspector = this._get_inspector(renderer_view);
      inspector.update(indices, true, false, true);
      this.get('source').set({
        "inspected": inspector.get('indices')
      }, {
        "silent": true
      });
      source.trigger('inspect', indices, tool, renderer_view, source, data);
      source.trigger("inspect" + (renderer_view.mget('id')), indices, tool, renderer_view, source, data);
      return !indices.is_empty();
    } else {
      return false;
    }
  };

  SelectionManager.prototype.clear = function(rview) {
    var k, ref, s, selector;
    if (rview != null) {
      selector = this._get_selector(rview);
      selector.clear();
    } else {
      ref = this.selectors;
      for (k in ref) {
        s = ref[k];
        s.clear();
      }
    }
    return this.get('source').set({
      "selected": hittest.create_hit_test_result()
    });
  };

  SelectionManager.prototype._get_selector = function(rview) {
    _.setdefault(this.selectors, rview.model.id, new Selector());
    return this.selectors[rview.model.id];
  };

  SelectionManager.prototype._get_inspector = function(rview) {
    _.setdefault(this.inspectors, rview.model.id, new Selector());
    return this.inspectors[rview.model.id];
  };

  return SelectionManager;

})(HasProps);

module.exports = SelectionManager;

},{"../core/has_props":"core/has_props","../core/logging":"core/logging","../core/properties":"core/properties","./hittest":"common/hittest","./selector":"common/selector","underscore":"underscore"}],"common/selector":[function(require,module,exports){
var HasProps, Selector, _, hittest, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

HasProps = require("../core/has_props");

hittest = require("./hittest");

logger = require("../core/logging").logger;

p = require("../core/properties");

Selector = (function(superClass) {
  extend(Selector, superClass);

  function Selector() {
    return Selector.__super__.constructor.apply(this, arguments);
  }

  Selector.prototype.type = 'Selector';

  Selector.prototype.update = function(indices, final, append, silent) {
    if (silent == null) {
      silent = false;
    }
    this.set('timestamp', new Date(), {
      silent: silent
    });
    this.set('final', final, {
      silent: silent
    });
    if (append) {
      indices['0d'].indices = _.union(this.get('indices')['0d'].indices, indices['0d'].indices);
      indices['0d'].glyph = this.get('indices')['0d'].glyph || indices['0d'].glyph;
      indices['1d'].indices = _.union(this.get('indices')['1d'].indices, indices['1d'].indices);
      indices['2d'].indices = _.union(this.get('indices')['2d'].indices, indices['2d'].indices);
    }
    return this.set('indices', indices, {
      silent: silent
    });
  };

  Selector.prototype.clear = function() {
    this.set('timestamp', new Date());
    this.set('final', true);
    return this.set('indices', hittest.create_hit_test_result());
  };

  Selector.internal({
    indices: [
      p.Any, function() {
        return hittest.create_hit_test_result();
      }
    ],
    final: [p.Boolean],
    timestamp: [p.Any]
  });

  return Selector;

})(HasProps);

module.exports = Selector;

},{"../core/has_props":"core/has_props","../core/logging":"core/logging","../core/properties":"core/properties","./hittest":"common/hittest","underscore":"underscore"}],"common/tool_events":[function(require,module,exports){
var Model, ToolEvents, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../model");

logger = require("../core/logging").logger;

p = require("../core/properties");

ToolEvents = (function(superClass) {
  extend(ToolEvents, superClass);

  function ToolEvents() {
    return ToolEvents.__super__.constructor.apply(this, arguments);
  }

  ToolEvents.prototype.type = 'ToolEvents';

  ToolEvents.define({
    geometries: [p.Array, []]
  });

  return ToolEvents;

})(Model);

module.exports = {
  Model: ToolEvents
};

},{"../core/logging":"core/logging","../core/properties":"core/properties","../model":"model","underscore":"underscore"}],"common/ui_events":[function(require,module,exports){
var $, Backbone, Hammer, UIEvents, logger, mousewheel,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

$ = require("jquery");

Backbone = require("backbone");

Hammer = require("hammerjs");

mousewheel = require("jquery-mousewheel")($);

logger = require("../core/logging").logger;

UIEvents = (function(superClass) {
  extend(UIEvents, superClass);

  function UIEvents() {
    return UIEvents.__super__.constructor.apply(this, arguments);
  }

  UIEvents.prototype.initialize = function(attrs, options) {
    UIEvents.__super__.initialize.call(this, attrs, options);
    return this._hammer_element();
  };

  UIEvents.prototype._hammer_element = function() {
    var hit_area;
    hit_area = this.get('hit_area');
    this.hammer = new Hammer(hit_area[0]);
    this.hammer.get('doubletap').recognizeWith('tap');
    this.hammer.get('tap').requireFailure('doubletap');
    this.hammer.get('doubletap').dropRequireFailure('tap');
    this.hammer.on('doubletap', (function(_this) {
      return function(e) {
        return _this._doubletap(e);
      };
    })(this));
    this.hammer.on('tap', (function(_this) {
      return function(e) {
        return _this._tap(e);
      };
    })(this));
    this.hammer.on('press', (function(_this) {
      return function(e) {
        return _this._press(e);
      };
    })(this));
    this.hammer.get('pan').set({
      direction: Hammer.DIRECTION_ALL
    });
    this.hammer.on('panstart', (function(_this) {
      return function(e) {
        return _this._pan_start(e);
      };
    })(this));
    this.hammer.on('pan', (function(_this) {
      return function(e) {
        return _this._pan(e);
      };
    })(this));
    this.hammer.on('panend', (function(_this) {
      return function(e) {
        return _this._pan_end(e);
      };
    })(this));
    this.hammer.get('pinch').set({
      enable: true
    });
    this.hammer.on('pinchstart', (function(_this) {
      return function(e) {
        return _this._pinch_start(e);
      };
    })(this));
    this.hammer.on('pinch', (function(_this) {
      return function(e) {
        return _this._pinch(e);
      };
    })(this));
    this.hammer.on('pinchend', (function(_this) {
      return function(e) {
        return _this._pinch_end(e);
      };
    })(this));
    this.hammer.get('rotate').set({
      enable: true
    });
    this.hammer.on('rotatestart', (function(_this) {
      return function(e) {
        return _this._rotate_start(e);
      };
    })(this));
    this.hammer.on('rotate', (function(_this) {
      return function(e) {
        return _this._rotate(e);
      };
    })(this));
    this.hammer.on('rotateend', (function(_this) {
      return function(e) {
        return _this._rotate_end(e);
      };
    })(this));
    hit_area.mousemove((function(_this) {
      return function(e) {
        return _this._mouse_move(e);
      };
    })(this));
    hit_area.mouseenter((function(_this) {
      return function(e) {
        return _this._mouse_enter(e);
      };
    })(this));
    hit_area.mouseleave((function(_this) {
      return function(e) {
        return _this._mouse_exit(e);
      };
    })(this));
    hit_area.mousewheel((function(_this) {
      return function(e, delta) {
        return _this._mouse_wheel(e, delta);
      };
    })(this));
    $(document).keydown((function(_this) {
      return function(e) {
        return _this._key_down(e);
      };
    })(this));
    return $(document).keyup((function(_this) {
      return function(e) {
        return _this._key_up(e);
      };
    })(this));
  };

  UIEvents.prototype.register_tool = function(tool_view) {
    var et, id, type;
    et = tool_view.model.event_type;
    id = tool_view.model.id;
    type = tool_view.model.type;
    if (et == null) {
      logger.debug("Button tool: " + type);
      return;
    }
    if (et === 'pan' || et === 'pinch' || et === 'rotate') {
      logger.debug("Registering tool: " + type + " for event '" + et + "'");
      if (tool_view["_" + et + "_start"] != null) {
        tool_view.listenTo(this, et + ":start:" + id, tool_view["_" + et + "_start"]);
      }
      if (tool_view["_" + et]) {
        tool_view.listenTo(this, et + ":" + id, tool_view["_" + et]);
      }
      if (tool_view["_" + et + "_end"]) {
        tool_view.listenTo(this, et + ":end:" + id, tool_view["_" + et + "_end"]);
      }
    } else if (et === "move") {
      logger.debug("Registering tool: " + type + " for event '" + et + "'");
      if (tool_view._move_enter != null) {
        tool_view.listenTo(this, "move:enter", tool_view._move_enter);
      }
      tool_view.listenTo(this, "move", tool_view["_move"]);
      if (tool_view._move_exit != null) {
        tool_view.listenTo(this, "move:exit", tool_view._move_exit);
      }
    } else {
      logger.debug("Registering tool: " + type + " for event '" + et + "'");
      tool_view.listenTo(this, et + ":" + id, tool_view["_" + et]);
    }
    if (tool_view._keydown != null) {
      logger.debug("Registering tool: " + type + " for event 'keydown'");
      tool_view.listenTo(this, "keydown", tool_view._keydown);
    }
    if (tool_view._keyup != null) {
      logger.debug("Registering tool: " + type + " for event 'keyup'");
      tool_view.listenTo(this, "keyup", tool_view._keyup);
    }
    if (tool_view._doubletap != null) {
      logger.debug("Registering tool: " + type + " for event 'doubletap'");
      tool_view.listenTo(this, "doubletap", tool_view._doubletap);
    }
    if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
      if (et === 'pinch') {
        logger.debug("Registering scroll on touch screen");
        return tool_view.listenTo(this, "scroll:" + id, tool_view["_scroll"]);
      }
    }
  };

  UIEvents.prototype._trigger = function(event_type, e) {
    var active_tool, base_event_type, gestures, toolbar;
    toolbar = this.get('toolbar');
    base_event_type = event_type.split(":")[0];
    if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
      if (event_type === 'scroll') {
        base_event_type = 'pinch';
      }
    }
    gestures = toolbar.get('gestures');
    active_tool = gestures[base_event_type].active;
    if (active_tool != null) {
      return this._trigger_event(event_type, active_tool, e);
    }
  };

  UIEvents.prototype._trigger_event = function(event_type, active_tool, e) {
    if (active_tool.get('active') === true) {
      if (event_type === 'scroll') {
        e.preventDefault();
        e.stopPropagation();
      }
      return this.trigger(event_type + ":" + active_tool.id, e);
    }
  };

  UIEvents.prototype._bokify_hammer = function(e) {
    var left, offset, ref, ref1, top, x, y;
    if (e.pointerType === 'mouse') {
      x = e.srcEvent.pageX;
      y = e.srcEvent.pageY;
    } else {
      x = e.pointers[0].pageX;
      y = e.pointers[0].pageY;
    }
    offset = $(e.target).offset();
    left = (ref = offset.left) != null ? ref : 0;
    top = (ref1 = offset.top) != null ? ref1 : 0;
    return e.bokeh = {
      sx: x - left,
      sy: y - top
    };
  };

  UIEvents.prototype._bokify_jq = function(e) {
    var left, offset, ref, ref1, top;
    offset = $(e.currentTarget).offset();
    left = (ref = offset.left) != null ? ref : 0;
    top = (ref1 = offset.top) != null ? ref1 : 0;
    return e.bokeh = {
      sx: e.pageX - left,
      sy: e.pageY - top
    };
  };

  UIEvents.prototype._tap = function(e) {
    this._bokify_hammer(e);
    return this._trigger('tap', e);
  };

  UIEvents.prototype._doubletap = function(e) {
    this._bokify_hammer(e);
    return this.trigger('doubletap', e);
  };

  UIEvents.prototype._press = function(e) {
    this._bokify_hammer(e);
    return this._trigger('press', e);
  };

  UIEvents.prototype._pan_start = function(e) {
    this._bokify_hammer(e);
    e.bokeh.sx -= e.deltaX;
    e.bokeh.sy -= e.deltaY;
    return this._trigger('pan:start', e);
  };

  UIEvents.prototype._pan = function(e) {
    this._bokify_hammer(e);
    return this._trigger('pan', e);
  };

  UIEvents.prototype._pan_end = function(e) {
    this._bokify_hammer(e);
    return this._trigger('pan:end', e);
  };

  UIEvents.prototype._pinch_start = function(e) {
    this._bokify_hammer(e);
    return this._trigger('pinch:start', e);
  };

  UIEvents.prototype._pinch = function(e) {
    this._bokify_hammer(e);
    return this._trigger('pinch', e);
  };

  UIEvents.prototype._pinch_end = function(e) {
    this._bokify_hammer(e);
    return this._trigger('pinch:end', e);
  };

  UIEvents.prototype._rotate_start = function(e) {
    this._bokify_hammer(e);
    return this._trigger('rotate:start', e);
  };

  UIEvents.prototype._rotate = function(e) {
    this._bokify_hammer(e);
    return this._trigger('rotate', e);
  };

  UIEvents.prototype._rotate_end = function(e) {
    this._bokify_hammer(e);
    return this._trigger('rotate:end', e);
  };

  UIEvents.prototype._mouse_enter = function(e) {
    this._bokify_jq(e);
    return this.trigger('move:enter', e);
  };

  UIEvents.prototype._mouse_move = function(e) {
    this._bokify_jq(e);
    return this.trigger('move', e);
  };

  UIEvents.prototype._mouse_exit = function(e) {
    this._bokify_jq(e);
    return this.trigger('move:exit', e);
  };

  UIEvents.prototype._mouse_wheel = function(e, delta) {
    this._bokify_jq(e);
    e.bokeh.delta = delta;
    return this._trigger('scroll', e);
  };

  UIEvents.prototype._key_down = function(e) {
    return this.trigger('keydown', e);
  };

  UIEvents.prototype._key_up = function(e) {
    return this.trigger('keyup', e);
  };

  return UIEvents;

})(Backbone.Model);

module.exports = UIEvents;

},{"../core/logging":"core/logging","backbone":"backbone","hammerjs":"hammerjs/hammer","jquery":"jquery","jquery-mousewheel":"jquery-mousewheel"}],"core/bokeh_view":[function(require,module,exports){
var Backbone, BokehView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Backbone = require("backbone");

BokehView = (function(superClass) {
  extend(BokehView, superClass);

  function BokehView() {
    return BokehView.__super__.constructor.apply(this, arguments);
  }

  BokehView.prototype.initialize = function(options) {
    if (!_.has(options, 'id')) {
      return this.id = _.uniqueId('BokehView');
    }
  };

  BokehView.prototype.bind_bokeh_events = function() {};

  BokehView.prototype.remove = function() {
    var ref, target, val;
    if (_.has(this, 'eventers')) {
      ref = this.eventers;
      for (target in ref) {
        if (!hasProp.call(ref, target)) continue;
        val = ref[target];
        val.off(null, null, this);
      }
    }
    this.trigger('remove', this);
    return BokehView.__super__.remove.call(this);
  };

  BokehView.prototype.mget = function() {
    return this.model.get.apply(this.model, arguments);
  };

  BokehView.prototype.mset = function() {
    return this.model.set.apply(this.model, arguments);
  };

  return BokehView;

})(Backbone.View);

module.exports = BokehView;

},{"backbone":"backbone","underscore":"underscore"}],"core/enums":[function(require,module,exports){
module.exports = {
  AngleUnits: ["deg", "rad"],
  Dimension: ["width", "height"],
  Direction: ["clock", "anticlock"],
  FontStyle: ["normal", "italic", "bold"],
  LineCap: ["butt", "round", "square"],
  LineJoin: ["miter", "round", "bevel"],
  Location: ["above", "below", "left", "right"],
  LegendLocation: ["top_left", "top_center", "top_right", "left_center", "center", "right_center", "bottom_left", "bottom_center", "bottom_right"],
  Orientation: ["vertical", "horizontal"],
  RenderLevel: ["image", "underlay", "glyph", "annotation", "overlay", "tool"],
  RenderMode: ["canvas", "css"],
  Side: ["left", "right"],
  SpatialUnits: ["screen", "data"],
  StartEnd: ["start", "end"],
  TextAlign: ["left", "right", "center"],
  TextBaseline: ["top", "middle", "bottom", "alphabetic", "hanging", "ideographic"],
  DistributionTypes: ["uniform", "normal"],
  TransformStepModes: ["after", "before", "center"],
  SizingMode: ["stretch_both", "scale_width", "scale_height", "scale_both", "fixed"]
};

},{}],"core/has_props":[function(require,module,exports){
var $, Backbone, HasProps, _, logger, property_mixins, refs,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  slice = [].slice;

$ = require("jquery");

_ = require("underscore");

Backbone = require("backbone");

logger = require("./logging").logger;

property_mixins = require("./property_mixins");

refs = require("./util/refs");

HasProps = (function(superClass) {
  extend(HasProps, superClass);

  HasProps.prototype.props = {};

  HasProps.prototype.mixins = [];

  HasProps.define = function(object) {
    var name, prop, results;
    results = [];
    for (name in object) {
      prop = object[name];
      results.push((function(_this) {
        return function(name, prop) {
          var default_value, internal, props, refined_prop, type;
          if (_this.prototype.props[name] != null) {
            throw new Error("attempted to redefine property '" + _this.name + "." + name + "'");
          }
          if ((_this.prototype[name] != null) && name !== "url") {
            throw new Error("attempted to redefine attribute '" + _this.name + "." + name + "'");
          }
          Object.defineProperty(_this.prototype, name, {
            get: function() {
              return this.get(name);
            },
            set: function(value) {
              return this.set(name, value);
            }
          }, {
            configurable: false,
            enumerable: true
          });
          type = prop[0], default_value = prop[1], internal = prop[2];
          refined_prop = {
            type: type,
            default_value: default_value,
            internal: internal != null ? internal : false
          };
          props = _.clone(_this.prototype.props);
          props[name] = refined_prop;
          return _this.prototype.props = props;
        };
      })(this)(name, prop));
    }
    return results;
  };

  HasProps.internal = function(object) {
    var _object, fn, name, prop;
    _object = {};
    fn = (function(_this) {
      return function(name, prop) {
        var default_value, type;
        type = prop[0], default_value = prop[1];
        return _object[name] = [type, default_value, true];
      };
    })(this);
    for (name in object) {
      prop = object[name];
      fn(name, prop);
    }
    return this.define(_object);
  };

  HasProps.mixin = function() {
    var mixins, names;
    names = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    this.define(property_mixins.create(names));
    mixins = this.prototype.mixins.concat(names);
    return this.prototype.mixins = mixins;
  };

  HasProps.mixins = function(names) {
    return this.mixin.apply(this, names);
  };

  HasProps.override = function(name_or_object, default_value) {
    var name, object, results;
    if (_.isString(name_or_object)) {
      object = {};
      object[name] = default_value;
    } else {
      object = name_or_object;
    }
    results = [];
    for (name in object) {
      default_value = object[name];
      results.push((function(_this) {
        return function(name, default_value) {
          var props, value;
          value = _this.prototype.props[name];
          if (value == null) {
            throw new Error("attempted to override nonexistent '" + _this.name + "." + name + "'");
          }
          props = _.clone(_this.prototype.props);
          props[name] = _.extend({}, value, {
            default_value: default_value
          });
          return _this.prototype.props = props;
        };
      })(this)(name, default_value));
    }
    return results;
  };

  HasProps.prototype.toString = function() {
    return this.type + "(" + this.id + ")";
  };

  HasProps.prototype.destroy = function(options) {
    HasProps.__super__.destroy.call(this, options);
    return this.stopListening();
  };

  function HasProps(attributes, options) {
    var attrs, default_value, name, ref, ref1, type;
    this.document = null;
    attrs = attributes || {};
    if (!options) {
      options = {};
    }
    this.cid = _.uniqueId('c');
    this.attributes = {};
    this.properties = {};
    ref = this.props;
    for (name in ref) {
      ref1 = ref[name], type = ref1.type, default_value = ref1.default_value;
      if (type == null) {
        throw new Error("undefined property type for " + this.type + "." + name);
      }
      this.properties[name] = new type({
        obj: this,
        attr: name,
        default_value: default_value
      });
    }
    if (options.parse) {
      attrs = this.parse(attrs, options) || {};
    }
    this._set_after_defaults = {};
    this.set(attrs, options);
    this.changed = {};
    this._computed = {};
    if (!_.has(attrs, this.idAttribute)) {
      this.id = _.uniqueId(this.type);
      this.attributes[this.idAttribute] = this.id;
    }
    if (!options.defer_initialization) {
      this.initialize.apply(this, arguments);
    }
  }

  HasProps.prototype.set = function(key, value, options) {
    var attrs, old, prop_name, results, val;
    if (_.isObject(key) || key === null) {
      attrs = key;
      options = value;
    } else {
      attrs = {};
      attrs[key] = value;
    }
    for (key in attrs) {
      if (!hasProp.call(attrs, key)) continue;
      val = attrs[key];
      prop_name = key;
      if (!(prop_name === "id" || this.props[prop_name])) {
        throw new Error(this.type + ".set('" + prop_name + "'): " + prop_name + " wasn't declared");
      }
      if (!((options != null) && options.defaults)) {
        this._set_after_defaults[key] = true;
      }
    }
    if (!_.isEmpty(attrs)) {
      old = {};
      for (key in attrs) {
        value = attrs[key];
        old[key] = this.get(key);
      }
      HasProps.__super__.set.call(this, attrs, options);
      if ((options != null ? options.silent : void 0) == null) {
        results = [];
        for (key in attrs) {
          value = attrs[key];
          results.push(this._tell_document_about_change(key, old[key], this.get(key)));
        }
        return results;
      }
    }
  };

  HasProps.prototype.add_dependencies = function(prop_name, object, fields) {
    var fld, j, len, prop_spec, results;
    if (!_.isArray(fields)) {
      fields = [fields];
    }
    prop_spec = this._computed[prop_name];
    prop_spec.dependencies = prop_spec.dependencies.concat({
      obj: object,
      fields: fields
    });
    results = [];
    for (j = 0, len = fields.length; j < len; j++) {
      fld = fields[j];
      results.push(this.listenTo(object, "change:" + fld, prop_spec['callbacks']['changedep']));
    }
    return results;
  };

  HasProps.prototype.define_computed_property = function(prop_name, getter, use_cache) {
    var changedep, prop_spec, propchange;
    if (use_cache == null) {
      use_cache = true;
    }
    if (this.props[prop_name] != null) {
      console.log("attempted to redefine existing property " + this.type + "." + prop_name);
    }
    if (_.has(this._computed, prop_name)) {
      throw new Error("attempted to redefine existing computed property " + this.type + "." + prop_name);
    }
    changedep = (function(_this) {
      return function() {
        return _this.trigger('changedep:' + prop_name);
      };
    })(this);
    propchange = (function(_this) {
      return function() {
        var firechange, new_val, old_val;
        firechange = true;
        if (prop_spec['use_cache']) {
          old_val = prop_spec.cache;
          prop_spec.cache = void 0;
          new_val = _this.get(prop_name);
          firechange = new_val !== old_val;
        }
        if (firechange) {
          _this.trigger('change:' + prop_name, _this, _this.get(prop_name));
          return _this.trigger('change', _this);
        }
      };
    })(this);
    prop_spec = {
      'getter': getter,
      'dependencies': [],
      'use_cache': use_cache,
      'callbacks': {
        changedep: changedep,
        propchange: propchange
      }
    };
    this._computed[prop_name] = prop_spec;
    this.listenTo(this, "changedep:" + prop_name, prop_spec['callbacks']['propchange']);
    return prop_spec;
  };

  HasProps.prototype.override_computed_property = function(prop_name, getter, use_cache) {
    if (use_cache == null) {
      use_cache = true;
    }
    if (_.has(this._computed, prop_name)) {
      this._remove_computed_property(prop_name);
    }
    return this.define_computed_property(prop_name, getter, use_cache);
  };

  HasProps.prototype._remove_computed_property = function(prop_name) {
    var dep, dependencies, fld, j, l, len, len1, obj, prop_spec, ref;
    prop_spec = this._computed[prop_name];
    dependencies = prop_spec.dependencies;
    for (j = 0, len = dependencies.length; j < len; j++) {
      dep = dependencies[j];
      obj = dep.obj;
      ref = dep['fields'];
      for (l = 0, len1 = ref.length; l < len1; l++) {
        fld = ref[l];
        obj.off('change:' + fld, prop_spec['callbacks']['changedep'], this);
      }
    }
    this.off("changedep:" + dep);
    return delete this._computed[prop_name];
  };

  HasProps.prototype.get = function(prop_name) {
    if (_.has(this._computed, prop_name)) {
      return this._get_prop(prop_name);
    } else {
      if (!(prop_name === "id" || this.props[prop_name])) {
        throw new Error(this.type + ".get('" + prop_name + "'): " + prop_name + " wasn't declared");
      }
      return HasProps.__super__.get.call(this, prop_name);
    }
  };

  HasProps.prototype._get_prop = function(prop_name) {
    var computed, getter, prop_spec;
    prop_spec = this._computed[prop_name];
    if (prop_spec.use_cache && prop_spec.cache) {
      return prop_spec.cache;
    } else {
      getter = prop_spec.getter;
      computed = getter.apply(this, [prop_name]);
      if (prop_spec.use_cache) {
        prop_spec.cache = computed;
      }
      return computed;
    }
  };

  HasProps.prototype.ref = function() {
    return refs.create_ref(this);
  };

  HasProps.prototype.set_subtype = function(subtype) {
    return this._subtype = subtype;
  };

  HasProps.prototype.sync = function(method, model, options) {
    return options.success(model.attributes, null, {});
  };

  HasProps.prototype.defaults = function() {
    throw new Error("don't use HasProps.defaults anymore");
  };

  HasProps.prototype.attribute_is_serializable = function(attr) {
    var prop;
    if (attr === "id") {
      return true;
    }
    prop = this.props[attr];
    if (prop == null) {
      throw new Error(this.type + ".attribute_is_serializable('" + attr + "'): " + attr + " wasn't declared");
    }
    return !prop.internal;
  };

  HasProps.prototype.serializable_attributes = function() {
    var attrs, name, ref, value;
    attrs = {};
    ref = this.attributes;
    for (name in ref) {
      value = ref[name];
      if (this.attribute_is_serializable(name)) {
        attrs[name] = value;
      }
    }
    return attrs;
  };

  HasProps.prototype.toJSON = function(options) {
    throw new Error("bug: toJSON should not be called on " + this + ", models require special serialization measures");
  };

  HasProps._value_to_json = function(key, value, optional_parent_object) {
    var i, j, len, ref_array, ref_obj, subkey, v;
    if (value instanceof HasProps) {
      return value.ref();
    } else if (_.isArray(value)) {
      ref_array = [];
      for (i = j = 0, len = value.length; j < len; i = ++j) {
        v = value[i];
        ref_array.push(HasProps._value_to_json(i, v, value));
      }
      return ref_array;
    } else if (_.isObject(value)) {
      ref_obj = {};
      for (subkey in value) {
        if (!hasProp.call(value, subkey)) continue;
        ref_obj[subkey] = HasProps._value_to_json(subkey, value[subkey], value);
      }
      return ref_obj;
    } else {
      return value;
    }
  };

  HasProps.prototype.attributes_as_json = function(include_defaults, value_to_json) {
    var attrs, key, ref, value;
    if (include_defaults == null) {
      include_defaults = true;
    }
    if (value_to_json == null) {
      value_to_json = HasProps._value_to_json;
    }
    attrs = {};
    ref = this.serializable_attributes();
    for (key in ref) {
      if (!hasProp.call(ref, key)) continue;
      value = ref[key];
      if (include_defaults) {
        attrs[key] = value;
      } else if (key in this._set_after_defaults) {
        attrs[key] = value;
      }
    }
    return value_to_json("attributes", attrs, this);
  };

  HasProps._json_record_references = function(doc, v, result, recurse) {
    var elem, j, k, len, model, results, results1;
    if (v === null) {

    } else if (refs.is_ref(v)) {
      if (!(v.id in result)) {
        model = doc.get_model_by_id(v.id);
        return HasProps._value_record_references(model, result, recurse);
      }
    } else if (_.isArray(v)) {
      results = [];
      for (j = 0, len = v.length; j < len; j++) {
        elem = v[j];
        results.push(HasProps._json_record_references(doc, elem, result, recurse));
      }
      return results;
    } else if (_.isObject(v)) {
      results1 = [];
      for (k in v) {
        if (!hasProp.call(v, k)) continue;
        elem = v[k];
        results1.push(HasProps._json_record_references(doc, elem, result, recurse));
      }
      return results1;
    }
  };

  HasProps._value_record_references = function(v, result, recurse) {
    var elem, immediate, j, k, l, len, len1, obj, results, results1, results2;
    if (v === null) {

    } else if (v instanceof HasProps) {
      if (!(v.id in result)) {
        result[v.id] = v;
        if (recurse) {
          immediate = v._immediate_references();
          results = [];
          for (j = 0, len = immediate.length; j < len; j++) {
            obj = immediate[j];
            results.push(HasProps._value_record_references(obj, result, true));
          }
          return results;
        }
      }
    } else if (_.isArray(v)) {
      results1 = [];
      for (l = 0, len1 = v.length; l < len1; l++) {
        elem = v[l];
        results1.push(HasProps._value_record_references(elem, result, recurse));
      }
      return results1;
    } else if (_.isObject(v)) {
      results2 = [];
      for (k in v) {
        if (!hasProp.call(v, k)) continue;
        elem = v[k];
        results2.push(HasProps._value_record_references(elem, result, recurse));
      }
      return results2;
    }
  };

  HasProps.prototype._immediate_references = function() {
    var attrs, key, result, value;
    result = {};
    attrs = this.serializable_attributes();
    for (key in attrs) {
      value = attrs[key];
      HasProps._value_record_references(value, result, false);
    }
    return _.values(result);
  };

  HasProps.prototype.references = function() {
    var references;
    references = {};
    HasProps._value_record_references(this, references, true);
    return _.values(references);
  };

  HasProps.prototype.attach_document = function(doc) {
    var name, prop, ref;
    if (this.document !== null && this.document !== doc) {
      throw new Error("models must be owned by only a single document");
    }
    this.document = doc;
    ref = this.properties;
    for (name in ref) {
      prop = ref[name];
      prop.update();
    }
    if (this._doc_attached != null) {
      return this._doc_attached();
    }
  };

  HasProps.prototype.detach_document = function() {
    return this.document = null;
  };

  HasProps.prototype._tell_document_about_change = function(attr, old, new_) {
    var need_invalidate, new_id, new_ref, new_refs, old_id, old_ref, old_refs;
    if (!this.attribute_is_serializable(attr)) {
      return;
    }
    if (this.document !== null) {
      new_refs = {};
      HasProps._value_record_references(new_, new_refs, false);
      old_refs = {};
      HasProps._value_record_references(old, old_refs, false);
      need_invalidate = false;
      for (new_id in new_refs) {
        new_ref = new_refs[new_id];
        if (!(new_id in old_refs)) {
          need_invalidate = true;
          break;
        }
      }
      if (!need_invalidate) {
        for (old_id in old_refs) {
          old_ref = old_refs[old_id];
          if (!(old_id in new_refs)) {
            need_invalidate = true;
            break;
          }
        }
      }
      if (need_invalidate) {
        this.document._invalidate_all_models();
      }
      return this.document._notify_change(this, attr, old, new_);
    }
  };

  return HasProps;

})(Backbone.Model);

module.exports = HasProps;

},{"./logging":"core/logging","./property_mixins":"core/property_mixins","./util/refs":"core/util/refs","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"core/layout/layout_canvas":[function(require,module,exports){
var EQ, GE, LayoutCanvas, Model, Strength, Variable, _, p, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ref = require("./solver"), Variable = ref.Variable, EQ = ref.EQ, GE = ref.GE, Strength = ref.Strength;

Model = require("../../model");

p = require("../properties");

LayoutCanvas = (function(superClass) {
  extend(LayoutCanvas, superClass);

  function LayoutCanvas() {
    return LayoutCanvas.__super__.constructor.apply(this, arguments);
  }

  LayoutCanvas.prototype.type = 'LayoutCanvas';

  LayoutCanvas.prototype.initialize = function(attrs, options) {
    LayoutCanvas.__super__.initialize.call(this, attrs, options);
    this._top = new Variable("top " + this.id);
    this._left = new Variable("left " + this.id);
    this._width = new Variable("width " + this.id);
    this._height = new Variable("height " + this.id);
    this._right = new Variable("right " + this.id);
    this._bottom = new Variable("bottom " + this.id);
    this.define_computed_property('height', this._get_var, false);
    this.define_computed_property('width', this._get_var, false);
    this.define_computed_property('right', this._get_var, false);
    this.define_computed_property('left', this._get_var, false);
    this.define_computed_property('top', this._get_var, false);
    return this.define_computed_property('bottom', this._get_var, false);
  };

  LayoutCanvas.internal({
    layout_location: [p.Any]
  });

  LayoutCanvas.prototype.get_edit_variables = function() {
    var editables;
    editables = [];
    editables.push({
      edit_variable: this._top,
      strength: Strength.strong
    });
    editables.push({
      edit_variable: this._left,
      strength: Strength.strong
    });
    editables.push({
      edit_variable: this._width,
      strength: Strength.strong
    });
    editables.push({
      edit_variable: this._height,
      strength: Strength.strong
    });
    return editables;
  };

  LayoutCanvas.prototype.get_constraints = function() {
    return [];
  };

  LayoutCanvas.prototype._get_var = function(prop_name) {
    return this['_' + prop_name].value();
  };

  return LayoutCanvas;

})(Model);

module.exports = {
  Model: LayoutCanvas
};

},{"../../model":"model","../properties":"core/properties","./solver":"core/layout/solver","underscore":"underscore"}],"core/layout/side_panel":[function(require,module,exports){
var ALPHABETIC, BOTTOM, CENTER, EQ, GE, HANGING, LEFT, LayoutCanvas, MIDDLE, RIGHT, SidePanel, TOP, _, _align_lookup, _align_lookup_negative, _align_lookup_positive, _angle_lookup, _baseline_lookup, logger, p, pi2, ref, update_constraints,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ref = require("./solver"), EQ = ref.EQ, GE = ref.GE;

LayoutCanvas = require("./layout_canvas");

p = require("../../core/properties");

logger = require("../../core/logging").logger;

pi2 = Math.PI / 2;

ALPHABETIC = 'alphabetic';

TOP = 'top';

BOTTOM = 'bottom';

MIDDLE = 'middle';

HANGING = 'hanging';

LEFT = 'left';

RIGHT = 'right';

CENTER = 'center';

_angle_lookup = {
  above: {
    parallel: 0,
    normal: -pi2,
    horizontal: 0,
    vertical: -pi2
  },
  below: {
    parallel: 0,
    normal: pi2,
    horizontal: 0,
    vertical: pi2
  },
  left: {
    parallel: -pi2,
    normal: 0,
    horizontal: 0,
    vertical: -pi2
  },
  right: {
    parallel: pi2,
    normal: 0,
    horizontal: 0,
    vertical: pi2
  }
};

_baseline_lookup = {
  above: {
    justified: TOP,
    parallel: ALPHABETIC,
    normal: MIDDLE,
    horizontal: ALPHABETIC,
    vertical: MIDDLE
  },
  below: {
    justified: BOTTOM,
    parallel: HANGING,
    normal: MIDDLE,
    horizontal: HANGING,
    vertical: MIDDLE
  },
  left: {
    justified: TOP,
    parallel: ALPHABETIC,
    normal: MIDDLE,
    horizontal: MIDDLE,
    vertical: ALPHABETIC
  },
  right: {
    justified: TOP,
    parallel: ALPHABETIC,
    normal: MIDDLE,
    horizontal: MIDDLE,
    vertical: ALPHABETIC
  }
};

_align_lookup = {
  above: {
    justified: CENTER,
    parallel: CENTER,
    normal: LEFT,
    horizontal: CENTER,
    vertical: LEFT
  },
  below: {
    justified: CENTER,
    parallel: CENTER,
    normal: LEFT,
    horizontal: CENTER,
    vertical: RIGHT
  },
  left: {
    justified: CENTER,
    parallel: CENTER,
    normal: RIGHT,
    horizontal: RIGHT,
    vertical: CENTER
  },
  right: {
    justified: CENTER,
    parallel: CENTER,
    normal: LEFT,
    horizontal: LEFT,
    vertical: CENTER
  }
};

_align_lookup_negative = {
  above: RIGHT,
  below: LEFT,
  left: RIGHT,
  right: LEFT
};

_align_lookup_positive = {
  above: LEFT,
  below: RIGHT,
  left: RIGHT,
  right: LEFT
};

update_constraints = function(view) {
  var s, side, size, v;
  v = view;
  if (v.model.props.visible != null) {
    if (v.mget('visible') === false) {
      return;
    }
  }
  size = v._get_size();
  if (v._last_size == null) {
    v._last_size = -1;
  }
  if (size === v._last_size) {
    return;
  }
  s = v.model.document.solver();
  v._last_size = size;
  if (v._size_constraint != null) {
    s.remove_constraint(v._size_constraint);
  }
  v._size_constraint = GE(v.model.panel._size, -size);
  s.add_constraint(v._size_constraint);
  if (v._full_set == null) {
    v._full_set = false;
  }
  if (!v._full_set) {
    side = v.model.panel.get('side');
    if (side === 'above' || side === 'below') {
      s.add_constraint(EQ(v.model.panel._width, [-1, v.plot_model.canvas._width]));
    }
    if (side === 'left' || side === 'right') {
      s.add_constraint(EQ(v.model.panel._height, [-1, v.plot_model.canvas._height]));
    }
    return v._full_set = true;
  }
};

SidePanel = (function(superClass) {
  extend(SidePanel, superClass);

  function SidePanel() {
    return SidePanel.__super__.constructor.apply(this, arguments);
  }

  SidePanel.internal({
    side: [p.String],
    plot: [p.Instance]
  });

  SidePanel.prototype.initialize = function(attrs, options) {
    var side;
    SidePanel.__super__.initialize.call(this, attrs, options);
    side = this.get('side');
    if (side === "above") {
      this._dim = 0;
      this._normals = [0, -1];
      this._size = this._height;
      return this._anchor = this._bottom;
    } else if (side === "below") {
      this._dim = 0;
      this._normals = [0, 1];
      this._size = this._height;
      return this._anchor = this._top;
    } else if (side === "left") {
      this._dim = 1;
      this._normals = [-1, 0];
      this._size = this._width;
      return this._anchor = this._right;
    } else if (side === "right") {
      this._dim = 1;
      this._normals = [1, 0];
      this._size = this._width;
      return this._anchor = this._left;
    } else {
      return logger.error("unrecognized side: '" + side + "'");
    }
  };

  SidePanel.prototype.get_constraints = function() {
    var constraints;
    constraints = [];
    constraints.push(GE(this._top));
    constraints.push(GE(this._bottom));
    constraints.push(GE(this._left));
    constraints.push(GE(this._right));
    constraints.push(GE(this._width));
    constraints.push(GE(this._height));
    constraints.push(EQ(this._left, this._width, [-1, this._right]));
    constraints.push(EQ(this._bottom, this._height, [-1, this._top]));
    return constraints;
  };

  SidePanel.prototype.apply_label_text_heuristics = function(ctx, orient) {
    var align, baseline, side;
    side = this.get('side');
    if (_.isString(orient)) {
      baseline = _baseline_lookup[side][orient];
      align = _align_lookup[side][orient];
    } else if (orient === 0) {
      baseline = _baseline_lookup[side][orient];
      align = _align_lookup[side][orient];
    } else if (orient < 0) {
      baseline = 'middle';
      align = _align_lookup_negative[side];
    } else if (orient > 0) {
      baseline = 'middle';
      align = _align_lookup_positive[side];
    }
    ctx.textBaseline = baseline;
    ctx.textAlign = align;
    return ctx;
  };

  SidePanel.prototype.get_label_angle_heuristic = function(orient) {
    var side;
    side = this.get('side');
    return _angle_lookup[side][orient];
  };

  return SidePanel;

})(LayoutCanvas.Model);

module.exports = {
  Model: SidePanel,
  update_constraints: update_constraints
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./layout_canvas":"core/layout/layout_canvas","./solver":"core/layout/solver","underscore":"underscore"}],"core/layout/solver":[function(require,module,exports){
var Backbone, Constraint, Expression, Operator, Solver, Strength, Variable, _, _constrainer, _weak_constrainer, kiwi;

_ = require("underscore");

Backbone = require("backbone");

kiwi = require("kiwi");

Variable = kiwi.Variable, Expression = kiwi.Expression, Constraint = kiwi.Constraint, Operator = kiwi.Operator, Strength = kiwi.Strength;

_constrainer = function(op) {
  return (function(_this) {
    return function() {
      var expr;
      expr = Object.create(Expression.prototype);
      Expression.apply(expr, arguments);
      return new Constraint(expr, op);
    };
  })(this);
};

_weak_constrainer = function(op) {
  return function() {
    var arg, args, i, len;
    args = [null];
    for (i = 0, len = arguments.length; i < len; i++) {
      arg = arguments[i];
      args.push(arg);
    }
    return new Constraint(new (Function.prototype.bind.apply(Expression, args)), op, kiwi.Strength.weak);
  };
};

Solver = (function() {
  function Solver() {
    this.solver = new kiwi.Solver();
  }

  Solver.prototype.clear = function() {
    return this.solver = new kiwi.Solver();
  };

  Solver.prototype.toString = function() {
    return "Solver[num_constraints=" + (this.num_constraints()) + ", num_edit_variables=" + (this.num_edit_variables()) + "]";
  };

  Solver.prototype.num_constraints = function() {
    return this.solver._cnMap._array.length;
  };

  Solver.prototype.num_edit_variables = function() {
    return this.solver._editMap._array.length;
  };

  Solver.prototype.update_variables = function(trigger) {
    if (trigger == null) {
      trigger = true;
    }
    this.solver.updateVariables();
    if (trigger) {
      return this.trigger('layout_update');
    }
  };

  Solver.prototype.add_constraint = function(constraint) {
    return this.solver.addConstraint(constraint);
  };

  Solver.prototype.remove_constraint = function(constraint) {
    return this.solver.removeConstraint(constraint);
  };

  Solver.prototype.add_edit_variable = function(variable, strength) {
    return this.solver.addEditVariable(variable, strength);
  };

  Solver.prototype.remove_edit_variable = function(variable) {
    return this.solver.removeEditVariable(variable, strength);
  };

  Solver.prototype.suggest_value = function(variable, value) {
    return this.solver.suggestValue(variable, value);
  };

  return Solver;

})();

_.extend(Solver.prototype, Backbone.Events);

module.exports = {
  Variable: Variable,
  Expression: Expression,
  Constraint: Constraint,
  Operator: Operator,
  Strength: Strength,
  EQ: _constrainer(Operator.Eq),
  LE: _constrainer(Operator.Le),
  GE: _constrainer(Operator.Ge),
  WEAK_EQ: _weak_constrainer(Operator.Eq),
  WEAK_LE: _weak_constrainer(Operator.Le),
  WEAK_GE: _weak_constrainer(Operator.Ge),
  Solver: Solver
};

},{"backbone":"backbone","kiwi":"kiwi","underscore":"underscore"}],"core/logging":[function(require,module,exports){
var JL, levels, logger, set_log_level;

JL = require("jsnlog").JL;

logger = JL("Bokeh");

logger.setOptions({
  "appenders": [JL.createConsoleAppender('consoleAppender')],
  "level": JL.getInfoLevel()
});

levels = {
  "trace": JL.getTraceLevel(),
  "debug": JL.getDebugLevel(),
  "info": JL.getInfoLevel(),
  "warn": JL.getWarnLevel(),
  "error": JL.getErrorLevel(),
  "fatal": JL.getFatalLevel()
};

set_log_level = function(level) {
  if (!(level in levels)) {
    console.log("Bokeh: Unrecognized logging level '" + level + "' passed to Bokeh.set_log_level, ignoring.");
    console.log("Bokeh: Valid log levels are: " + (Object.keys(levels)));
    return;
  }
  console.log("Bokeh: setting log level to: '" + level + "'");
  logger.setOptions({
    "level": levels[level]
  });
  return null;
};

module.exports = {
  levels: levels,
  logger: logger,
  set_log_level: set_log_level
};

},{"jsnlog":"jsnlog"}],"core/properties":[function(require,module,exports){
var Anchor, Angle, AngleSpec, AngleUnits, Any, Array, Backbone, Bool, Color, ColorSpec, Dimension, Direction, DirectionSpec, Distance, DistanceSpec, Distribution, Font, FontSizeSpec, FontStyle, Instance, LegendLocation, LineCap, LineJoin, Location, Number, NumberSpec, Orientation, Property, RenderLevel, RenderMode, SizingMode, SpatialUnits, String, StringSpec, TextAlign, TextBaseline, TransformStepMode, _, enum_prop, enums, simple_prop, svg_colors, units_prop, valid_rgb,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

_ = require("underscore");

Backbone = require("backbone");

enums = require("./enums");

svg_colors = require("./util/svg_colors");

valid_rgb = require("./util/color").valid_rgb;

Property = (function(superClass) {
  extend(Property, superClass);

  function Property() {
    return Property.__super__.constructor.apply(this, arguments);
  }

  Property.prototype.dataspec = false;

  Property.prototype.specifiers = ['field', 'value'];

  Property.prototype.initialize = function(attrs, options) {
    var attr, obj;
    Property.__super__.initialize.call(this, attrs, options);
    this._init(false);
    obj = this.get('obj');
    attr = this.get('attr');
    this.listenTo(obj, "change:" + attr, function() {
      this._init();
      return obj.trigger("propchange");
    });
    this.listenTo(this, "change:obj", function() {
      throw new Error("attempted to reset 'obj' on Property");
    });
    return this.listenTo(this, "change:attr", function() {
      throw new Error("attempted to reset 'attr' on Property");
    });
  };

  Property.prototype.update = function() {
    return this._init();
  };

  Property.prototype.init = function() {};

  Property.prototype.transform = function(values) {
    return values;
  };

  Property.prototype.validate = function(value) {};

  Property.prototype.value = function(do_spec_transform) {
    var ret;
    if (do_spec_transform == null) {
      do_spec_transform = true;
    }
    if (_.isUndefined(this.spec.value)) {
      throw new Error("attempted to retrieve property value for property without value specification");
    }
    ret = this.transform([this.spec.value])[0];
    if ((this.spec.transform != null) && do_spec_transform) {
      ret = this.spec.transform.compute(ret);
    }
    return ret;
  };

  Property.prototype.array = function(source) {
    var data, i, length, ret, value;
    if (!this.dataspec) {
      throw new Error("attempted to retrieve property array for non-dataspec property");
    }
    data = source.get('data');
    if (this.spec.field != null) {
      if (this.spec.field in data) {
        ret = this.transform(source.get_column(this.spec.field));
      } else {
        throw new Error("attempted to retrieve property array for nonexistent field '" + this.spec.field + "'");
      }
    } else {
      length = source.get_length();
      if (length == null) {
        length = 1;
      }
      value = this.value(false);
      ret = (function() {
        var j, ref, results;
        results = [];
        for (i = j = 0, ref = length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
          results.push(value);
        }
        return results;
      })();
    }
    if (this.spec.transform != null) {
      ret = this.spec.transform.v_compute(ret);
    }
    return ret;
  };

  Property.prototype._init = function(trigger) {
    var attr, attr_value, default_value, obj;
    if (trigger == null) {
      trigger = true;
    }
    obj = this.get('obj');
    if (obj == null) {
      throw new Error("missing property object");
    }
    if (obj.properties == null) {
      throw new Error("property object must be a HasProps");
    }
    attr = this.get('attr');
    if (attr == null) {
      throw new Error("missing property attr");
    }
    attr_value = obj.get(attr);
    if (_.isUndefined(attr_value)) {
      default_value = this.get('default_value');
      attr_value = (function() {
        switch (false) {
          case !_.isUndefined(default_value):
            return null;
          case !_.isArray(default_value):
            return _.clone(default_value);
          case !_.isFunction(default_value):
            return default_value(obj);
          default:
            return default_value;
        }
      })();
      obj.set(attr, attr_value, {
        silent: true,
        defaults: true
      });
    }
    if (_.isArray(attr_value)) {
      this.spec = {
        value: attr_value
      };
    } else if (_.isObject(attr_value) && _.size(_.pick.apply(null, [attr_value].concat(this.specifiers))) === 1) {
      this.spec = attr_value;
    } else {
      this.spec = {
        value: attr_value
      };
    }
    if ((this.spec.field != null) && !_.isString(this.spec.field)) {
      throw new Error("field value for property '" + attr + "' is not a string");
    }
    if (this.spec.value != null) {
      this.validate(this.spec.value);
    }
    this.init();
    if (trigger) {
      return this.trigger("change");
    }
  };

  return Property;

})(Backbone.Model);

simple_prop = function(name, pred) {
  var Prop;
  return Prop = (function(superClass) {
    extend(Prop, superClass);

    function Prop() {
      return Prop.__super__.constructor.apply(this, arguments);
    }

    Prop.prototype.toString = function() {
      return name + "(obj: " + (this.get(obj).id) + ", spec: " + (JSON.stringify(this.spec)) + ")";
    };

    Prop.prototype.validate = function(value) {
      var attr;
      if (!pred(value)) {
        attr = this.get('attr');
        throw new Error(name + " property '" + attr + "' given invalid value: " + value);
      }
    };

    return Prop;

  })(Property);
};

Any = (function(superClass) {
  extend(Any, superClass);

  function Any() {
    return Any.__super__.constructor.apply(this, arguments);
  }

  return Any;

})(simple_prop("Any", function(x) {
  return true;
}));

Array = (function(superClass) {
  extend(Array, superClass);

  function Array() {
    return Array.__super__.constructor.apply(this, arguments);
  }

  return Array;

})(simple_prop("Array", function(x) {
  return _.isArray(x) || x instanceof Float64Array;
}));

Bool = (function(superClass) {
  extend(Bool, superClass);

  function Bool() {
    return Bool.__super__.constructor.apply(this, arguments);
  }

  return Bool;

})(simple_prop("Bool", _.isBoolean));

Color = (function(superClass) {
  extend(Color, superClass);

  function Color() {
    return Color.__super__.constructor.apply(this, arguments);
  }

  return Color;

})(simple_prop("Color", function(x) {
  return (svg_colors[x.toLowerCase()] != null) || x.substring(0, 1) === "#" || valid_rgb(x);
}));

Instance = (function(superClass) {
  extend(Instance, superClass);

  function Instance() {
    return Instance.__super__.constructor.apply(this, arguments);
  }

  return Instance;

})(simple_prop("Instance", function(x) {
  return x.properties != null;
}));

Number = (function(superClass) {
  extend(Number, superClass);

  function Number() {
    return Number.__super__.constructor.apply(this, arguments);
  }

  return Number;

})(simple_prop("Number", function(x) {
  return _.isNumber(x) || _.isBoolean(x);
}));

String = (function(superClass) {
  extend(String, superClass);

  function String() {
    return String.__super__.constructor.apply(this, arguments);
  }

  return String;

})(simple_prop("String", _.isString));

Font = (function(superClass) {
  extend(Font, superClass);

  function Font() {
    return Font.__super__.constructor.apply(this, arguments);
  }

  return Font;

})(String);

enum_prop = function(name, enum_values) {
  var Enum;
  return Enum = (function(superClass) {
    extend(Enum, superClass);

    function Enum() {
      return Enum.__super__.constructor.apply(this, arguments);
    }

    Enum.prototype.toString = function() {
      return name + "(obj: " + (this.get(obj).id) + ", spec: " + (JSON.stringify(this.spec)) + ")";
    };

    return Enum;

  })(simple_prop(name, function(x) {
    return indexOf.call(enum_values, x) >= 0;
  }));
};

Anchor = (function(superClass) {
  extend(Anchor, superClass);

  function Anchor() {
    return Anchor.__super__.constructor.apply(this, arguments);
  }

  return Anchor;

})(enum_prop("Anchor", enums.LegendLocation));

AngleUnits = (function(superClass) {
  extend(AngleUnits, superClass);

  function AngleUnits() {
    return AngleUnits.__super__.constructor.apply(this, arguments);
  }

  return AngleUnits;

})(enum_prop("AngleUnits", enums.AngleUnits));

Direction = (function(superClass) {
  extend(Direction, superClass);

  function Direction() {
    return Direction.__super__.constructor.apply(this, arguments);
  }

  Direction.prototype.transform = function(values) {
    var i, j, ref, result;
    result = new Uint8Array(values.length);
    for (i = j = 0, ref = values.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      switch (values[i]) {
        case 'clock':
          result[i] = false;
          break;
        case 'anticlock':
          result[i] = true;
      }
    }
    return result;
  };

  return Direction;

})(enum_prop("Direction", enums.Direction));

Dimension = (function(superClass) {
  extend(Dimension, superClass);

  function Dimension() {
    return Dimension.__super__.constructor.apply(this, arguments);
  }

  return Dimension;

})(enum_prop("Dimension", enums.Dimension));

FontStyle = (function(superClass) {
  extend(FontStyle, superClass);

  function FontStyle() {
    return FontStyle.__super__.constructor.apply(this, arguments);
  }

  return FontStyle;

})(enum_prop("FontStyle", enums.FontStyle));

LineCap = (function(superClass) {
  extend(LineCap, superClass);

  function LineCap() {
    return LineCap.__super__.constructor.apply(this, arguments);
  }

  return LineCap;

})(enum_prop("LineCap", enums.LineCap));

LineJoin = (function(superClass) {
  extend(LineJoin, superClass);

  function LineJoin() {
    return LineJoin.__super__.constructor.apply(this, arguments);
  }

  return LineJoin;

})(enum_prop("LineJoin", enums.LineJoin));

LegendLocation = (function(superClass) {
  extend(LegendLocation, superClass);

  function LegendLocation() {
    return LegendLocation.__super__.constructor.apply(this, arguments);
  }

  return LegendLocation;

})(enum_prop("LegendLocation", enums.LegendLocation));

Location = (function(superClass) {
  extend(Location, superClass);

  function Location() {
    return Location.__super__.constructor.apply(this, arguments);
  }

  return Location;

})(enum_prop("Location", enums.Location));

Orientation = (function(superClass) {
  extend(Orientation, superClass);

  function Orientation() {
    return Orientation.__super__.constructor.apply(this, arguments);
  }

  return Orientation;

})(enum_prop("Orientation", enums.Orientation));

TextAlign = (function(superClass) {
  extend(TextAlign, superClass);

  function TextAlign() {
    return TextAlign.__super__.constructor.apply(this, arguments);
  }

  return TextAlign;

})(enum_prop("TextAlign", enums.TextAlign));

TextBaseline = (function(superClass) {
  extend(TextBaseline, superClass);

  function TextBaseline() {
    return TextBaseline.__super__.constructor.apply(this, arguments);
  }

  return TextBaseline;

})(enum_prop("TextBaseline", enums.TextBaseline));

RenderLevel = (function(superClass) {
  extend(RenderLevel, superClass);

  function RenderLevel() {
    return RenderLevel.__super__.constructor.apply(this, arguments);
  }

  return RenderLevel;

})(enum_prop("RenderLevel", enums.RenderLevel));

RenderMode = (function(superClass) {
  extend(RenderMode, superClass);

  function RenderMode() {
    return RenderMode.__super__.constructor.apply(this, arguments);
  }

  return RenderMode;

})(enum_prop("RenderMode", enums.RenderMode));

SizingMode = (function(superClass) {
  extend(SizingMode, superClass);

  function SizingMode() {
    return SizingMode.__super__.constructor.apply(this, arguments);
  }

  return SizingMode;

})(enum_prop("SizingMode", enums.SizingMode));

SpatialUnits = (function(superClass) {
  extend(SpatialUnits, superClass);

  function SpatialUnits() {
    return SpatialUnits.__super__.constructor.apply(this, arguments);
  }

  return SpatialUnits;

})(enum_prop("SpatialUnits", enums.SpatialUnits));

Distribution = (function(superClass) {
  extend(Distribution, superClass);

  function Distribution() {
    return Distribution.__super__.constructor.apply(this, arguments);
  }

  return Distribution;

})(enum_prop("Distribution", enums.DistributionTypes));

TransformStepMode = (function(superClass) {
  extend(TransformStepMode, superClass);

  function TransformStepMode() {
    return TransformStepMode.__super__.constructor.apply(this, arguments);
  }

  return TransformStepMode;

})(enum_prop("TransformStepMode", enums.TransformStepModes));

units_prop = function(name, valid_units, default_units) {
  var UnitsProp;
  return UnitsProp = (function(superClass) {
    extend(UnitsProp, superClass);

    function UnitsProp() {
      return UnitsProp.__super__.constructor.apply(this, arguments);
    }

    UnitsProp.prototype.toString = function() {
      return name + "(obj: " + (this.get(obj).id) + ", spec: " + (JSON.stringify(this.spec)) + ")";
    };

    UnitsProp.prototype.init = function() {
      var units;
      if (this.spec.units == null) {
        this.spec.units = default_units;
      }
      this.units = this.spec.units;
      units = this.spec.units;
      if (indexOf.call(valid_units, units) < 0) {
        throw new Error(name + " units must be one of " + valid_units + ", given invalid value: " + units);
      }
    };

    return UnitsProp;

  })(Number);
};

Angle = (function(superClass) {
  extend(Angle, superClass);

  function Angle() {
    return Angle.__super__.constructor.apply(this, arguments);
  }

  Angle.prototype.transform = function(values) {
    var x;
    if (this.spec.units === "deg") {
      values = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = values.length; j < len; j++) {
          x = values[j];
          results.push(x * Math.PI / 180.0);
        }
        return results;
      })();
    }
    values = (function() {
      var j, len, results;
      results = [];
      for (j = 0, len = values.length; j < len; j++) {
        x = values[j];
        results.push(-x);
      }
      return results;
    })();
    return Angle.__super__.transform.call(this, values);
  };

  return Angle;

})(units_prop("Angle", enums.AngleUnits, "rad"));

Distance = (function(superClass) {
  extend(Distance, superClass);

  function Distance() {
    return Distance.__super__.constructor.apply(this, arguments);
  }

  return Distance;

})(units_prop("Distance", enums.SpatialUnits, "data"));

AngleSpec = (function(superClass) {
  extend(AngleSpec, superClass);

  function AngleSpec() {
    return AngleSpec.__super__.constructor.apply(this, arguments);
  }

  AngleSpec.prototype.dataspec = true;

  return AngleSpec;

})(Angle);

ColorSpec = (function(superClass) {
  extend(ColorSpec, superClass);

  function ColorSpec() {
    return ColorSpec.__super__.constructor.apply(this, arguments);
  }

  ColorSpec.prototype.dataspec = true;

  return ColorSpec;

})(Color);

DirectionSpec = (function(superClass) {
  extend(DirectionSpec, superClass);

  function DirectionSpec() {
    return DirectionSpec.__super__.constructor.apply(this, arguments);
  }

  DirectionSpec.prototype.dataspec = true;

  return DirectionSpec;

})(Distance);

DistanceSpec = (function(superClass) {
  extend(DistanceSpec, superClass);

  function DistanceSpec() {
    return DistanceSpec.__super__.constructor.apply(this, arguments);
  }

  DistanceSpec.prototype.dataspec = true;

  return DistanceSpec;

})(Distance);

FontSizeSpec = (function(superClass) {
  extend(FontSizeSpec, superClass);

  function FontSizeSpec() {
    return FontSizeSpec.__super__.constructor.apply(this, arguments);
  }

  FontSizeSpec.prototype.dataspec = true;

  return FontSizeSpec;

})(String);

NumberSpec = (function(superClass) {
  extend(NumberSpec, superClass);

  function NumberSpec() {
    return NumberSpec.__super__.constructor.apply(this, arguments);
  }

  NumberSpec.prototype.dataspec = true;

  return NumberSpec;

})(Number);

StringSpec = (function(superClass) {
  extend(StringSpec, superClass);

  function StringSpec() {
    return StringSpec.__super__.constructor.apply(this, arguments);
  }

  StringSpec.prototype.dataspec = true;

  return StringSpec;

})(String);

module.exports = {
  Property: Property,
  simple_prop: simple_prop,
  enum_prop: enum_prop,
  units_prop: units_prop,
  Anchor: Anchor,
  Any: Any,
  Angle: Angle,
  AngleUnits: AngleUnits,
  Array: Array,
  Bool: Bool,
  Boolean: Bool,
  Color: Color,
  Dimension: Dimension,
  Direction: Direction,
  Distance: Distance,
  Font: Font,
  FontStyle: FontStyle,
  Instance: Instance,
  LegendLocation: LegendLocation,
  LineCap: LineCap,
  LineJoin: LineJoin,
  Location: Location,
  Number: Number,
  Int: Number,
  Orientation: Orientation,
  RenderLevel: RenderLevel,
  RenderMode: RenderMode,
  SizingMode: SizingMode,
  SpatialUnits: SpatialUnits,
  String: String,
  TextAlign: TextAlign,
  TextBaseline: TextBaseline,
  Distribution: Distribution,
  TransformStepMode: TransformStepMode,
  AngleSpec: AngleSpec,
  ColorSpec: ColorSpec,
  DirectionSpec: DirectionSpec,
  DistanceSpec: DistanceSpec,
  FontSizeSpec: FontSizeSpec,
  NumberSpec: NumberSpec,
  StringSpec: StringSpec
};

},{"./enums":"core/enums","./util/color":"core/util/color","./util/svg_colors":"core/util/svg_colors","backbone":"backbone","underscore":"underscore"}],"core/property_mixins":[function(require,module,exports){
var _, _fill_mixin, _gen_mixin, _line_mixin, _text_mixin, create, fill, line, p, text;

_ = require("underscore");

p = require("./properties");

_gen_mixin = function(mixin, prefix) {
  var name, result, type;
  result = {};
  if (prefix == null) {
    prefix = "";
  }
  for (name in mixin) {
    type = mixin[name];
    result[prefix + name] = type;
  }
  return result;
};

_line_mixin = {
  line_color: [p.ColorSpec, 'black'],
  line_width: [p.NumberSpec, 1],
  line_alpha: [p.NumberSpec, 1.0],
  line_join: [p.LineJoin, 'miter'],
  line_cap: [p.LineCap, 'butt'],
  line_dash: [p.Array, []],
  line_dash_offset: [p.Number, 0]
};

line = function(prefix) {
  return _gen_mixin(_line_mixin, prefix);
};

_fill_mixin = {
  fill_color: [p.ColorSpec, 'gray'],
  fill_alpha: [p.NumberSpec, 1.0]
};

fill = function(prefix) {
  return _gen_mixin(_fill_mixin, prefix);
};

_text_mixin = {
  text_font: [p.Font, 'helvetica'],
  text_font_size: [p.FontSizeSpec, '12pt'],
  text_font_style: [p.FontStyle, 'normal'],
  text_color: [p.ColorSpec, '#444444'],
  text_alpha: [p.NumberSpec, 1.0],
  text_align: [p.TextAlign, 'left'],
  text_baseline: [p.TextBaseline, 'bottom']
};

text = function(prefix) {
  return _gen_mixin(_text_mixin, prefix);
};

create = function(configs) {
  var config, i, kind, len, prefix, ref, result;
  result = {};
  for (i = 0, len = configs.length; i < len; i++) {
    config = configs[i];
    ref = config.split(":"), kind = ref[0], prefix = ref[1];
    if (this[kind] == null) {
      throw Error("Unknown property mixin kind '" + kind + "'");
    }
    result = _.extend(result, this[kind](prefix));
  }
  return result;
};

module.exports = {
  line: line,
  fill: fill,
  text: text,
  create: create
};

},{"./properties":"core/properties","underscore":"underscore"}],"core/util/bbox":[function(require,module,exports){
var empty, union;

empty = function() {
  return {
    minX: Infinity,
    minY: Infinity,
    maxX: -Infinity,
    maxY: -Infinity
  };
};

union = function(a, b) {
  var r;
  r = {};
  r.minX = Math.min(a.minX, b.minX);
  r.maxX = Math.max(a.maxX, b.maxX);
  r.minY = Math.min(a.minY, b.minY);
  r.maxY = Math.max(a.maxY, b.maxY);
  return r;
};

module.exports = {
  empty: empty,
  union: union
};

},{}],"core/util/canvas":[function(require,module,exports){
var fixup_ellipse, fixup_image_smoothing, fixup_line_dash, fixup_line_dash_offset, fixup_measure_text, get_scale_ratio;

fixup_line_dash = function(ctx) {
  if (!ctx.setLineDash) {
    ctx.setLineDash = function(dash) {
      ctx.mozDash = dash;
      return ctx.webkitLineDash = dash;
    };
  }
  if (!ctx.getLineDash) {
    return ctx.getLineDash = function() {
      return ctx.mozDash;
    };
  }
};

fixup_line_dash_offset = function(ctx) {
  ctx.setLineDashOffset = function(dash_offset) {
    ctx.lineDashOffset = dash_offset;
    ctx.mozDashOffset = dash_offset;
    return ctx.webkitLineDashOffset = dash_offset;
  };
  return ctx.getLineDashOffset = function() {
    return ctx.mozDashOffset;
  };
};

fixup_image_smoothing = function(ctx) {
  ctx.setImageSmoothingEnabled = function(value) {
    ctx.imageSmoothingEnabled = value;
    ctx.mozImageSmoothingEnabled = value;
    ctx.oImageSmoothingEnabled = value;
    return ctx.webkitImageSmoothingEnabled = value;
  };
  return ctx.getImageSmoothingEnabled = function() {
    var ref;
    return (ref = ctx.imageSmoothingEnabled) != null ? ref : true;
  };
};

fixup_measure_text = function(ctx) {
  if (ctx.measureText && (ctx.html5MeasureText == null)) {
    ctx.html5MeasureText = ctx.measureText;
    return ctx.measureText = function(text) {
      var textMetrics;
      textMetrics = ctx.html5MeasureText(text);
      textMetrics.ascent = ctx.html5MeasureText("m").width * 1.6;
      return textMetrics;
    };
  }
};

get_scale_ratio = function(ctx, hidpi) {
  var backingStoreRatio, devicePixelRatio;
  if (hidpi) {
    devicePixelRatio = window.devicePixelRatio || 1;
    backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
    return devicePixelRatio / backingStoreRatio;
  } else {
    return 1;
  }
};

fixup_ellipse = function(ctx) {
  var ellipse_bezier;
  ellipse_bezier = function(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) {
    var c, rx, ry;
    if (anticlockwise == null) {
      anticlockwise = false;
    }
    c = 0.551784;
    ctx.translate(x, y);
    ctx.rotate(rotation);
    rx = radiusX;
    ry = radiusY;
    if (anticlockwise) {
      rx = -radiusX;
      ry = -radiusY;
    }
    ctx.moveTo(-rx, 0);
    ctx.bezierCurveTo(-rx, ry * c, -rx * c, ry, 0, ry);
    ctx.bezierCurveTo(rx * c, ry, rx, ry * c, rx, 0);
    ctx.bezierCurveTo(rx, -ry * c, rx * c, -ry, 0, -ry);
    ctx.bezierCurveTo(-rx * c, -ry, -rx, -ry * c, -rx, 0);
    ctx.rotate(-rotation);
    ctx.translate(-x, -y);
  };
  if (!ctx.ellipse) {
    return ctx.ellipse = ellipse_bezier;
  }
};

module.exports = {
  fixup_image_smoothing: fixup_image_smoothing,
  fixup_line_dash: fixup_line_dash,
  fixup_line_dash_offset: fixup_line_dash_offset,
  fixup_measure_text: fixup_measure_text,
  get_scale_ratio: get_scale_ratio,
  fixup_ellipse: fixup_ellipse
};

},{}],"core/util/color":[function(require,module,exports){
var _component2hex, color2hex, color2rgba, svg_colors, valid_rgb,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

svg_colors = require("./svg_colors");

_component2hex = function(v) {
  var h;
  h = Number(v).toString(16);
  return h = h.length === 1 ? '0' + h : h;
};

color2hex = function(color) {
  var hex, rgb, v;
  color = color + '';
  if (color.indexOf('#') === 0) {
    return color;
  } else if (svg_colors[color] != null) {
    return svg_colors[color];
  } else if (color.indexOf('rgb') === 0) {
    rgb = color.match(/\d+/g);
    hex = ((function() {
      var j, len, results;
      results = [];
      for (j = 0, len = rgb.length; j < len; j++) {
        v = rgb[j];
        results.push(_component2hex(v));
      }
      return results;
    })()).join('');
    return '#' + hex.slice(0, 8);
  } else {
    return color;
  }
};

color2rgba = function(color, alpha) {
  var hex, i, rgba;
  if (alpha == null) {
    alpha = 1;
  }
  if (!color) {
    return [0, 0, 0, 0];
  }
  hex = color2hex(color);
  hex = hex.replace(/ |#/g, '');
  if (hex.length <= 4) {
    hex = hex.replace(/(.)/g, '$1$1');
  }
  hex = hex.match(/../g);
  rgba = (function() {
    var j, len, results;
    results = [];
    for (j = 0, len = hex.length; j < len; j++) {
      i = hex[j];
      results.push(parseInt(i, 16) / 255);
    }
    return results;
  })();
  while (rgba.length < 3) {
    rgba.push(0);
  }
  if (rgba.length < 4) {
    rgba.push(alpha);
  }
  return rgba.slice(0, 4);
};

valid_rgb = function(value) {
  var contents, params, ref, rgb;
  switch (value.substring(0, 4)) {
    case "rgba":
      params = {
        start: "rgba(",
        len: 4,
        alpha: true
      };
      break;
    case "rgb(":
      params = {
        start: "rgb(",
        len: 3,
        alpha: false
      };
      break;
    default:
      return false;
  }
  if (new RegExp(".*?(\\.).*(,)").test(value)) {
    throw new Error("color expects integers for rgb in rgb/rgba tuple, received " + value);
  }
  contents = value.replace(params.start, "").replace(")", "").split(',').map(parseFloat);
  if (contents.length !== params.len) {
    throw new Error("color expects rgba " + expect_len + "-tuple, received " + value);
  }
  if (params.alpha && !((0 <= (ref = contents[3]) && ref <= 1))) {
    throw new Error("color expects rgba 4-tuple to have alpha value between 0 and 1");
  }
  if (indexOf.call((function() {
    var j, len, ref1, results;
    ref1 = contents.slice(0, 3);
    results = [];
    for (j = 0, len = ref1.length; j < len; j++) {
      rgb = ref1[j];
      results.push((0 <= rgb && rgb <= 255));
    }
    return results;
  })(), false) >= 0) {
    throw new Error("color expects rgb to have value between 0 and 255");
  }
  return true;
};

module.exports = {
  color2hex: color2hex,
  color2rgba: color2rgba,
  valid_rgb: valid_rgb
};

},{"./svg_colors":"core/util/svg_colors"}],"core/util/data_structures":[function(require,module,exports){
var MultiDict, Set, _;

_ = require("underscore");

MultiDict = (function() {
  function MultiDict() {
    this._dict = {};
  }

  MultiDict.prototype._existing = function(key) {
    if (key in this._dict) {
      return this._dict[key];
    } else {
      return null;
    }
  };

  MultiDict.prototype.add_value = function(key, value) {
    var existing;
    if (value === null) {
      throw new Error("Can't put null in this dict");
    }
    if (_.isArray(value)) {
      throw new Error("Can't put arrays in this dict");
    }
    existing = this._existing(key);
    if (existing === null) {
      return this._dict[key] = value;
    } else if (_.isArray(existing)) {
      return existing.push(value);
    } else {
      return this._dict[key] = [existing, value];
    }
  };

  MultiDict.prototype.remove_value = function(key, value) {
    var existing, new_array;
    existing = this._existing(key);
    if (_.isArray(existing)) {
      new_array = _.without(existing, value);
      if (new_array.length > 0) {
        return this._dict[key] = new_array;
      } else {
        return delete this._dict[key];
      }
    } else if (_.isEqual(existing, value)) {
      return delete this._dict[key];
    }
  };

  MultiDict.prototype.get_one = function(key, duplicate_error) {
    var existing;
    existing = this._existing(key);
    if (_.isArray(existing)) {
      if (existing.length === 1) {
        return existing[0];
      } else {
        throw new Error(duplicate_error);
      }
    } else {
      return existing;
    }
  };

  return MultiDict;

})();

Set = (function() {
  function Set(array) {
    if (!array) {
      this.values = [];
    } else {
      if (array.constructor === Set) {
        return new Set(array.values);
      }
      if (array.constructor === Array) {
        this.values = Set.compact(array);
      } else {
        this.values = [array];
      }
    }
  }

  Set.compact = function(array) {
    var item, j, len, newArray;
    newArray = [];
    for (j = 0, len = array.length; j < len; j++) {
      item = array[j];
      if (newArray.indexOf(item) === -1) {
        newArray.push(item);
      }
    }
    return newArray;
  };

  Set.prototype.push = function(item) {
    if (this.missing(item)) {
      return this.values.push(item);
    }
  };

  Set.prototype.remove = function(item) {
    var i;
    i = this.values.indexOf(item);
    return this.values = this.values.slice(0, i).concat(this.values.slice(i + 1));
  };

  Set.prototype.length = function() {
    return this.values.length;
  };

  Set.prototype.includes = function(item) {
    return this.values.indexOf(item) !== -1;
  };

  Set.prototype.missing = function(item) {
    return !this.includes(item);
  };

  Set.prototype.slice = function(from, to) {
    return this.values.slice(from, to);
  };

  Set.prototype.join = function(str) {
    return this.values.join(str);
  };

  Set.prototype.toString = function() {
    return this.join(', ');
  };

  Set.prototype.includes = function(item) {
    return this.values.indexOf(item) !== -1;
  };

  Set.prototype.union = function(set) {
    set = new Set(set);
    return new Set(this.values.concat(set.values));
  };

  Set.prototype.intersect = function(set) {
    var item, j, len, newSet, ref;
    set = new Set(set);
    newSet = new Set;
    ref = set.values;
    for (j = 0, len = ref.length; j < len; j++) {
      item = ref[j];
      if (this.includes(item) && set.includes(item)) {
        newSet.push(item);
      }
    }
    return newSet;
  };

  Set.prototype.diff = function(set) {
    var item, j, len, newSet, ref;
    set = new Set(set);
    newSet = new Set;
    ref = this.values;
    for (j = 0, len = ref.length; j < len; j++) {
      item = ref[j];
      if (set.missing(item)) {
        newSet.push(item);
      }
    }
    return newSet;
  };

  return Set;

})();

module.exports = {
  MultiDict: MultiDict,
  Set: Set
};

},{"underscore":"underscore"}],"core/util/math":[function(require,module,exports){
var angle_between, angle_dist, angle_norm, array_max, array_min, atan2, random, rnorm;

array_min = function(arr) {
  var len, min, val;
  len = arr.length;
  min = Infinity;
  while (len--) {
    val = arr[len];
    if (val < min) {
      min = val;
    }
  }
  return min;
};

array_max = function(arr) {
  var len, max, val;
  len = arr.length;
  max = -Infinity;
  while (len--) {
    val = arr[len];
    if (val > max) {
      max = val;
    }
  }
  return max;
};

angle_norm = function(angle) {
  while (angle < 0) {
    angle += 2 * Math.PI;
  }
  while (angle > 2 * Math.PI) {
    angle -= 2 * Math.PI;
  }
  return angle;
};

angle_dist = function(lhs, rhs) {
  return Math.abs(angle_norm(lhs - rhs));
};

angle_between = function(mid, lhs, rhs, direction) {
  var d;
  mid = angle_norm(mid);
  d = angle_dist(lhs, rhs);
  if (direction === "anticlock") {
    return angle_dist(lhs, mid) <= d && angle_dist(mid, rhs) <= d;
  } else {
    return !(angle_dist(lhs, mid) <= d && angle_dist(mid, rhs) <= d);
  }
};

random = function() {
  return Math.random();
};

atan2 = function(start, end) {
  "Calculate the angle between a line containing start and end points (composed\nof [x, y] arrays) and the positive x-axis.";
  return Math.atan2(end[1] - start[1], end[0] - start[0]);
};

rnorm = function(mu, sigma) {
  var r1, r2, rn;
  r1 = null;
  r2 = null;
  while (true) {
    r1 = random();
    r2 = random();
    r2 = (2 * r2 - 1) * Math.sqrt(2 * (1 / Math.E));
    if (-4 * r1 * r1 * Math.log(r1) >= r2 * r2) {
      break;
    }
  }
  rn = r2 / r1;
  rn = mu + sigma * rn;
  return rn;
};

module.exports = {
  array_min: array_min,
  array_max: array_max,
  angle_norm: angle_norm,
  angle_dist: angle_dist,
  angle_between: angle_between,
  atan2: atan2,
  rnorm: rnorm,
  random: random
};

},{}],"core/util/refs":[function(require,module,exports){
var HasProps, _, convert_to_ref, create_ref, is_ref;

_ = require("underscore");

HasProps = require("../has_props");

create_ref = function(obj) {
  var ref;
  if (!(obj instanceof HasProps.constructor)) {
    throw new Error("can only create refs for HasProps subclasses");
  }
  ref = {
    'type': obj.type,
    'id': obj.id
  };
  if (obj._subtype != null) {
    ref['subtype'] = obj._subtype;
  }
  return ref;
};

is_ref = function(arg) {
  var keys;
  if (_.isObject(arg)) {
    keys = _.keys(arg).sort();
    if (keys.length === 2) {
      return keys[0] === 'id' && keys[1] === 'type';
    }
    if (keys.length === 3) {
      return keys[0] === 'id' && keys[1] === 'subtype' && keys[2] === 'type';
    }
  }
  return false;
};

convert_to_ref = function(value) {
  if (_.isArray(value)) {
    return _.map(value, convert_to_ref);
  } else {
    if (value instanceof HasProps.constructor) {
      return value.ref();
    }
  }
};

module.exports = {
  convert_to_ref: convert_to_ref,
  create_ref: create_ref,
  is_ref: is_ref
};

},{"../has_props":"core/has_props","underscore":"underscore"}],"core/util/svg_colors":[function(require,module,exports){
module.exports = {
  indianred: "#CD5C5C",
  lightcoral: "#F08080",
  salmon: "#FA8072",
  darksalmon: "#E9967A",
  lightsalmon: "#FFA07A",
  crimson: "#DC143C",
  red: "#FF0000",
  firebrick: "#B22222",
  darkred: "#8B0000",
  pink: "#FFC0CB",
  lightpink: "#FFB6C1",
  hotpink: "#FF69B4",
  deeppink: "#FF1493",
  mediumvioletred: "#C71585",
  palevioletred: "#DB7093",
  coral: "#FF7F50",
  tomato: "#FF6347",
  orangered: "#FF4500",
  darkorange: "#FF8C00",
  orange: "#FFA500",
  gold: "#FFD700",
  yellow: "#FFFF00",
  lightyellow: "#FFFFE0",
  lemonchiffon: "#FFFACD",
  lightgoldenrodyellow: "#FAFAD2",
  papayawhip: "#FFEFD5",
  moccasin: "#FFE4B5",
  peachpuff: "#FFDAB9",
  palegoldenrod: "#EEE8AA",
  khaki: "#F0E68C",
  darkkhaki: "#BDB76B",
  lavender: "#E6E6FA",
  thistle: "#D8BFD8",
  plum: "#DDA0DD",
  violet: "#EE82EE",
  orchid: "#DA70D6",
  fuchsia: "#FF00FF",
  magenta: "#FF00FF",
  mediumorchid: "#BA55D3",
  mediumpurple: "#9370DB",
  blueviolet: "#8A2BE2",
  darkviolet: "#9400D3",
  darkorchid: "#9932CC",
  darkmagenta: "#8B008B",
  purple: "#800080",
  indigo: "#4B0082",
  slateblue: "#6A5ACD",
  darkslateblue: "#483D8B",
  mediumslateblue: "#7B68EE",
  greenyellow: "#ADFF2F",
  chartreuse: "#7FFF00",
  lawngreen: "#7CFC00",
  lime: "#00FF00",
  limegreen: "#32CD32",
  palegreen: "#98FB98",
  lightgreen: "#90EE90",
  mediumspringgreen: "#00FA9A",
  springgreen: "#00FF7F",
  mediumseagreen: "#3CB371",
  seagreen: "#2E8B57",
  forestgreen: "#228B22",
  green: "#008000",
  darkgreen: "#006400",
  yellowgreen: "#9ACD32",
  olivedrab: "#6B8E23",
  olive: "#808000",
  darkolivegreen: "#556B2F",
  mediumaquamarine: "#66CDAA",
  darkseagreen: "#8FBC8F",
  lightseagreen: "#20B2AA",
  darkcyan: "#008B8B",
  teal: "#008080",
  aqua: "#00FFFF",
  cyan: "#00FFFF",
  lightcyan: "#E0FFFF",
  paleturquoise: "#AFEEEE",
  aquamarine: "#7FFFD4",
  turquoise: "#40E0D0",
  mediumturquoise: "#48D1CC",
  darkturquoise: "#00CED1",
  cadetblue: "#5F9EA0",
  steelblue: "#4682B4",
  lightsteelblue: "#B0C4DE",
  powderblue: "#B0E0E6",
  lightblue: "#ADD8E6",
  skyblue: "#87CEEB",
  lightskyblue: "#87CEFA",
  deepskyblue: "#00BFFF",
  dodgerblue: "#1E90FF",
  cornflowerblue: "#6495ED",
  royalblue: "#4169E1",
  blue: "#0000FF",
  mediumblue: "#0000CD",
  darkblue: "#00008B",
  navy: "#000080",
  midnightblue: "#191970",
  cornsilk: "#FFF8DC",
  blanchedalmond: "#FFEBCD",
  bisque: "#FFE4C4",
  navajowhite: "#FFDEAD",
  wheat: "#F5DEB3",
  burlywood: "#DEB887",
  tan: "#D2B48C",
  rosybrown: "#BC8F8F",
  sandybrown: "#F4A460",
  goldenrod: "#DAA520",
  darkgoldenrod: "#B8860B",
  peru: "#CD853F",
  chocolate: "#D2691E",
  saddlebrown: "#8B4513",
  sienna: "#A0522D",
  brown: "#A52A2A",
  maroon: "#800000",
  white: "#FFFFFF",
  snow: "#FFFAFA",
  honeydew: "#F0FFF0",
  mintcream: "#F5FFFA",
  azure: "#F0FFFF",
  aliceblue: "#F0F8FF",
  ghostwhite: "#F8F8FF",
  whitesmoke: "#F5F5F5",
  seashell: "#FFF5EE",
  beige: "#F5F5DC",
  oldlace: "#FDF5E6",
  floralwhite: "#FFFAF0",
  ivory: "#FFFFF0",
  antiquewhite: "#FAEBD7",
  linen: "#FAF0E6",
  lavenderblush: "#FFF0F5",
  mistyrose: "#FFE4E1",
  gainsboro: "#DCDCDC",
  lightgray: "#D3D3D3",
  lightgrey: "#D3D3D3",
  silver: "#C0C0C0",
  darkgray: "#A9A9A9",
  darkgrey: "#A9A9A9",
  gray: "#808080",
  grey: "#808080",
  dimgray: "#696969",
  dimgrey: "#696969",
  lightslategray: "#778899",
  lightslategrey: "#778899",
  slategray: "#708090",
  slategrey: "#708090",
  darkslategray: "#2F4F4F",
  darkslategrey: "#2F4F4F",
  black: "#000000"
};

},{}],"core/util/text":[function(require,module,exports){
var $, cache, get_text_height;

$ = require("jquery");

cache = {};

get_text_height = function(font) {
  var block, body, div, result, text;
  if (cache[font] != null) {
    return cache[font];
  }
  text = $('<span>Hg</span>').css({
    font: font
  });
  block = $('<div style="display: inline-block; width: 1px; height: 0px;"> </div>');
  div = $('<div></div>');
  div.append(text, block);
  body = $('body');
  body.append(div);
  try {
    result = {};
    block.css({
      verticalAlign: 'baseline'
    });
    result.ascent = block.offset().top - text.offset().top;
    block.css({
      verticalAlign: 'bottom'
    });
    result.height = block.offset().top - text.offset().top;
    result.descent = result.height - result.ascent;
  } finally {
    div.remove();
  }
  cache[font] = result;
  return result;
};

module.exports = {
  get_text_height: get_text_height
};

},{"jquery":"jquery"}],"core/util/throttle":[function(require,module,exports){
var _delay_animation, delay_animation, throttle;

_delay_animation = function(f) {
  return f();
};

delay_animation = (typeof window !== "undefined" && window !== null ? window.requestAnimationFrame : void 0) || (typeof window !== "undefined" && window !== null ? window.mozRequestAnimationFrame : void 0) || (typeof window !== "undefined" && window !== null ? window.webkitRequestAnimationFrame : void 0) || (typeof window !== "undefined" && window !== null ? window.msRequestAnimationFrame : void 0) || _delay_animation;

throttle = function(func, wait) {
  var args, context, later, pending, previous, ref, result, timeout;
  ref = [null, null, null, null], context = ref[0], args = ref[1], timeout = ref[2], result = ref[3];
  previous = 0;
  pending = false;
  later = function() {
    previous = new Date;
    timeout = null;
    pending = false;
    return result = func.apply(context, args);
  };
  return function() {
    var now, remaining;
    now = new Date;
    remaining = wait - (now - previous);
    context = this;
    args = arguments;
    if (remaining <= 0 && !pending) {
      clearTimeout(timeout);
      pending = true;
      delay_animation(later);
    } else if (!timeout && !pending) {
      timeout = setTimeout((function() {
        return delay_animation(later);
      }), remaining);
    }
    return result;
  };
};

module.exports = {
  throttle: throttle
};

},{}],"core/util/underscore":[function(require,module,exports){
var _, patch;

_ = require("underscore");

patch = function() {
  return _.uniqueId = function(prefix) {
    var hexDigits, i, j, s, uuid;
    s = [];
    hexDigits = "0123456789ABCDEF";
    for (i = j = 0; j <= 31; i = ++j) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);
    uuid = s.join("");
    if (prefix) {
      return prefix + "-" + uuid;
    } else {
      return uuid;
    }
  };
};

_.isNullOrUndefined = function(x) {
  return _.isNull(x) || _.isUndefined(x);
};

_.setdefault = function(obj, key, value) {
  if (_.has(obj, key)) {
    return obj[key];
  } else {
    obj[key] = value;
    return value;
  }
};

module.exports = {
  patch: patch
};

},{"underscore":"underscore"}],"document":[function(require,module,exports){
var $, ColumnDataSource, DEFAULT_TITLE, Document, DocumentChangedEvent, EQ, HasProps, ModelChangedEvent, Models, MultiDict, RootAddedEvent, RootRemovedEvent, Set, Solver, TitleChangedEvent, Variable, _, is_ref, js_version, logger, ref1, ref2,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

_ = require("underscore");

$ = require("jquery");

Models = require("./base").Models;

js_version = require("./version");

ref1 = require("./core/layout/solver"), EQ = ref1.EQ, Solver = ref1.Solver, Variable = ref1.Variable;

logger = require("./core/logging").logger;

HasProps = require("./core/has_props");

is_ref = require("./core/util/refs").is_ref;

ref2 = require("./core/util/data_structures"), MultiDict = ref2.MultiDict, Set = ref2.Set;

ColumnDataSource = require("./models/sources/column_data_source");

DocumentChangedEvent = (function() {
  function DocumentChangedEvent(document) {
    this.document = document;
  }

  return DocumentChangedEvent;

})();

ModelChangedEvent = (function(superClass) {
  extend(ModelChangedEvent, superClass);

  function ModelChangedEvent(document, model1, attr1, old1, new_1) {
    this.document = document;
    this.model = model1;
    this.attr = attr1;
    this.old = old1;
    this.new_ = new_1;
    ModelChangedEvent.__super__.constructor.call(this, this.document);
  }

  ModelChangedEvent.prototype.json = function(references) {
    var id, value, value_json, value_refs;
    if (this.attr === 'id') {
      console.log("'id' field is immutable and should never be in a ModelChangedEvent ", this);
      throw new Error("'id' field should never change, whatever code just set it is wrong");
    }
    value = this.new_;
    value_json = HasProps._value_to_json('new_', value, this.model);
    value_refs = {};
    HasProps._value_record_references(value, value_refs, true);
    if (this.model.id in value_refs && this.model !== value) {
      delete value_refs[this.model.id];
    }
    for (id in value_refs) {
      references[id] = value_refs[id];
    }
    return {
      'kind': 'ModelChanged',
      'model': this.model.ref(),
      'attr': this.attr,
      'new': value_json
    };
  };

  return ModelChangedEvent;

})(DocumentChangedEvent);

TitleChangedEvent = (function(superClass) {
  extend(TitleChangedEvent, superClass);

  function TitleChangedEvent(document, title1) {
    this.document = document;
    this.title = title1;
    TitleChangedEvent.__super__.constructor.call(this, this.document);
  }

  TitleChangedEvent.prototype.json = function(references) {
    return {
      'kind': 'TitleChanged',
      'title': this.title
    };
  };

  return TitleChangedEvent;

})(DocumentChangedEvent);

RootAddedEvent = (function(superClass) {
  extend(RootAddedEvent, superClass);

  function RootAddedEvent(document, model1) {
    this.document = document;
    this.model = model1;
    RootAddedEvent.__super__.constructor.call(this, this.document);
  }

  RootAddedEvent.prototype.json = function(references) {
    HasProps._value_record_references(this.model, references, true);
    return {
      'kind': 'RootAdded',
      'model': this.model.ref()
    };
  };

  return RootAddedEvent;

})(DocumentChangedEvent);

RootRemovedEvent = (function(superClass) {
  extend(RootRemovedEvent, superClass);

  function RootRemovedEvent(document, model1) {
    this.document = document;
    this.model = model1;
    RootRemovedEvent.__super__.constructor.call(this, this.document);
  }

  RootRemovedEvent.prototype.json = function(references) {
    return {
      'kind': 'RootRemoved',
      'model': this.model.ref()
    };
  };

  return RootRemovedEvent;

})(DocumentChangedEvent);

DEFAULT_TITLE = "Bokeh Application";

Document = (function() {
  function Document() {
    this._title = DEFAULT_TITLE;
    this._roots = [];
    this._all_models = {};
    this._all_models_by_name = new MultiDict();
    this._all_models_freeze_count = 0;
    this._callbacks = [];
    this._doc_width = new Variable("document_width");
    this._doc_height = new Variable("document_height");
    this._solver = new Solver();
    this._init_solver();
    $(window).on("resize", $.proxy(this.resize, this));
  }

  Document.prototype._init_solver = function() {
    var j, len, model, ref3, results;
    this._solver.clear();
    this._solver.add_edit_variable(this._doc_width);
    this._solver.add_edit_variable(this._doc_height);
    ref3 = this._roots;
    results = [];
    for (j = 0, len = ref3.length; j < len; j++) {
      model = ref3[j];
      if (model.layoutable) {
        results.push(this._add_layoutable(model));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  Document.prototype.solver = function() {
    return this._solver;
  };

  Document.prototype.resize = function() {
    this._resize();
    return this._resize();
  };

  Document.prototype._resize = function() {
    var height, j, len, measuring, ref3, root, root_div, target_height, vars, width;
    ref3 = this._roots;
    for (j = 0, len = ref3.length; j < len; j++) {
      root = ref3[j];
      if (root.layoutable !== true) {
        continue;
      }
      vars = root.get_constrained_variables();
      if ((vars.width == null) && (vars.height == null)) {
        continue;
      }
      root_div = $("#modelid_" + root.id);
      target_height = 0;
      measuring = root_div;
      while (target_height === 0) {
        measuring = measuring.parent();
        target_height = measuring.height();
      }
      width = measuring.width();
      height = target_height;
      if (vars.width != null) {
        logger.debug("Suggest width on Document -- " + width);
        this._solver.suggest_value(this._doc_width, width);
      }
      if (vars.height != null) {
        logger.debug("Suggest height on Document -- " + height);
        this._solver.suggest_value(this._doc_height, height);
      }
    }
    this._solver.update_variables(false);
    return this._solver.trigger('resize');
  };

  Document.prototype.clear = function() {
    var results;
    this._push_all_models_freeze();
    try {
      results = [];
      while (this._roots.length > 0) {
        results.push(this.remove_root(this._roots[0]));
      }
      return results;
    } finally {
      this._pop_all_models_freeze();
    }
  };

  Document.prototype._destructively_move = function(dest_doc) {
    var j, l, len, len1, r, roots;
    if (dest_doc === this) {
      throw new Error("Attempted to overwrite a document with itself");
    }
    dest_doc.clear();
    roots = [];
    this._push_all_models_freeze();
    try {
      while (this._roots.length > 0) {
        this.remove_root(this._roots[0]);
        roots.push(r);
      }
    } finally {
      this._pop_all_models_freeze();
    }
    for (j = 0, len = roots.length; j < len; j++) {
      r = roots[j];
      if (r.document !== null) {
        throw new Error("Somehow we didn't detach " + r);
      }
    }
    if (_all_models.length !== 0) {
      throw new Error("_all_models still had stuff in it: " + this._all_models);
    }
    for (l = 0, len1 = roots.length; l < len1; l++) {
      r = roots[l];
      dest_doc.add_root(r);
    }
    return dest_doc.set_title(this._title);
  };

  Document.prototype._push_all_models_freeze = function() {
    return this._all_models_freeze_count += 1;
  };

  Document.prototype._pop_all_models_freeze = function() {
    this._all_models_freeze_count -= 1;
    if (this._all_models_freeze_count === 0) {
      return this._recompute_all_models();
    }
  };

  Document.prototype._invalidate_all_models = function() {
    logger.debug("invalidating document models");
    if (this._all_models_freeze_count === 0) {
      return this._recompute_all_models();
    }
  };

  Document.prototype._recompute_all_models = function() {
    var a, d, j, l, len, len1, len2, len3, m, n, name, new_all_models_set, o, old_all_models_set, r, recomputed, ref3, ref4, ref5, ref6, to_attach, to_detach;
    new_all_models_set = new Set();
    ref3 = this._roots;
    for (j = 0, len = ref3.length; j < len; j++) {
      r = ref3[j];
      new_all_models_set = new_all_models_set.union(r.references());
    }
    old_all_models_set = new Set(_.values(this._all_models));
    to_detach = old_all_models_set.diff(new_all_models_set);
    to_attach = new_all_models_set.diff(old_all_models_set);
    recomputed = {};
    ref4 = new_all_models_set.values;
    for (l = 0, len1 = ref4.length; l < len1; l++) {
      m = ref4[l];
      recomputed[m.id] = m;
    }
    ref5 = to_detach.values;
    for (n = 0, len2 = ref5.length; n < len2; n++) {
      d = ref5[n];
      d.detach_document();
      name = d.get('name');
      if (name !== null) {
        this._all_models_by_name.remove_value(name, d);
      }
    }
    ref6 = to_attach.values;
    for (o = 0, len3 = ref6.length; o < len3; o++) {
      a = ref6[o];
      a.attach_document(this);
      name = a.get('name');
      if (name !== null) {
        this._all_models_by_name.add_value(name, a);
      }
    }
    return this._all_models = recomputed;
  };

  Document.prototype.roots = function() {
    return this._roots;
  };

  Document.prototype._add_layoutable = function(model) {
    var constraint, constraints, edit_variable, editables, j, l, len, len1, ref3, strength, vars;
    if (model.layoutable !== true) {
      throw new Error("Cannot add non-layoutable - " + model);
    }
    editables = model.get_edit_variables();
    constraints = model.get_constraints();
    vars = model.get_constrained_variables();
    for (j = 0, len = editables.length; j < len; j++) {
      ref3 = editables[j], edit_variable = ref3.edit_variable, strength = ref3.strength;
      this._solver.add_edit_variable(edit_variable, strength);
    }
    for (l = 0, len1 = constraints.length; l < len1; l++) {
      constraint = constraints[l];
      this._solver.add_constraint(constraint);
    }
    if (vars.width != null) {
      this._solver.add_constraint(EQ(vars.width, this._doc_width));
    }
    if (vars.height != null) {
      this._solver.add_constraint(EQ(vars.height, this._doc_height));
    }
    return this._solver.update_variables();
  };

  Document.prototype.add_root = function(model) {
    logger.debug("Adding root: " + model);
    if (indexOf.call(this._roots, model) >= 0) {
      return;
    }
    this._push_all_models_freeze();
    try {
      this._roots.push(model);
      model._is_root = true;
    } finally {
      this._pop_all_models_freeze();
    }
    this._init_solver();
    return this._trigger_on_change(new RootAddedEvent(this, model));
  };

  Document.prototype.remove_root = function(model) {
    var i;
    i = this._roots.indexOf(model);
    if (i < 0) {
      return;
    }
    this._push_all_models_freeze();
    try {
      this._roots.splice(i, 1);
      model._is_root = false;
    } finally {
      this._pop_all_models_freeze();
    }
    this._init_solver();
    return this._trigger_on_change(new RootRemovedEvent(this, model));
  };

  Document.prototype.title = function() {
    return this._title;
  };

  Document.prototype.set_title = function(title) {
    if (title !== this._title) {
      this._title = title;
      return this._trigger_on_change(new TitleChangedEvent(this, title));
    }
  };

  Document.prototype.get_model_by_id = function(model_id) {
    if (model_id in this._all_models) {
      return this._all_models[model_id];
    } else {
      return null;
    }
  };

  Document.prototype.get_model_by_name = function(name) {
    return this._all_models_by_name.get_one(name, "Multiple models are named '" + name + "'");
  };

  Document.prototype.on_change = function(callback) {
    if (indexOf.call(this._callbacks, callback) >= 0) {
      return;
    }
    return this._callbacks.push(callback);
  };

  Document.prototype.remove_on_change = function(callback) {
    var i;
    i = this._callbacks.indexOf(callback);
    if (i >= 0) {
      return this._callbacks.splice(i, 1);
    }
  };

  Document.prototype._trigger_on_change = function(event) {
    var cb, j, len, ref3, results;
    ref3 = this._callbacks;
    results = [];
    for (j = 0, len = ref3.length; j < len; j++) {
      cb = ref3[j];
      results.push(cb(event));
    }
    return results;
  };

  Document.prototype._notify_change = function(model, attr, old, new_) {
    if (attr === 'name') {
      this._all_models_by_name.remove_value(old, model);
      if (new_ !== null) {
        this._all_models_by_name.add_value(new_, model);
      }
    }
    return this._trigger_on_change(new ModelChangedEvent(this, model, attr, old, new_));
  };

  Document._references_json = function(references, include_defaults) {
    var j, len, r, ref, references_json;
    if (include_defaults == null) {
      include_defaults = true;
    }
    references_json = [];
    for (j = 0, len = references.length; j < len; j++) {
      r = references[j];
      ref = r.ref();
      ref['attributes'] = r.attributes_as_json(include_defaults);
      delete ref['attributes']['id'];
      references_json.push(ref);
    }
    return references_json;
  };

  Document._instantiate_object = function(obj_id, obj_type, obj_attrs) {
    var full_attrs, model;
    full_attrs = _.extend({}, obj_attrs, {
      id: obj_id
    });
    model = Models(obj_type);
    return new model(full_attrs, {
      silent: true,
      defer_initialization: true
    });
  };

  Document._instantiate_references_json = function(references_json, existing_models) {
    var instance, j, len, obj, obj_attrs, obj_id, obj_type, references;
    references = {};
    for (j = 0, len = references_json.length; j < len; j++) {
      obj = references_json[j];
      obj_id = obj['id'];
      obj_type = obj['type'];
      obj_attrs = obj['attributes'];
      if (obj_id in existing_models) {
        instance = existing_models[obj_id];
      } else {
        instance = Document._instantiate_object(obj_id, obj_type, obj_attrs);
        if ('subtype' in obj) {
          instance.set_subtype(obj['subtype']);
        }
      }
      references[instance.id] = instance;
    }
    return references;
  };

  Document._resolve_refs = function(value, old_references, new_references) {
    var resolve_array, resolve_dict, resolve_ref;
    resolve_ref = function(v) {
      if (is_ref(v)) {
        if (v['id'] in old_references) {
          return old_references[v['id']];
        } else if (v['id'] in new_references) {
          return new_references[v['id']];
        } else {
          throw new Error("reference " + (JSON.stringify(v)) + " isn't known (not in Document?)");
        }
      } else if (_.isArray(v)) {
        return resolve_array(v);
      } else if (_.isObject(v)) {
        return resolve_dict(v);
      } else {
        return v;
      }
    };
    resolve_dict = function(dict) {
      var k, resolved, v;
      resolved = {};
      for (k in dict) {
        v = dict[k];
        resolved[k] = resolve_ref(v);
      }
      return resolved;
    };
    resolve_array = function(array) {
      var j, len, results, v;
      results = [];
      for (j = 0, len = array.length; j < len; j++) {
        v = array[j];
        results.push(resolve_ref(v));
      }
      return results;
    };
    return resolve_ref(value);
  };

  Document._initialize_references_json = function(references_json, old_references, new_references) {
    var foreach_depth_first, instance, j, len, obj, obj_attrs, obj_id, to_update, was_new;
    to_update = {};
    for (j = 0, len = references_json.length; j < len; j++) {
      obj = references_json[j];
      obj_id = obj['id'];
      obj_attrs = obj['attributes'];
      was_new = false;
      instance = obj_id in old_references ? old_references[obj_id] : (was_new = true, new_references[obj_id]);
      obj_attrs = Document._resolve_refs(obj_attrs, old_references, new_references);
      to_update[instance.id] = [instance, obj_attrs, was_new];
    }
    foreach_depth_first = function(items, f) {
      var already_started, foreach_value, k, results, v;
      already_started = {};
      foreach_value = function(v, f) {
        var a, attrs, e, k, l, len1, ref3, results, results1, same_as_v;
        if (v instanceof HasProps) {
          if (!(v.id in already_started) && v.id in items) {
            already_started[v.id] = true;
            ref3 = items[v.id], same_as_v = ref3[0], attrs = ref3[1], was_new = ref3[2];
            for (a in attrs) {
              e = attrs[a];
              foreach_value(e, f);
            }
            return f(v, attrs, was_new);
          }
        } else if (_.isArray(v)) {
          results = [];
          for (l = 0, len1 = v.length; l < len1; l++) {
            e = v[l];
            results.push(foreach_value(e, f));
          }
          return results;
        } else if (_.isObject(v)) {
          results1 = [];
          for (k in v) {
            e = v[k];
            results1.push(foreach_value(e, f));
          }
          return results1;
        }
      };
      results = [];
      for (k in items) {
        v = items[k];
        results.push(foreach_value(v[0], f));
      }
      return results;
    };
    foreach_depth_first(to_update, function(instance, attrs, was_new) {
      if (was_new) {
        return instance.set(attrs);
      }
    });
    return foreach_depth_first(to_update, function(instance, attrs, was_new) {
      if (was_new) {
        return instance.initialize(attrs);
      }
    });
  };

  Document._event_for_attribute_change = function(changed_obj, key, new_value, doc, value_refs) {
    var changed_model, event;
    changed_model = doc.get_model_by_id(changed_obj.id);
    if (!changed_model.attribute_is_serializable(key)) {
      return null;
    }
    event = {
      'kind': 'ModelChanged',
      'model': {
        id: changed_obj.id,
        type: changed_obj.type
      },
      'attr': key,
      'new': new_value
    };
    HasProps._json_record_references(doc, new_value, value_refs, true);
    return event;
  };

  Document._events_to_sync_objects = function(from_obj, to_obj, to_doc, value_refs) {
    var added, events, from_keys, j, key, l, len, len1, len2, n, new_value, old_value, removed, shared, to_keys;
    from_keys = Object.keys(from_obj.attributes);
    to_keys = Object.keys(to_obj.attributes);
    removed = _.difference(from_keys, to_keys);
    added = _.difference(to_keys, from_keys);
    shared = _.intersection(from_keys, to_keys);
    events = [];
    for (j = 0, len = removed.length; j < len; j++) {
      key = removed[j];
      logger.warn("Server sent key " + key + " but we don't seem to have it in our JSON");
    }
    for (l = 0, len1 = added.length; l < len1; l++) {
      key = added[l];
      new_value = to_obj.attributes[key];
      events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
    }
    for (n = 0, len2 = shared.length; n < len2; n++) {
      key = shared[n];
      old_value = from_obj.attributes[key];
      new_value = to_obj.attributes[key];
      if (old_value === null && new_value === null) {

      } else if (old_value === null || new_value === null) {
        events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
      } else {
        if (!_.isEqual(old_value, new_value)) {
          events.push(Document._event_for_attribute_change(from_obj, key, new_value, to_doc, value_refs));
        }
      }
    }
    return _.filter(events, function(e) {
      return e !== null;
    });
  };

  Document._compute_patch_since_json = function(from_json, to_doc) {
    var events, from_references, from_root_ids, from_roots, id, include_defaults, j, l, len, len1, model, r, ref3, ref4, ref5, refs, to_json, to_references, to_root_ids, to_roots, update_model_events, value_refs;
    to_json = to_doc.to_json(include_defaults = false);
    refs = function(json) {
      var j, len, obj, ref3, result;
      result = {};
      ref3 = json['roots']['references'];
      for (j = 0, len = ref3.length; j < len; j++) {
        obj = ref3[j];
        result[obj.id] = obj;
      }
      return result;
    };
    from_references = refs(from_json);
    from_roots = {};
    from_root_ids = [];
    ref3 = from_json['roots']['root_ids'];
    for (j = 0, len = ref3.length; j < len; j++) {
      r = ref3[j];
      from_roots[r] = from_references[r];
      from_root_ids.push(r);
    }
    to_references = refs(to_json);
    to_roots = {};
    to_root_ids = [];
    ref4 = to_json['roots']['root_ids'];
    for (l = 0, len1 = ref4.length; l < len1; l++) {
      r = ref4[l];
      to_roots[r] = to_references[r];
      to_root_ids.push(r);
    }
    from_root_ids.sort();
    to_root_ids.sort();
    if (_.difference(from_root_ids, to_root_ids).length > 0 || _.difference(to_root_ids, from_root_ids).length > 0) {
      throw new Error("Not implemented: computing add/remove of document roots");
    }
    value_refs = {};
    events = [];
    ref5 = to_doc._all_models;
    for (id in ref5) {
      model = ref5[id];
      if (id in from_references) {
        update_model_events = Document._events_to_sync_objects(from_references[id], to_references[id], to_doc, value_refs);
        events = events.concat(update_model_events);
      }
    }
    return {
      'events': events,
      'references': Document._references_json(_.values(value_refs), include_defaults = false)
    };
  };

  Document.prototype.to_json_string = function(include_defaults) {
    if (include_defaults == null) {
      include_defaults = true;
    }
    return JSON.stringify(this.to_json(include_defaults));
  };

  Document.prototype.to_json = function(include_defaults) {
    var j, len, r, ref3, root_ids, root_references;
    if (include_defaults == null) {
      include_defaults = true;
    }
    root_ids = [];
    ref3 = this._roots;
    for (j = 0, len = ref3.length; j < len; j++) {
      r = ref3[j];
      root_ids.push(r.id);
    }
    root_references = _.values(this._all_models);
    return {
      'title': this._title,
      'roots': {
        'root_ids': root_ids,
        'references': Document._references_json(root_references, include_defaults)
      }
    };
  };

  Document.from_json_string = function(s) {
    var json;
    if (s === null || (s == null)) {
      throw new Error("JSON string is " + (typeof s));
    }
    json = JSON.parse(s);
    return Document.from_json(json);
  };

  Document.from_json = function(json) {
    var doc, j, len, py_version, r, references, references_json, root_ids, roots_json, versions_string;
    logger.debug("Creating Document from JSON");
    if (typeof json !== 'object') {
      throw new Error("JSON object has wrong type " + (typeof json));
    }
    py_version = json['version'];
    versions_string = "Library versions: JS (" + js_version + ")  /  Python (" + py_version + ")";
    if (js_version.split('-')[0] !== py_version.split('-')[0]) {
      logger.warn("JS/Python version mismatch");
      logger.warn(versions_string);
    } else {
      logger.debug(versions_string);
    }
    roots_json = json['roots'];
    root_ids = roots_json['root_ids'];
    references_json = roots_json['references'];
    references = Document._instantiate_references_json(references_json, {});
    Document._initialize_references_json(references_json, {}, references);
    doc = new Document();
    for (j = 0, len = root_ids.length; j < len; j++) {
      r = root_ids[j];
      doc.add_root(references[r]);
    }
    doc.set_title(json['title']);
    return doc;
  };

  Document.prototype.replace_with_json = function(json) {
    var replacement;
    replacement = Document.from_json(json);
    return replacement._destructively_move(this);
  };

  Document.prototype.create_json_patch_string = function(events) {
    return JSON.stringify(this.create_json_patch(events));
  };

  Document.prototype.create_json_patch = function(events) {
    var event, j, json_events, len, references, result;
    references = {};
    json_events = [];
    for (j = 0, len = events.length; j < len; j++) {
      event = events[j];
      if (event.document !== this) {
        console.log("Cannot create a patch using events from a different document, event had ", event.document, " we are ", this);
        throw new Error("Cannot create a patch using events from a different document");
      }
      json_events.push(event.json(references));
    }
    return result = {
      events: json_events,
      references: Document._references_json(_.values(references))
    };
  };

  Document.prototype.apply_json_patch_string = function(patch) {
    return this.apply_json_patch(JSON.parse(patch));
  };

  Document.prototype.apply_json_patch = function(patch) {
    var attr, column_source, column_source_id, data, event_json, events_json, id, j, l, len, len1, model_id, new_references, obj1, old_references, patched_id, patched_obj, patches, references, references_json, results, rollover, root_id, root_obj, value;
    references_json = patch['references'];
    events_json = patch['events'];
    references = Document._instantiate_references_json(references_json, this._all_models);
    for (j = 0, len = events_json.length; j < len; j++) {
      event_json = events_json[j];
      if ('model' in event_json) {
        model_id = event_json['model']['id'];
        if (model_id in this._all_models) {
          references[model_id] = this._all_models[model_id];
        } else {
          if (!(model_id in references)) {
            console.log("Got an event for unknown model ", event_json['model']);
            throw new Error("event model wasn't known");
          }
        }
      }
    }
    old_references = {};
    new_references = {};
    for (id in references) {
      value = references[id];
      if (id in this._all_models) {
        old_references[id] = value;
      } else {
        new_references[id] = value;
      }
    }
    Document._initialize_references_json(references_json, old_references, new_references);
    results = [];
    for (l = 0, len1 = events_json.length; l < len1; l++) {
      event_json = events_json[l];
      if (event_json['kind'] === 'ModelChanged') {
        patched_id = event_json['model']['id'];
        if (!(patched_id in this._all_models)) {
          throw new Error("Cannot apply patch to " + patched_id + " which is not in the document");
        }
        patched_obj = this._all_models[patched_id];
        attr = event_json['attr'];
        value = Document._resolve_refs(event_json['new'], old_references, new_references);
        results.push(patched_obj.set((
          obj1 = {},
          obj1["" + attr] = value,
          obj1
        )));
      } else if (event_json['kind'] === 'ColumnsStreamed') {
        column_source_id = event_json['column_source']['id'];
        if (!(column_source_id in this._all_models)) {
          throw new Error("Cannot stream to " + column_source_id + " which is not in the document");
        }
        column_source = this._all_models[column_source_id];
        if (!(column_source instanceof ColumnDataSource.Model)) {
          throw new Error("Cannot stream to non-ColumnDataSource");
        }
        data = event_json['data'];
        rollover = event_json['rollover'];
        results.push(column_source.stream(data, rollover));
      } else if (event_json['kind'] === 'ColumnsPatched') {
        column_source_id = event_json['column_source']['id'];
        if (!(column_source_id in this._all_models)) {
          throw new Error("Cannot patch " + column_source_id + " which is not in the document");
        }
        column_source = this._all_models[column_source_id];
        if (!(column_source instanceof ColumnDataSource.Model)) {
          throw new Error("Cannot patch non-ColumnDataSource");
        }
        patches = event_json['patches'];
        results.push(column_source.patch(patches));
      } else if (event_json['kind'] === 'RootAdded') {
        root_id = event_json['model']['id'];
        root_obj = references[root_id];
        results.push(this.add_root(root_obj));
      } else if (event_json['kind'] === 'RootRemoved') {
        root_id = event_json['model']['id'];
        root_obj = references[root_id];
        results.push(this.remove_root(root_obj));
      } else if (event_json['kind'] === 'TitleChanged') {
        results.push(this.set_title(event_json['title']));
      } else {
        throw new Error("Unknown patch event " + JSON.stringify(event_json));
      }
    }
    return results;
  };

  return Document;

})();

module.exports = {
  Document: Document,
  DocumentChangedEvent: DocumentChangedEvent,
  ModelChangedEvent: ModelChangedEvent,
  TitleChangedEvent: TitleChangedEvent,
  RootAddedEvent: RootAddedEvent,
  RootRemovedEvent: RootRemovedEvent,
  DEFAULT_TITLE: DEFAULT_TITLE
};

},{"./base":"base","./core/has_props":"core/has_props","./core/layout/solver":"core/layout/solver","./core/logging":"core/logging","./core/util/data_structures":"core/util/data_structures","./core/util/refs":"core/util/refs","./models/sources/column_data_source":"models/sources/column_data_source","./version":"version","jquery":"jquery","underscore":"underscore"}],"embed":[function(require,module,exports){
var $, BOKEH_ROOT, Backbone, Document, Promise, RootAddedEvent, RootRemovedEvent, TitleChangedEvent, _, _create_view, _get_session, _handle_notebook_comms, _init_comms, _render_document_to_element, _sessions, add_document_from_session, add_document_standalone, add_document_static, add_model_from_session, add_model_static, base, embed_items, fill_render_item_from_script_tag, inject_css, inject_raw_css, logger, pull_session, ref, ref1, set_log_level;

$ = require("jquery");

_ = require("underscore");

Backbone = require("backbone");

Promise = require("es6-promise").Promise;

base = require("./base");

pull_session = require("./client").pull_session;

ref = require("./core/logging"), logger = ref.logger, set_log_level = ref.set_log_level;

ref1 = require("./document"), Document = ref1.Document, RootAddedEvent = ref1.RootAddedEvent, RootRemovedEvent = ref1.RootRemovedEvent, TitleChangedEvent = ref1.TitleChangedEvent;

BOKEH_ROOT = "bk-root";

_handle_notebook_comms = function(msg) {
  var data;
  logger.debug("handling notebook comms");
  data = JSON.parse(msg.content.data);
  if ('events' in data && 'references' in data) {
    return this.apply_json_patch(data);
  } else if ('doc' in data) {
    return this.replace_with_json(data['doc']);
  } else {
    throw new Error("handling notebook comms message: ", msg);
  }
};

_init_comms = function(target, doc) {
  var comm_manager, e, error1;
  if (typeof Jupyter !== "undefined" && Jupyter !== null) {
    try {
      comm_manager = Jupyter.notebook.kernel.comm_manager;
      return comm_manager.register_target(target, function(comm, msg) {
        logger.info("Registering Jupyter comms for target " + target);
        return comm.on_msg(_.bind(_handle_notebook_comms, doc));
      });
    } catch (error1) {
      e = error1;
      return logger.warn("Jupyter comms failed to register. push_notebook() will not function. (exception reported: " + e + ")");
    }
  } else {
    return console.warn('Juptyer notebooks comms not available. push_notebook() will not function');
  }
};

_create_view = function(model) {
  var view;
  view = new model.default_view({
    model: model
  });
  base.index[model.id] = view;
  return view;
};

_render_document_to_element = function(element, document, use_for_title) {
  var i, len, model, ref2, render_model, unrender_model, views;
  views = {};
  render_model = function(model) {
    var view;
    view = _create_view(model);
    views[model.id] = view;
    return $(element).append(view.$el);
  };
  unrender_model = function(model) {
    var view;
    if (model.id in views) {
      view = views[model.id];
      $(element).remove(view.$el);
      delete views[model.id];
      return delete base.index[model.id];
    }
  };
  ref2 = document.roots();
  for (i = 0, len = ref2.length; i < len; i++) {
    model = ref2[i];
    render_model(model);
  }
  if (use_for_title) {
    window.document.title = document.title();
  }
  document.on_change(function(event) {
    if (event instanceof RootAddedEvent) {
      return render_model(event.model);
    } else if (event instanceof RootRemovedEvent) {
      return unrender_model(event.model);
    } else if (use_for_title && event instanceof TitleChangedEvent) {
      return window.document.title = event.title;
    }
  });
  return views;
};

add_model_static = function(element, model_id, doc) {
  var model, view;
  model = doc.get_model_by_id(model_id);
  if (model == null) {
    throw new Error("Model " + model_id + " was not in document " + doc);
  }
  view = _create_view(model);
  return _.delay(function() {
    return $(element).replaceWith(view.$el);
  });
};

add_document_static = function(element, doc, use_for_title) {
  return _.delay(function() {
    return _render_document_to_element($(element), doc, use_for_title);
  });
};

add_document_standalone = function(document, element, use_for_title) {
  if (use_for_title == null) {
    use_for_title = false;
  }
  return _render_document_to_element($(element), document, use_for_title);
};

_sessions = {};

_get_session = function(websocket_url, session_id) {
  var subsessions;
  if ((websocket_url == null) || websocket_url === null) {
    throw new Error("Missing websocket_url");
  }
  if (!(websocket_url in _sessions)) {
    _sessions[websocket_url] = {};
  }
  subsessions = _sessions[websocket_url];
  if (!(session_id in subsessions)) {
    subsessions[session_id] = pull_session(websocket_url, session_id);
  }
  return subsessions[session_id];
};

add_document_from_session = function(element, websocket_url, session_id, use_for_title) {
  var promise;
  promise = _get_session(websocket_url, session_id);
  return promise.then(function(session) {
    return _render_document_to_element(element, session.document, use_for_title);
  }, function(error) {
    logger.error("Failed to load Bokeh session " + session_id + ": " + error);
    throw error;
  });
};

add_model_from_session = function(element, websocket_url, model_id, session_id) {
  var promise;
  promise = _get_session(websocket_url, session_id);
  return promise.then(function(session) {
    var model, view;
    model = session.document.get_model_by_id(model_id);
    if (model == null) {
      throw new Error("Did not find model " + model_id + " in session");
    }
    view = _create_view(model);
    return $(element).replaceWith(view.$el);
  }, function(error) {
    logger.error("Failed to load Bokeh session " + session_id + ": " + error);
    throw error;
  });
};

inject_css = function(url) {
  var link;
  link = $("<link href='" + url + "' rel='stylesheet' type='text/css'>");
  return $('body').append(link);
};

inject_raw_css = function(css) {
  var style;
  style = $("<style>").html(css);
  return $('body').append(style);
};

fill_render_item_from_script_tag = function(script, item) {
  var info;
  info = script.data();
  if ((info.bokehLogLevel != null) && info.bokehLogLevel.length > 0) {
    set_log_level(info.bokehLogLevel);
  }
  if ((info.bokehDocId != null) && info.bokehDocId.length > 0) {
    item['docid'] = info.bokehDocId;
  }
  if ((info.bokehModelId != null) && info.bokehModelId.length > 0) {
    item['modelid'] = info.bokehModelId;
  }
  if ((info.bokehSessionId != null) && info.bokehSessionId.length > 0) {
    item['sessionid'] = info.bokehSessionId;
  }
  return logger.info("Will inject Bokeh script tag with params " + (JSON.stringify(item)));
};

embed_items = function(docs_json, render_items, websocket_url) {
  var container, docid, docs, elem, element_id, i, item, len, promise, results, use_for_title;
  if (websocket_url == null) {
    websocket_url = null;
  }
  docs = {};
  for (docid in docs_json) {
    docs[docid] = Document.from_json(docs_json[docid]);
  }
  results = [];
  for (i = 0, len = render_items.length; i < len; i++) {
    item = render_items[i];
    if (item.notebook_comms_target != null) {
      _init_comms(item.notebook_comms_target, docs[docid]);
    }
    element_id = item['elementid'];
    elem = $('#' + element_id);
    if (elem.length === 0) {
      throw new Error("Error rendering Bokeh model: could not find tag with id: " + element_id);
    }
    if (elem.length > 1) {
      throw new Error("Error rendering Bokeh model: found too many tags with id: " + element_id);
    }
    if (!document.body.contains(elem[0])) {
      throw new Error("Error rendering Bokeh model: element with id '" + element_id + "' must be under <body>");
    }
    if (elem.prop("tagName") === "SCRIPT") {
      fill_render_item_from_script_tag(elem, item);
      container = $('<div>', {
        "class": BOKEH_ROOT
      });
      elem.replaceWith(container);
      elem = container;
    }
    use_for_title = (item.use_for_title != null) && item.use_for_title;
    promise = null;
    if (item.modelid != null) {
      if (item.docid != null) {
        add_model_static(elem, item.modelid, docs[item.docid]);
      } else if (item.sessionid != null) {
        promise = add_model_from_session(elem, websocket_url, item.modelid, item.sessionid);
      } else {
        throw new Error("Error rendering Bokeh model " + item['modelid'] + " to element " + element_id + ": no document ID or session ID specified");
      }
    } else {
      if (item.docid != null) {
        add_document_static(elem, docs[item.docid], use_for_title);
      } else if (item.sessionid != null) {
        promise = add_document_from_session(elem, websocket_url, item.sessionid, use_for_title);
      } else {
        throw new Error("Error rendering Bokeh document to element " + element_id + ": no document ID or session ID specified");
      }
    }
    if (promise !== null) {
      results.push(promise.then(function(value) {
        return console.log("Bokeh items were rendered successfully");
      }, function(error) {
        return console.log("Error rendering Bokeh items ", error);
      }));
    } else {
      results.push(void 0);
    }
  }
  return results;
};

module.exports = {
  embed_items: embed_items,
  add_document_static: add_document_static,
  add_document_standalone: add_document_standalone,
  inject_css: inject_css,
  inject_raw_css: inject_raw_css,
  BOKEH_ROOT: BOKEH_ROOT
};

},{"./base":"base","./client":"client","./core/logging":"core/logging","./document":"document","backbone":"backbone","es6-promise":"es6-promise","jquery":"jquery","underscore":"underscore"}],"main":[function(require,module,exports){
var Bokeh, _, logging;

_ = require("underscore");

Bokeh = {};

Bokeh.require = require;

Bokeh.version = require("./version");

Bokeh._ = require("underscore");

Bokeh.$ = require("jquery");

Bokeh.Backbone = require("backbone");

Bokeh.Backbone.$ = Bokeh.$;

logging = require("./core/logging");

Bokeh.logger = logging.logger;

Bokeh.set_log_level = logging.set_log_level;

Bokeh.index = require("./base").index;

Bokeh.embed = require("./embed");

Bokeh.Models = require("./base").Models;

_.extend(Bokeh, require("./api"));

Bokeh.Bokeh = Bokeh;

module.exports = Bokeh;

},{"./api":"api","./base":"base","./core/logging":"core/logging","./embed":"embed","./version":"version","backbone":"backbone","jquery":"jquery","underscore":"underscore"}],"model":[function(require,module,exports){
var HasProps, Model, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

HasProps = require("./core/has_props");

p = require("./core/properties");

Model = (function(superClass) {
  extend(Model, superClass);

  function Model() {
    return Model.__super__.constructor.apply(this, arguments);
  }

  Model.prototype.type = "Model";

  Model.prototype._coords = [];

  Model.coords = function(coords) {
    var _coords, i, len, ref1, result, x, y;
    _coords = this.prototype._coords.concat(coords);
    this.prototype._coords = _coords;
    result = {};
    for (i = 0, len = coords.length; i < len; i++) {
      ref1 = coords[i], x = ref1[0], y = ref1[1];
      result[x] = [p.NumberSpec];
      result[y] = [p.NumberSpec];
    }
    return this.define(result);
  };

  Model.define({
    tags: [p.Array, []],
    name: [p.String]
  });

  Model.prototype.select = function(selector) {
    if (selector.prototype instanceof Model) {
      return this.references().filter(function(ref) {
        return ref instanceof selector;
      });
    } else if (_.isString(selector)) {
      return this.references().filter(function(ref) {
        return ref.name === selector;
      });
    } else {
      throw new Error("invalid selector");
    }
  };

  Model.prototype.select_one = function(selector) {
    var result;
    result = this.select(selector);
    switch (result.length) {
      case 0:
        return null;
      case 1:
        return result[0];
      default:
        throw new Error("found more than one object matching given selector");
    }
  };

  return Model;

})(HasProps);

module.exports = Model;

},{"./core/has_props":"core/has_props","./core/properties":"core/properties","underscore":"underscore"}],"models/annotations/annotation":[function(require,module,exports){
var Annotation, AnnotationView, Renderer, SidePanel, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SidePanel = require("../../core/layout/side_panel");

p = require("../../core/properties");

Renderer = require("../renderers/renderer");

AnnotationView = (function(superClass) {
  extend(AnnotationView, superClass);

  function AnnotationView() {
    return AnnotationView.__super__.constructor.apply(this, arguments);
  }

  AnnotationView.prototype._get_panel_offset = function() {
    var x, y;
    x = this.model.panel._left._value;
    y = this.model.panel._bottom._value;
    return {
      x: x,
      y: -y
    };
  };

  AnnotationView.prototype._get_size = function() {
    return -1;
  };

  return AnnotationView;

})(Renderer.View);

Annotation = (function(superClass) {
  extend(Annotation, superClass);

  function Annotation() {
    return Annotation.__super__.constructor.apply(this, arguments);
  }

  Annotation.prototype.type = 'Annotation';

  Annotation.prototype.default_view = AnnotationView;

  Annotation.define({
    plot: [p.Instance]
  });

  Annotation.override({
    level: 'annotation'
  });

  Annotation.prototype.add_panel = function(side) {
    this.panel = new SidePanel.Model({
      side: side
    });
    this.panel.attach_document(this.document);
    return this.level = 'overlay';
  };

  return Annotation;

})(Renderer.Model);

module.exports = {
  Model: Annotation,
  View: AnnotationView
};

},{"../../core/layout/side_panel":"core/layout/side_panel","../../core/properties":"core/properties","../renderers/renderer":"models/renderers/renderer","underscore":"underscore"}],"models/annotations/arrow":[function(require,module,exports){
var Annotation, Arrow, ArrowView, ColumnDataSource, OpenHead, _, atan2, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Annotation = require("./annotation");

OpenHead = require("./arrow_head").OpenHead;

ColumnDataSource = require("../sources/column_data_source");

p = require("../../core/properties");

atan2 = require("../../core/util/math").atan2;

ArrowView = (function(superClass) {
  extend(ArrowView, superClass);

  function ArrowView() {
    return ArrowView.__super__.constructor.apply(this, arguments);
  }

  ArrowView.prototype.initialize = function(options) {
    ArrowView.__super__.initialize.call(this, options);
    if (this.mget('source') == null) {
      this.mset('source', new ColumnDataSource.Model());
    }
    this.canvas = this.plot_model.get('canvas');
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    return this.set_data();
  };

  ArrowView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change', this.plot_view.request_render);
    return this.listenTo(this.mget('source'), 'change', function() {
      set_data();
      return this.plot_view.request_render();
    });
  };

  ArrowView.prototype.set_data = function() {
    ArrowView.__super__.set_data.call(this, this.mget('source'));
    return this.set_visuals(this.mget('source'));
  };

  ArrowView.prototype._map_data = function() {
    var end, start, x_name, y_name;
    if (this.mget('start_units') === 'data') {
      start = this.plot_view.map_to_screen(this._x_start, this._y_start, x_name = this.mget('x_range_name'), y_name = this.mget('y_range_name'));
    } else {
      start = [this.canvas.v_vx_to_sx(this._x_start.slice(0)), this.canvas.v_vy_to_sy(this._y_start.slice(0))];
    }
    if (this.mget('end_units') === 'data') {
      end = this.plot_view.map_to_screen(this._x_end, this._y_end, x_name = this.mget('x_range_name'), y_name = this.mget('y_range_name'));
    } else {
      end = [this.canvas.v_vx_to_sx(this._x_end.slice(0)), this.canvas.v_vy_to_sy(this._y_end.slice(0))];
    }
    return [start, end];
  };

  ArrowView.prototype.render = function() {
    var ref;
    ref = this._map_data(), this.start = ref[0], this.end = ref[1];
    this._draw_arrow_body();
    if (this.mget('end') != null) {
      this._draw_arrow_head(this.mget('end'), this.start, this.end);
    }
    if (this.mget('start') != null) {
      return this._draw_arrow_head(this.mget('start'), this.end, this.start);
    }
  };

  ArrowView.prototype._draw_arrow_body = function() {
    var ctx, i, j, ref;
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    for (i = j = 0, ref = this._x_start.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      this.visuals.line.set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(this.start[0][i], this.start[1][i]);
      ctx.lineTo(this.end[0][i], this.end[1][i]);
      if (this.visuals.line.doit) {
        ctx.stroke();
      }
    }
    return ctx.restore();
  };

  ArrowView.prototype._draw_arrow_head = function(head, start, end) {
    var angle, ctx, i, j, ref, results;
    ctx = this.plot_view.canvas_view.ctx;
    results = [];
    for (i = j = 0, ref = this._x_start.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      angle = Math.PI / 2 + atan2([start[0][i], start[1][i]], [end[0][i], end[1][i]]);
      ctx.save();
      ctx.translate(end[0][i], end[1][i]);
      ctx.rotate(angle);
      head.render(ctx, i);
      results.push(ctx.restore());
    }
    return results;
  };

  return ArrowView;

})(Annotation.View);

Arrow = (function(superClass) {
  extend(Arrow, superClass);

  function Arrow() {
    return Arrow.__super__.constructor.apply(this, arguments);
  }

  Arrow.prototype.default_view = ArrowView;

  Arrow.prototype.type = 'Arrow';

  Arrow.mixins(['line']);

  Arrow.define({
    x_start: [p.NumberSpec],
    y_start: [p.NumberSpec],
    start_units: [p.String, 'data'],
    start: [p.Instance, null],
    x_end: [p.NumberSpec],
    y_end: [p.NumberSpec],
    end_units: [p.String, 'data'],
    end: [p.Instance, new OpenHead.Model({})],
    source: [p.Instance],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default']
  });

  return Arrow;

})(Annotation.Model);

module.exports = {
  Model: Arrow,
  View: ArrowView
};

},{"../../core/properties":"core/properties","../../core/util/math":"core/util/math","../sources/column_data_source":"models/sources/column_data_source","./annotation":"models/annotations/annotation","./arrow_head":"models/annotations/arrow_head","underscore":"underscore"}],"models/annotations/arrow_head":[function(require,module,exports){
var Annotation, ArrowHead, NormalHead, OpenHead, Renderer, VeeHead, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Annotation = require("./annotation");

Renderer = require("../renderers/renderer");

p = require("../../core/properties");

ArrowHead = (function(superClass) {
  extend(ArrowHead, superClass);

  function ArrowHead() {
    return ArrowHead.__super__.constructor.apply(this, arguments);
  }

  ArrowHead.prototype.type = 'ArrowHead';

  ArrowHead.prototype.initialize = function(options) {
    var j, len, name, prefix, ref, ref1, results, spec;
    ArrowHead.__super__.initialize.call(this, options);
    this.visuals = {};
    ref = this.mixins;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      spec = ref[j];
      ref1 = spec.split(":"), name = ref1[0], prefix = ref1[1];
      if (prefix == null) {
        prefix = "";
      }
      results.push(this.visuals[prefix + name] = new Renderer.Visuals[name]({
        obj: this,
        prefix: prefix
      }));
    }
    return results;
  };

  ArrowHead.prototype.render = function(ctx, i) {
    return null;
  };

  return ArrowHead;

})(Annotation.Model);

OpenHead = (function(superClass) {
  extend(OpenHead, superClass);

  function OpenHead() {
    return OpenHead.__super__.constructor.apply(this, arguments);
  }

  OpenHead.prototype.type = 'OpenHead';

  OpenHead.prototype.render = function(ctx, i) {
    if (this.visuals["line"].doit) {
      this.visuals["line"].set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.get("size"), this.get("size"));
      return ctx.stroke();
    }
  };

  OpenHead.mixins(['line']);

  OpenHead.define({
    size: [p.Number, 25]
  });

  return OpenHead;

})(ArrowHead);

NormalHead = (function(superClass) {
  extend(NormalHead, superClass);

  function NormalHead() {
    return NormalHead.__super__.constructor.apply(this, arguments);
  }

  NormalHead.prototype.type = 'NormalHead';

  NormalHead.prototype.render = function(ctx, i) {
    if (this.visuals["fill"].doit) {
      this.visuals["fill"].set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.get("size"), this.get("size"));
      ctx.closePath();
      ctx.fill();
    }
    if (this.visuals["line"].doit) {
      this.visuals["line"].set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.get("size"), this.get("size"));
      ctx.closePath();
      return ctx.stroke();
    }
  };

  NormalHead.mixins(['line', 'fill']);

  NormalHead.define({
    size: [p.Number, 25]
  });

  NormalHead.override({
    fill_color: 'black'
  });

  return NormalHead;

})(ArrowHead);

VeeHead = (function(superClass) {
  extend(VeeHead, superClass);

  function VeeHead() {
    return VeeHead.__super__.constructor.apply(this, arguments);
  }

  VeeHead.prototype.type = 'VeeHead';

  VeeHead.prototype.render = function(ctx, i) {
    if (this.visuals["fill"].doit) {
      this.visuals["fill"].set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0.5 * this.get("size"));
      ctx.closePath();
      ctx.fill();
    }
    if (this.visuals["line"].doit) {
      this.visuals["line"].set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.get("size"), this.get("size"));
      ctx.lineTo(0, 0.5 * this.get("size"));
      ctx.closePath();
      return ctx.stroke();
    }
  };

  VeeHead.mixins(['line', 'fill']);

  VeeHead.define({
    size: [p.Number, 25]
  });

  VeeHead.override({
    fill_color: 'black'
  });

  return VeeHead;

})(ArrowHead);

module.exports = {
  OpenHead: {
    Model: OpenHead
  },
  NormalHead: {
    Model: NormalHead
  },
  VeeHead: {
    Model: VeeHead
  }
};

},{"../../core/properties":"core/properties","../renderers/renderer":"models/renderers/renderer","./annotation":"models/annotations/annotation"}],"models/annotations/box_annotation":[function(require,module,exports){
var Annotation, BoxAnnotation, BoxAnnotationView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Annotation = require("./annotation");

p = require("../../core/properties");

BoxAnnotationView = (function(superClass) {
  extend(BoxAnnotationView, superClass);

  function BoxAnnotationView() {
    return BoxAnnotationView.__super__.constructor.apply(this, arguments);
  }

  BoxAnnotationView.prototype.initialize = function(options) {
    BoxAnnotationView.__super__.initialize.call(this, options);
    this.$el.appendTo(this.plot_view.$el.find('div.bk-canvas-overlays'));
    this.$el.addClass('bk-shading');
    return this.$el.hide();
  };

  BoxAnnotationView.prototype.bind_bokeh_events = function() {
    if (this.mget('render_mode') === 'css') {
      this.listenTo(this.model, 'change', this.render);
      return this.listenTo(this.model, 'data_update', this.render);
    } else {
      this.listenTo(this.model, 'change', this.plot_view.request_render);
      return this.listenTo(this.model, 'data_update', this.plot_view.request_render);
    }
  };

  BoxAnnotationView.prototype.render = function() {
    var sbottom, sleft, sright, stop;
    if ((this.mget('left') == null) && (this.mget('right') == null) && (this.mget('top') == null) && (this.mget('bottom') == null)) {
      this.$el.hide();
      return null;
    }
    this.frame = this.plot_model.get('frame');
    this.canvas = this.plot_model.get('canvas');
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    sleft = this.canvas.vx_to_sx(this._calc_dim('left', this.xmapper, this.frame.get('h_range').get('start')));
    sright = this.canvas.vx_to_sx(this._calc_dim('right', this.xmapper, this.frame.get('h_range').get('end')));
    sbottom = this.canvas.vy_to_sy(this._calc_dim('bottom', this.ymapper, this.frame.get('v_range').get('start')));
    stop = this.canvas.vy_to_sy(this._calc_dim('top', this.ymapper, this.frame.get('v_range').get('end')));
    if (this.mget('render_mode') === 'css') {
      return this._css_box(sleft, sright, sbottom, stop);
    } else {
      return this._canvas_box(sleft, sright, sbottom, stop);
    }
  };

  BoxAnnotationView.prototype._css_box = function(sleft, sright, sbottom, stop) {
    var ba, bc, lc, ld, lw, sh, style, sw;
    sw = Math.abs(sright - sleft);
    sh = Math.abs(sbottom - stop);
    lw = this.mget("line_width").value;
    lc = this.mget("line_color").value;
    bc = this.mget("fill_color").value;
    ba = this.mget("fill_alpha").value;
    style = "left:" + sleft + "px; width:" + sw + "px; top:" + stop + "px; height:" + sh + "px; border-width:" + lw + "px; border-color:" + lc + "; background-color:" + bc + "; opacity:" + ba + ";";
    ld = this.mget("line_dash");
    if (_.isArray(ld)) {
      if (ld.length < 2) {
        ld = "solid";
      } else {
        ld = "dashed";
      }
    }
    if (_.isString(ld)) {
      style += " border-style:" + ld + ";";
    }
    this.$el.attr('style', style);
    return this.$el.show();
  };

  BoxAnnotationView.prototype._canvas_box = function(sleft, sright, sbottom, stop) {
    var ctx;
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    ctx.beginPath();
    ctx.rect(sleft, stop, sright - sleft, sbottom - stop);
    this.visuals.fill.set_value(ctx);
    ctx.fill();
    this.visuals.line.set_value(ctx);
    ctx.stroke();
    return ctx.restore();
  };

  BoxAnnotationView.prototype._calc_dim = function(dim, mapper, frame_extrema) {
    var vdim;
    if (this.mget(dim) != null) {
      if (this.mget(dim + '_units') === 'data') {
        vdim = mapper.map_to_target(this.mget(dim));
      } else {
        vdim = this.mget(dim);
      }
    } else {
      vdim = frame_extrema;
    }
    return vdim;
  };

  return BoxAnnotationView;

})(Annotation.View);

BoxAnnotation = (function(superClass) {
  extend(BoxAnnotation, superClass);

  function BoxAnnotation() {
    return BoxAnnotation.__super__.constructor.apply(this, arguments);
  }

  BoxAnnotation.prototype.default_view = BoxAnnotationView;

  BoxAnnotation.prototype.type = 'BoxAnnotation';

  BoxAnnotation.mixins(['line', 'fill']);

  BoxAnnotation.define({
    render_mode: [p.RenderMode, 'canvas'],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default'],
    top: [p.Number, null],
    top_units: [p.SpatialUnits, 'data'],
    bottom: [p.Number, null],
    bottom_units: [p.SpatialUnits, 'data'],
    left: [p.Number, null],
    left_units: [p.SpatialUnits, 'data'],
    right: [p.Number, null],
    right_units: [p.SpatialUnits, 'data']
  });

  BoxAnnotation.override({
    fill_color: '#fff9ba',
    fill_alpha: 0.4,
    line_color: '#cccccc',
    line_alpha: 0.3
  });

  BoxAnnotation.prototype.update = function(arg) {
    var bottom, left, right, top;
    left = arg.left, right = arg.right, top = arg.top, bottom = arg.bottom;
    this.set({
      left: left,
      right: right,
      top: top,
      bottom: bottom
    }, {
      silent: true
    });
    return this.trigger('data_update');
  };

  return BoxAnnotation;

})(Annotation.Model);

module.exports = {
  Model: BoxAnnotation,
  View: BoxAnnotationView
};

},{"../../core/properties":"core/properties","./annotation":"models/annotations/annotation","underscore":"underscore"}],"models/annotations/label":[function(require,module,exports){
var Label, LabelView, TextAnnotation, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

TextAnnotation = require("./text_annotation");

p = require("../../core/properties");

LabelView = (function(superClass) {
  extend(LabelView, superClass);

  function LabelView() {
    return LabelView.__super__.constructor.apply(this, arguments);
  }

  LabelView.prototype.initialize = function(options) {
    var name, prop, ref, results;
    LabelView.__super__.initialize.call(this, options);
    this.canvas = this.plot_model.get('canvas');
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    ref = this.visuals;
    results = [];
    for (name in ref) {
      prop = ref[name];
      results.push(prop.warm_cache(null));
    }
    return results;
  };

  LabelView.prototype._get_size = function() {
    var ctx, height, side, width;
    ctx = this.plot_view.canvas_view.ctx;
    this.visuals.text.set_value(ctx);
    side = this.model.panel.side;
    if (side === "above" || side === "below") {
      height = ctx.measureText(this.mget('text')).ascent;
      return height;
    }
    if (side === 'left' || side === 'right') {
      width = ctx.measureText(this.mget('text')).width;
      return width;
    }
  };

  LabelView.prototype.render = function() {
    var angle, ctx, panel_offset, sx, sy, vx, vy;
    ctx = this.plot_view.canvas_view.ctx;
    switch (this.mget('angle_units')) {
      case "rad":
        angle = -1 * this.mget('angle');
        break;
      case "deg":
        angle = -1 * this.mget('angle') * Math.PI / 180.0;
    }
    if (this.mget('x_units') === "data") {
      vx = this.xmapper.map_to_target(this.mget('x'));
    } else {
      vx = this.mget('x');
    }
    sx = this.canvas.vx_to_sx(vx);
    if (this.mget('y_units') === "data") {
      vy = this.ymapper.map_to_target(this.mget('y'));
    } else {
      vy = this.mget('y');
    }
    sy = this.canvas.vy_to_sy(vy);
    if (this.model.panel != null) {
      panel_offset = this._get_panel_offset();
      sx += panel_offset.x;
      sy += panel_offset.y;
    }
    if (this.mget('render_mode') === 'canvas') {
      return this._canvas_text(ctx, this.mget('text'), sx + this.mget('x_offset'), sy - this.mget('y_offset'), angle);
    } else {
      return this._css_text(ctx, this.mget('text'), sx + this.mget('x_offset'), sy - this.mget('y_offset'), angle);
    }
  };

  return LabelView;

})(TextAnnotation.View);

Label = (function(superClass) {
  extend(Label, superClass);

  function Label() {
    return Label.__super__.constructor.apply(this, arguments);
  }

  Label.prototype.default_view = LabelView;

  Label.prototype.type = 'Label';

  Label.mixins(['text', 'line:border_', 'fill:background_']);

  Label.define({
    x: [p.Number],
    x_units: [p.SpatialUnits, 'data'],
    y: [p.Number],
    y_units: [p.SpatialUnits, 'data'],
    text: [p.String],
    angle: [p.Angle, 0],
    angle_units: [p.AngleUnits, 'rad'],
    x_offset: [p.Number, 0],
    y_offset: [p.Number, 0],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default'],
    render_mode: [p.RenderMode, 'canvas']
  });

  Label.override({
    background_fill_color: null,
    border_line_color: null
  });

  return Label;

})(TextAnnotation.Model);

module.exports = {
  Model: Label,
  View: LabelView
};

},{"../../core/properties":"core/properties","./text_annotation":"models/annotations/text_annotation"}],"models/annotations/label_set":[function(require,module,exports){
var $, ColumnDataSource, LabelSet, LabelSetView, TextAnnotation, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

$ = require("jquery");

TextAnnotation = require("./text_annotation");

ColumnDataSource = require("../sources/column_data_source");

p = require("../../core/properties");

LabelSetView = (function(superClass) {
  extend(LabelSetView, superClass);

  function LabelSetView() {
    return LabelSetView.__super__.constructor.apply(this, arguments);
  }

  LabelSetView.prototype.initialize = function(options) {
    var i, j, ref, results;
    LabelSetView.__super__.initialize.call(this, options);
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    this.set_data(this.mget('source'));
    this.set_visuals(this.mget('source'));
    if (this.mget('render_mode') === 'css') {
      results = [];
      for (i = j = 0, ref = this._text.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        this.title_div = $("<div>").addClass('bk-annotation-child').hide();
        results.push(this.title_div.appendTo(this.$el));
      }
      return results;
    }
  };

  LabelSetView.prototype.bind_bokeh_events = function() {
    if (this.mget('render_mode') === 'css') {
      this.listenTo(this.model, 'change', function() {
        this.set_data(this.mget('source'));
        return this.render();
      });
      return this.listenTo(this.mget('source'), 'change', function() {
        this.set_data(this.mget('source'));
        return this.render();
      });
    } else {
      this.listenTo(this.model, 'change', function() {
        this.set_data(this.mget('source'));
        return this.plot_view.request_render();
      });
      return this.listenTo(this.mget('source'), 'change', function() {
        this.set_data(this.mget('source'));
        return this.plot_view.request_render();
      });
    }
  };

  LabelSetView.prototype._map_data = function() {
    var sx, sy, vx, vy;
    if (this.mget('x_units') === "data") {
      vx = this.xmapper.v_map_to_target(this._x);
    } else {
      vx = this._x.slice(0);
    }
    sx = this.canvas.v_vx_to_sx(vx);
    if (this.mget('y_units') === "data") {
      vy = this.ymapper.v_map_to_target(this._y);
    } else {
      vy = this._y.slice(0);
    }
    sy = this.canvas.v_vy_to_sy(vy);
    return [sx, sy];
  };

  LabelSetView.prototype.render = function() {
    var ctx, i, j, k, ref, ref1, ref2, results, results1, sx, sy;
    ctx = this.plot_view.canvas_view.ctx;
    ref = this._map_data(), sx = ref[0], sy = ref[1];
    if (this.mget('render_mode') === 'canvas') {
      results = [];
      for (i = j = 0, ref1 = this._text.length; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
        results.push(this._v_canvas_text(ctx, i, this._text[i], sx[i] + this._x_offset[i], sy[i] - this._y_offset[i], this._angle[i]));
      }
      return results;
    } else {
      results1 = [];
      for (i = k = 0, ref2 = this._text.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) {
        results1.push(this._v_css_text(ctx, i, this._text[i], sx[i] + this._x_offset[i], sy[i] - this._y_offset[i], this._angle[i]));
      }
      return results1;
    }
  };

  LabelSetView.prototype._get_size = function() {
    var ctx, height, side, width;
    ctx = this.plot_view.canvas_view.ctx;
    this.visuals.text.set_value(ctx);
    side = this.model.panel.side;
    if (side === "above" || side === "below") {
      height = ctx.measureText(this._text[0]).ascent;
      return height;
    }
    if (side === 'left' || side === 'right') {
      width = ctx.measureText(this._text[0]).width;
      return width;
    }
  };

  LabelSetView.prototype._v_canvas_text = function(ctx, i, text, sx, sy, angle) {
    var bbox_dims;
    this.visuals.text.set_vectorize(ctx, i);
    bbox_dims = this._calculate_bounding_box_dimensions(ctx, text);
    ctx.save();
    ctx.beginPath();
    ctx.translate(sx, sy);
    ctx.rotate(angle);
    ctx.rect(bbox_dims[0], bbox_dims[1], bbox_dims[2], bbox_dims[3]);
    if (this.visuals.background_fill.doit) {
      this.visuals.background_fill.set_vectorize(ctx, i);
      ctx.fill();
    }
    if (this.visuals.border_line.doit) {
      this.visuals.border_line.set_vectorize(ctx, i);
      ctx.stroke();
    }
    if (this.visuals.text.doit) {
      this.visuals.text.set_vectorize(ctx, i);
      ctx.fillText(text, 0, 0);
    }
    return ctx.restore();
  };

  LabelSetView.prototype._v_css_text = function(ctx, i, text, sx, sy, angle) {
    var bbox_dims, div_style, ld, line_dash;
    this.visuals.text.set_vectorize(ctx, i);
    bbox_dims = this._calculate_bounding_box_dimensions(ctx, text);
    ld = this.visuals.border_line.line_dash.value();
    if (_.isArray(ld)) {
      if (ld.length < 2) {
        line_dash = "solid";
      } else {
        line_dash = "dashed";
      }
    }
    if (_.isString(ld)) {
      line_dash = ld;
    }
    this.visuals.border_line.set_vectorize(ctx, i);
    this.visuals.background_fill.set_vectorize(ctx, i);
    div_style = {
      'position': 'absolute',
      'left': (sx + bbox_dims[0]) + "px",
      'top': (sy + bbox_dims[1]) + "px",
      'color': "" + (this.visuals.text.text_color.value()),
      'opacity': "" + (this.visuals.text.text_alpha.value()),
      'font': "" + (this.visuals.text.font_value()),
      'line-height': "normal"
    };
    if (angle) {
      _.extend(div_style, {
        'transform': "rotate(" + angle + "rad)"
      });
    }
    if (this.visuals.background_fill.doit) {
      _.extend(div_style, {
        'background-color': "" + (this.visuals.background_fill.color_value())
      });
    }
    if (this.visuals.border_line.doit) {
      _.extend(div_style, {
        'border-style': "" + line_dash,
        'border-width': "" + (this.visuals.border_line.line_width.value()),
        'border-color': "" + (this.visuals.border_line.color_value())
      });
    }
    return this.$el.children().eq(i).html(text).css(div_style).show();
  };

  return LabelSetView;

})(TextAnnotation.View);

LabelSet = (function(superClass) {
  extend(LabelSet, superClass);

  function LabelSet() {
    return LabelSet.__super__.constructor.apply(this, arguments);
  }

  LabelSet.prototype.default_view = LabelSetView;

  LabelSet.prototype.type = 'Label';

  LabelSet.mixins(['text', 'line:border_', 'fill:background_']);

  LabelSet.coords([['x', 'y']]);

  LabelSet.define({
    x_units: [p.SpatialUnits, 'data'],
    y_units: [p.SpatialUnits, 'data'],
    text: [
      p.StringSpec, {
        field: "text"
      }
    ],
    angle: [p.AngleSpec, 0],
    x_offset: [
      p.NumberSpec, {
        value: 0
      }
    ],
    y_offset: [
      p.NumberSpec, {
        value: 0
      }
    ],
    source: [
      p.Instance, function() {
        return new ColumnDataSource.Model();
      }
    ],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default'],
    render_mode: [p.RenderMode, 'canvas']
  });

  LabelSet.override({
    background_fill_color: null,
    border_line_color: null
  });

  return LabelSet;

})(TextAnnotation.Model);

module.exports = {
  Model: LabelSet,
  View: LabelSetView
};

},{"../../core/properties":"core/properties","../sources/column_data_source":"models/sources/column_data_source","./text_annotation":"models/annotations/text_annotation","jquery":"jquery","underscore":"underscore"}],"models/annotations/legend":[function(require,module,exports){
var Annotation, Legend, LegendView, _, get_text_height, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Annotation = require("./annotation");

p = require("../../core/properties");

get_text_height = require("../../core/util/text").get_text_height;

LegendView = (function(superClass) {
  extend(LegendView, superClass);

  function LegendView() {
    return LegendView.__super__.constructor.apply(this, arguments);
  }

  LegendView.prototype.initialize = function(options) {
    return LegendView.__super__.initialize.call(this, options);
  };

  LegendView.prototype.compute_legend_bbox = function() {
    var ctx, glyph_height, glyph_width, glyphs, h_range, i, label_height, label_standoff, label_width, legend_height, legend_margin, legend_name, legend_names, legend_padding, legend_spacing, legend_width, len, location, max_label_width, name, ref, v_range, width, x, y;
    legend_names = (function() {
      var i, len, ref, ref1, results;
      ref = this.mget("legends");
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        ref1 = ref[i], legend_name = ref1[0], glyphs = ref1[1];
        results.push(legend_name);
      }
      return results;
    }).call(this);
    glyph_height = this.mget('glyph_height');
    glyph_width = this.mget('glyph_width');
    label_height = this.mget('label_height');
    label_width = this.mget('label_width');
    this.max_label_height = _.max([get_text_height(this.visuals.label_text.font_value()).height, label_height, glyph_height]);
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    this.visuals.label_text.set_value(ctx);
    this.text_widths = {};
    for (i = 0, len = legend_names.length; i < len; i++) {
      name = legend_names[i];
      this.text_widths[name] = _.max([ctx.measureText(name).width, label_width]);
    }
    ctx.restore();
    max_label_width = _.max(_.values(this.text_widths));
    legend_margin = this.mget('legend_margin');
    legend_padding = this.mget('legend_padding');
    legend_spacing = this.mget('legend_spacing');
    label_standoff = this.mget('label_standoff');
    if (this.mget("orientation") === "vertical") {
      legend_height = legend_names.length * this.max_label_height + (legend_names.length - 1) * legend_spacing + 2 * legend_padding;
      legend_width = max_label_width + glyph_width + label_standoff + 2 * legend_padding;
    } else {
      legend_width = 2 * legend_padding + (legend_names.length - 1) * legend_spacing;
      ref = this.text_widths;
      for (name in ref) {
        width = ref[name];
        legend_width += _.max([width, label_width]) + glyph_width + label_standoff;
      }
      legend_height = this.max_label_height + 2 * legend_padding;
    }
    location = this.mget('location');
    h_range = this.plot_view.frame.get('h_range');
    v_range = this.plot_view.frame.get('v_range');
    if (_.isString(location)) {
      switch (location) {
        case 'top_left':
          x = h_range.get('start') + legend_margin;
          y = v_range.get('end') - legend_margin;
          break;
        case 'top_center':
          x = (h_range.get('end') + h_range.get('start')) / 2 - legend_width / 2;
          y = v_range.get('end') - legend_margin;
          break;
        case 'top_right':
          x = h_range.get('end') - legend_margin - legend_width;
          y = v_range.get('end') - legend_margin;
          break;
        case 'right_center':
          x = h_range.get('end') - legend_margin - legend_width;
          y = (v_range.get('end') + v_range.get('start')) / 2 + legend_height / 2;
          break;
        case 'bottom_right':
          x = h_range.get('end') - legend_margin - legend_width;
          y = v_range.get('start') + legend_margin + legend_height;
          break;
        case 'bottom_center':
          x = (h_range.get('end') + h_range.get('start')) / 2 - legend_width / 2;
          y = v_range.get('start') + legend_margin + legend_height;
          break;
        case 'bottom_left':
          x = h_range.get('start') + legend_margin;
          y = v_range.get('start') + legend_margin + legend_height;
          break;
        case 'left_center':
          x = h_range.get('start') + legend_margin;
          y = (v_range.get('end') + v_range.get('start')) / 2 + legend_height / 2;
          break;
        case 'center':
          x = (h_range.get('end') + h_range.get('start')) / 2 - legend_width / 2;
          y = (v_range.get('end') + v_range.get('start')) / 2 + legend_height / 2;
      }
    } else if (_.isArray(location) && location.length === 2) {
      x = location[0], y = location[1];
    }
    x = this.plot_view.canvas.vx_to_sx(x);
    y = this.plot_view.canvas.vy_to_sy(y);
    return {
      x: x,
      y: y,
      width: legend_width,
      height: legend_height
    };
  };

  LegendView.prototype.render = function() {
    var N, bbox, ctx, glyph_height, glyph_width, glyphs, i, idx, j, label_standoff, legend_name, legend_spacing, len, len1, orientation, panel_offset, ref, ref1, renderer, view, x1, x2, xoffset, y1, y2, yoffset;
    if (this.model.legends.length === 0) {
      return;
    }
    bbox = this.compute_legend_bbox();
    glyph_height = this.mget('glyph_height');
    glyph_width = this.mget('glyph_width');
    orientation = this.mget('orientation');
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    if (this.model.panel != null) {
      panel_offset = this._get_panel_offset();
      ctx.translate(panel_offset.x, panel_offset.y);
    }
    ctx.beginPath();
    ctx.rect(bbox.x, bbox.y, bbox.width, bbox.height);
    this.visuals.background_fill.set_value(ctx);
    ctx.fill();
    if (this.visuals.border_line.doit) {
      this.visuals.border_line.set_value(ctx);
      ctx.stroke();
    }
    N = this.mget("legends").length;
    legend_spacing = this.mget('legend_spacing');
    label_standoff = this.mget('label_standoff');
    xoffset = yoffset = this.mget('legend_padding');
    ref = this.mget("legends");
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      ref1 = ref[idx], legend_name = ref1[0], glyphs = ref1[1];
      x1 = bbox.x + xoffset;
      y1 = bbox.y + yoffset;
      x2 = x1 + glyph_width;
      y2 = y1 + glyph_height;
      if (orientation === "vertical") {
        yoffset += this.max_label_height + legend_spacing;
      } else {
        xoffset += this.text_widths[legend_name] + glyph_width + label_standoff + legend_spacing;
      }
      this.visuals.label_text.set_value(ctx);
      ctx.fillText(legend_name, x2 + label_standoff, y1 + this.max_label_height / 2.0);
      for (j = 0, len1 = glyphs.length; j < len1; j++) {
        renderer = glyphs[j];
        view = this.plot_view.renderer_views[renderer.id];
        view.draw_legend(ctx, x1, x2, y1, y2);
      }
    }
    return ctx.restore();
  };

  LegendView.prototype._get_size = function() {
    var bbox, side;
    bbox = this.compute_legend_bbox();
    side = this.model.panel.side;
    if (side === 'above' || side === 'below') {
      return bbox.height;
    }
    if (side === 'left' || side === 'right') {
      return bbox.width;
    }
  };

  LegendView.prototype._get_panel_offset = function() {
    var x, y;
    x = this.model.panel._left._value;
    y = this.model.panel._top._value;
    return {
      x: x,
      y: -y
    };
  };

  return LegendView;

})(Annotation.View);

Legend = (function(superClass) {
  extend(Legend, superClass);

  function Legend() {
    return Legend.__super__.constructor.apply(this, arguments);
  }

  Legend.prototype.default_view = LegendView;

  Legend.prototype.type = 'Legend';

  Legend.mixins(['text:label_', 'line:border_', 'fill:background_']);

  Legend.define({
    legends: [p.Array, []],
    orientation: [p.Orientation, 'vertical'],
    location: [p.Any, 'top_right'],
    label_standoff: [p.Number, 5],
    glyph_height: [p.Number, 20],
    glyph_width: [p.Number, 20],
    label_height: [p.Number, 20],
    label_width: [p.Number, 20],
    legend_margin: [p.Number, 10],
    legend_padding: [p.Number, 10],
    legend_spacing: [p.Number, 3]
  });

  Legend.override({
    border_line_color: "#e5e5e5",
    border_line_alpha: 0.5,
    border_line_width: 1,
    background_fill_color: "#ffffff",
    background_fill_alpha: 0.95,
    label_text_font_size: "10pt",
    label_text_baseline: "middle"
  });

  return Legend;

})(Annotation.Model);

module.exports = {
  Model: Legend,
  View: LegendView
};

},{"../../core/properties":"core/properties","../../core/util/text":"core/util/text","./annotation":"models/annotations/annotation","underscore":"underscore"}],"models/annotations/poly_annotation":[function(require,module,exports){
var Annotation, PolyAnnotation, PolyAnnotationView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Annotation = require("./annotation");

p = require("../../core/properties");

PolyAnnotationView = (function(superClass) {
  extend(PolyAnnotationView, superClass);

  function PolyAnnotationView() {
    return PolyAnnotationView.__super__.constructor.apply(this, arguments);
  }

  PolyAnnotationView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change', this.plot_view.request_render);
    return this.listenTo(this.model, 'data_update', this.plot_view.request_render);
  };

  PolyAnnotationView.prototype.render = function(ctx) {
    var canvas, i, j, ref, sx, sy, vx, vy, xs, ys;
    xs = this.mget('xs');
    ys = this.mget('ys');
    if (xs.length !== ys.length) {
      return null;
    }
    if (xs.length < 3 || ys.length < 3) {
      return null;
    }
    canvas = this.plot_view.canvas;
    ctx = this.plot_view.canvas_view.ctx;
    for (i = j = 0, ref = xs.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (this.mget('xs_units') === 'screen') {
        vx = xs[i];
      }
      if (this.mget('ys_units') === 'screen') {
        vy = ys[i];
      }
      sx = canvas.vx_to_sx(vx);
      sy = canvas.vy_to_sy(vy);
      if (i === 0) {
        ctx.beginPath();
        ctx.moveTo(sx, sy);
      } else {
        ctx.lineTo(sx, sy);
      }
    }
    ctx.closePath();
    if (this.visuals.line.doit) {
      this.visuals.line.set_value(ctx);
      ctx.stroke();
    }
    if (this.visuals.fill.doit) {
      this.visuals.fill.set_value(ctx);
      return ctx.fill();
    }
  };

  return PolyAnnotationView;

})(Annotation.View);

PolyAnnotation = (function(superClass) {
  extend(PolyAnnotation, superClass);

  function PolyAnnotation() {
    return PolyAnnotation.__super__.constructor.apply(this, arguments);
  }

  PolyAnnotation.prototype.default_view = PolyAnnotationView;

  PolyAnnotation.prototype.type = "PolyAnnotation";

  PolyAnnotation.mixins(['line', 'fill']);

  PolyAnnotation.define({
    xs: [p.Array, []],
    xs_units: [p.SpatialUnits, 'data'],
    ys: [p.Array, []],
    ys_units: [p.SpatialUnits, 'data'],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default']
  });

  PolyAnnotation.override({
    fill_color: "#fff9ba",
    fill_alpha: 0.4,
    line_color: "#cccccc",
    line_alpha: 0.3
  });

  PolyAnnotation.prototype.update = function(arg) {
    var xs, ys;
    xs = arg.xs, ys = arg.ys;
    this.set({
      xs: xs,
      ys: ys
    }, {
      silent: true
    });
    return this.trigger('data_update');
  };

  return PolyAnnotation;

})(Annotation.Model);

module.exports = {
  Model: PolyAnnotation,
  View: PolyAnnotationView
};

},{"../../core/properties":"core/properties","./annotation":"models/annotations/annotation","underscore":"underscore"}],"models/annotations/span":[function(require,module,exports){
var Annotation, Span, SpanView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Annotation = require("./annotation");

p = require("../../core/properties");

SpanView = (function(superClass) {
  extend(SpanView, superClass);

  function SpanView() {
    return SpanView.__super__.constructor.apply(this, arguments);
  }

  SpanView.prototype.initialize = function(options) {
    SpanView.__super__.initialize.call(this, options);
    this.$el.appendTo(this.plot_view.$el.find('div.bk-canvas-overlays'));
    this.$el.css({
      position: 'absolute'
    });
    return this.$el.hide();
  };

  SpanView.prototype.bind_bokeh_events = function() {
    if (this.mget('for_hover')) {
      return this.listenTo(this.model, 'change:computed_location', this._draw_span);
    } else {
      if (this.mget('render_mode') === 'canvas') {
        return this.listenTo(this.model, 'change:location', this.plot_view.request_render);
      } else {
        return this.listenTo(this.model, 'change:location', this._draw_span);
      }
    }
  };

  SpanView.prototype.render = function() {
    return this._draw_span();
  };

  SpanView.prototype._draw_span = function() {
    var canvas, ctx, frame, height, loc, sleft, stop, width, xmapper, ymapper;
    if (this.mget('for_hover')) {
      loc = this.mget('computed_location');
    } else {
      loc = this.mget('location');
    }
    if (loc == null) {
      this.$el.hide();
      return;
    }
    frame = this.plot_model.get('frame');
    canvas = this.plot_model.get('canvas');
    xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    if (this.mget('dimension') === 'width') {
      stop = canvas.vy_to_sy(this._calc_dim(loc, ymapper));
      sleft = canvas.vx_to_sx(frame.get('left'));
      width = frame.get('width');
      height = this.model.properties.line_width.value();
    } else {
      stop = canvas.vy_to_sy(frame.get('top'));
      sleft = canvas.vx_to_sx(this._calc_dim(loc, xmapper));
      width = this.model.properties.line_width.value();
      height = frame.get('height');
    }
    if (this.mget("render_mode") === "css") {
      this.$el.css({
        'top': stop,
        'left': sleft,
        'width': width + "px",
        'height': height + "px",
        'z-index': 1000,
        'background-color': this.model.properties.line_color.value(),
        'opacity': this.model.properties.line_alpha.value()
      });
      return this.$el.show();
    } else if (this.mget("render_mode") === "canvas") {
      ctx = this.plot_view.canvas_view.ctx;
      ctx.save();
      ctx.beginPath();
      this.visuals.line.set_value(ctx);
      ctx.moveTo(sleft, stop);
      if (this.mget('dimension') === "width") {
        ctx.lineTo(sleft + width, stop);
      } else {
        ctx.lineTo(sleft, stop + height);
      }
      ctx.stroke();
      return ctx.restore();
    }
  };

  SpanView.prototype._calc_dim = function(location, mapper) {
    var vdim;
    if (this.mget('location_units') === 'data') {
      vdim = mapper.map_to_target(location);
    } else {
      vdim = location;
    }
    return vdim;
  };

  return SpanView;

})(Annotation.View);

Span = (function(superClass) {
  extend(Span, superClass);

  function Span() {
    return Span.__super__.constructor.apply(this, arguments);
  }

  Span.prototype.default_view = SpanView;

  Span.prototype.type = 'Span';

  Span.mixins(['line']);

  Span.define({
    render_mode: [p.RenderMode, 'canvas'],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default'],
    location: [p.Number, null],
    location_units: [p.SpatialUnits, 'data'],
    dimension: [p.Dimension, 'width']
  });

  Span.override({
    line_color: 'black'
  });

  Span.internal({
    for_hover: [p.Boolean, false],
    computed_location: [p.Number, null]
  });

  return Span;

})(Annotation.Model);

module.exports = {
  Model: Span,
  View: SpanView
};

},{"../../core/properties":"core/properties","./annotation":"models/annotations/annotation","underscore":"underscore"}],"models/annotations/text_annotation":[function(require,module,exports){
var Annotation, TextAnnotation, TextAnnotationView, _, get_text_height, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Annotation = require("./annotation");

p = require("../../core/properties");

get_text_height = require("../../core/util/text").get_text_height;

TextAnnotationView = (function(superClass) {
  extend(TextAnnotationView, superClass);

  function TextAnnotationView() {
    return TextAnnotationView.__super__.constructor.apply(this, arguments);
  }

  TextAnnotationView.prototype.initialize = function(options) {
    TextAnnotationView.__super__.initialize.call(this, options);
    this.canvas = this.plot_model.get('canvas');
    this.frame = this.plot_model.get('frame');
    if (this.mget('render_mode') === 'css') {
      this.$el.addClass('bk-annotation');
      return this.$el.appendTo(this.plot_view.$el.find('div.bk-canvas-overlays'));
    }
  };

  TextAnnotationView.prototype.bind_bokeh_events = function() {
    if (this.mget('render_mode') === 'css') {
      return this.listenTo(this.model, 'change', this.render);
    } else {
      return this.listenTo(this.model, 'change', this.plot_view.request_render);
    }
  };

  TextAnnotationView.prototype._calculate_text_dimensions = function(ctx, text) {
    var height, width;
    width = ctx.measureText(text).width;
    height = get_text_height(this.visuals.text.font_value()).height;
    return [width, height];
  };

  TextAnnotationView.prototype._calculate_bounding_box_dimensions = function(ctx, text) {
    var height, ref, width, x_offset, y_offset;
    ref = this._calculate_text_dimensions(ctx, text), width = ref[0], height = ref[1];
    switch (ctx.textAlign) {
      case 'left':
        x_offset = 0;
        break;
      case 'center':
        x_offset = -width / 2;
        break;
      case 'right':
        x_offset = -width;
    }
    switch (ctx.textBaseline) {
      case 'top':
        y_offset = 0.0;
        break;
      case 'middle':
        y_offset = -0.5 * height;
        break;
      case 'bottom':
        y_offset = -1.0 * height;
        break;
      case 'alphabetic':
        y_offset = -0.8 * height;
        break;
      case 'hanging':
        y_offset = -0.17 * height;
        break;
      case 'ideographic':
        y_offset = -0.83 * height;
    }
    return [x_offset, y_offset, width, height];
  };

  TextAnnotationView.prototype._get_size = function() {
    var ctx;
    ctx = this.plot_view.canvas_view.ctx;
    this.visuals.text.set_value(ctx);
    return ctx.measureText(this.mget('text')).ascent;
  };

  TextAnnotationView.prototype.render = function() {
    return null;
  };

  TextAnnotationView.prototype._canvas_text = function(ctx, text, sx, sy, angle) {
    var bbox_dims;
    this.visuals.text.set_value(ctx);
    bbox_dims = this._calculate_bounding_box_dimensions(ctx, text);
    ctx.save();
    ctx.beginPath();
    ctx.translate(sx, sy);
    if (angle) {
      ctx.rotate(angle);
    }
    ctx.rect(bbox_dims[0], bbox_dims[1], bbox_dims[2], bbox_dims[3]);
    if (this.visuals.background_fill.doit) {
      this.visuals.background_fill.set_value(ctx);
      ctx.fill();
    }
    if (this.visuals.border_line.doit) {
      this.visuals.border_line.set_value(ctx);
      ctx.stroke();
    }
    if (this.visuals.text.doit) {
      this.visuals.text.set_value(ctx);
      ctx.fillText(text, 0, 0);
    }
    return ctx.restore();
  };

  TextAnnotationView.prototype._css_text = function(ctx, text, sx, sy, angle) {
    var bbox_dims, div_style, ld, line_dash;
    this.$el.hide();
    this.visuals.text.set_value(ctx);
    bbox_dims = this._calculate_bounding_box_dimensions(ctx, text);
    ld = this.visuals.border_line.line_dash.value();
    if (_.isArray(ld)) {
      if (ld.length < 2) {
        line_dash = "solid";
      } else {
        line_dash = "dashed";
      }
    }
    if (_.isString(ld)) {
      line_dash = ld;
    }
    this.visuals.border_line.set_value(ctx);
    this.visuals.background_fill.set_value(ctx);
    div_style = {
      'position': 'absolute',
      'left': (sx + bbox_dims[0]) + "px",
      'top': (sy + bbox_dims[1]) + "px",
      'color': "" + (this.visuals.text.text_color.value()),
      'opacity': "" + (this.visuals.text.text_alpha.value()),
      'font': "" + (this.visuals.text.font_value()),
      'line-height': "normal"
    };
    if (angle) {
      _.extend(div_style, {
        'transform': "rotate(" + angle + "rad)"
      });
    }
    if (this.visuals.background_fill.doit) {
      _.extend(div_style, {
        'background-color': "" + (this.visuals.background_fill.color_value())
      });
    }
    if (this.visuals.border_line.doit) {
      _.extend(div_style, {
        'border-style': "" + line_dash,
        'border-width': "" + (this.visuals.border_line.line_width.value()),
        'border-color': "" + (this.visuals.border_line.color_value())
      });
    }
    return this.$el.html(text).css(div_style).show();
  };

  return TextAnnotationView;

})(Annotation.View);

TextAnnotation = (function(superClass) {
  extend(TextAnnotation, superClass);

  function TextAnnotation() {
    return TextAnnotation.__super__.constructor.apply(this, arguments);
  }

  TextAnnotation.prototype.type = 'TextAnnotation';

  TextAnnotation.prototype.default_view = TextAnnotationView;

  return TextAnnotation;

})(Annotation.Model);

module.exports = {
  Model: TextAnnotation,
  View: TextAnnotationView
};

},{"../../core/properties":"core/properties","../../core/util/text":"core/util/text","./annotation":"models/annotations/annotation","underscore":"underscore"}],"models/annotations/title":[function(require,module,exports){
var TextAnnotation, Title, TitleView, Visuals, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

TextAnnotation = require("./text_annotation");

p = require("../../core/properties");

Visuals = require("../renderers/renderer").Visuals;

TitleView = (function(superClass) {
  extend(TitleView, superClass);

  function TitleView() {
    return TitleView.__super__.constructor.apply(this, arguments);
  }

  TitleView.prototype.initialize = function(options) {
    var ctx;
    TitleView.__super__.initialize.call(this, options);
    this.visuals.text = new Visuals.text({
      obj: this.model,
      prefix: ""
    });
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    this.model.panel.apply_label_text_heuristics(ctx, 'justified');
    this.model.text_baseline = ctx.textBaseline;
    this.model.text_align = this.model.align;
    return ctx.restore();
  };

  TitleView.prototype._get_computed_location = function() {
    var height, ref, sx, sy, vx, vy, width;
    ref = this._calculate_text_dimensions(this.plot_view.canvas_view.ctx, this.text), width = ref[0], height = ref[1];
    switch (this.model.panel.side) {
      case 'left':
        vx = 0;
        vy = this._get_text_location(this.mget('align'), this.frame.get('v_range')) + this.mget('offset');
        break;
      case 'right':
        vx = this.canvas.get('right') - 1;
        vy = this.canvas.get('height') - this._get_text_location(this.mget('align'), this.frame.get('v_range')) - this.mget('offset');
        break;
      case 'above':
        vx = this._get_text_location(this.mget('align'), this.frame.get('h_range')) + this.mget('offset');
        vy = this.canvas.get('top') - 10;
        break;
      case 'below':
        vx = this._get_text_location(this.mget('align'), this.frame.get('h_range')) + this.mget('offset');
        vy = 0;
    }
    sx = this.canvas.vx_to_sx(vx);
    sy = this.canvas.vy_to_sy(vy);
    return [sx, sy];
  };

  TitleView.prototype._get_text_location = function(alignment, range) {
    var text_location;
    switch (alignment) {
      case 'left':
        text_location = range.get('start');
        break;
      case 'center':
        text_location = (range.get('end') + range.get('start')) / 2;
        break;
      case 'right':
        text_location = range.get('end');
    }
    return text_location;
  };

  TitleView.prototype.render = function() {
    var angle, ctx, ref, sx, sy;
    angle = this.model.panel.get_label_angle_heuristic('parallel');
    ref = this._get_computed_location(), sx = ref[0], sy = ref[1];
    ctx = this.plot_view.canvas_view.ctx;
    if (this.model.text === "" || this.model.text === null) {
      return;
    }
    if (this.model.render_mode === 'canvas') {
      return this._canvas_text(ctx, this.model.text, sx, sy, angle);
    } else {
      return this._css_text(ctx, this.model.text, sx, sy, angle);
    }
  };

  TitleView.prototype._get_size = function() {
    var ctx, text;
    text = this.model.text;
    if (text === "" || text === null) {
      return 0;
    } else {
      ctx = this.plot_view.canvas_view.ctx;
      this.visuals.text.set_value(ctx);
      return ctx.measureText(text).ascent + 10;
    }
  };

  return TitleView;

})(TextAnnotation.View);

Title = (function(superClass) {
  extend(Title, superClass);

  function Title() {
    return Title.__super__.constructor.apply(this, arguments);
  }

  Title.prototype.default_view = TitleView;

  Title.prototype.type = 'Title';

  Title.mixins(['line:border_', 'fill:background_']);

  Title.define({
    text: [p.String],
    text_font: [p.Font, 'helvetica'],
    text_font_size: [p.FontSizeSpec, '10pt'],
    text_font_style: [p.FontStyle, 'bold'],
    text_color: [p.ColorSpec, '#444444'],
    text_alpha: [p.NumberSpec, 1.0],
    align: [p.TextAlign, 'left'],
    offset: [p.Number, 0],
    render_mode: [p.RenderMode, 'canvas']
  });

  Title.override({
    background_fill_color: null,
    border_line_color: null
  });

  Title.internal({
    text_align: [p.TextAlign, 'left'],
    text_baseline: [p.TextBaseline, 'bottom']
  });

  return Title;

})(TextAnnotation.Model);

module.exports = {
  Model: Title,
  View: TitleView
};

},{"../../core/properties":"core/properties","../renderers/renderer":"models/renderers/renderer","./text_annotation":"models/annotations/text_annotation"}],"models/annotations/tooltip":[function(require,module,exports){
var $, Annotation, Tooltip, TooltipView, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

$ = require("jquery");

_ = require("underscore");

Annotation = require("./annotation");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

TooltipView = (function(superClass) {
  extend(TooltipView, superClass);

  function TooltipView() {
    return TooltipView.__super__.constructor.apply(this, arguments);
  }

  TooltipView.prototype.className = "bk-tooltip";

  TooltipView.prototype.initialize = function(options) {
    TooltipView.__super__.initialize.call(this, options);
    this.$el.appendTo(this.plot_view.$el.find('div.bk-canvas-overlays'));
    this.$el.css({
      'z-index': 1010
    });
    return this.$el.hide();
  };

  TooltipView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change:data', this._draw_tips);
  };

  TooltipView.prototype.render = function() {
    return this._draw_tips();
  };

  TooltipView.prototype._draw_tips = function() {
    var arrow_size, attachment, bottom, content, data, height, i, left, len, side, sx, sy, tip, top, val, vx, vy, width;
    data = this.model.data;
    this.$el.empty();
    this.$el.hide();
    this.$el.toggleClass("bk-tooltip-custom", this.mget("custom"));
    if (_.isEmpty(data)) {
      return;
    }
    for (i = 0, len = data.length; i < len; i++) {
      val = data[i];
      vx = val[0], vy = val[1], content = val[2];
      if (this.mget('inner_only') && !this.plot_view.frame.contains(vx, vy)) {
        continue;
      }
      tip = $('<div />').appendTo(this.$el);
      tip.append(content);
    }
    sx = this.plot_view.mget('canvas').vx_to_sx(vx);
    sy = this.plot_view.mget('canvas').vy_to_sy(vy);
    attachment = this.model.attachment;
    switch (attachment) {
      case "horizontal":
        width = this.plot_view.frame.get('width');
        left = this.plot_view.frame.get('left');
        if (vx - left < width / 2) {
          side = 'right';
        } else {
          side = 'left';
        }
        break;
      case "vertical":
        height = this.plot_view.frame.get('height');
        bottom = this.plot_view.frame.get('bottom');
        if (vy - bottom < height / 2) {
          side = 'below';
        } else {
          side = 'above';
        }
        break;
      default:
        side = attachment;
    }
    this.$el.removeClass('bk-right bk-left bk-above bk-below');
    arrow_size = 10;
    switch (side) {
      case "right":
        this.$el.addClass("bk-left");
        left = sx + (this.$el.outerWidth() - this.$el.innerWidth()) + arrow_size;
        top = sy - this.$el.outerHeight() / 2;
        break;
      case "left":
        this.$el.addClass("bk-right");
        left = sx - this.$el.outerWidth() - arrow_size;
        top = sy - this.$el.outerHeight() / 2;
        break;
      case "above":
        this.$el.addClass("bk-above");
        top = sy + (this.$el.outerHeight() - this.$el.innerHeight()) + arrow_size;
        left = Math.round(sx - this.$el.outerWidth() / 2);
        break;
      case "below":
        this.$el.addClass("bk-below");
        top = sy - this.$el.outerHeight() - arrow_size;
        left = Math.round(sx - this.$el.outerWidth() / 2);
    }
    if (this.$el.children().length > 0) {
      this.$el.css({
        top: top,
        left: left
      });
      return this.$el.show();
    }
  };

  return TooltipView;

})(Annotation.View);

Tooltip = (function(superClass) {
  extend(Tooltip, superClass);

  function Tooltip() {
    return Tooltip.__super__.constructor.apply(this, arguments);
  }

  Tooltip.prototype.default_view = TooltipView;

  Tooltip.prototype.type = 'Tooltip';

  Tooltip.define({
    attachment: [p.String, 'horizontal'],
    inner_only: [p.Bool, true]
  });

  Tooltip.override({
    level: 'overlay'
  });

  Tooltip.internal({
    data: [p.Any, []],
    custom: [p.Any]
  });

  Tooltip.prototype.clear = function() {
    return this.data = [];
  };

  Tooltip.prototype.add = function(vx, vy, content) {
    var data;
    data = this.data;
    data.push([vx, vy, content]);
    this.data = data;
    return this.trigger('change:data');
  };

  return Tooltip;

})(Annotation.Model);

module.exports = {
  Model: Tooltip,
  View: TooltipView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./annotation":"models/annotations/annotation","jquery":"jquery","underscore":"underscore"}],"models/axes/axis":[function(require,module,exports){
var Axis, AxisView, GE, GuideRenderer, Renderer, SidePanel, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SidePanel = require("../../core/layout/side_panel");

GuideRenderer = require("../renderers/guide_renderer");

Renderer = require("../renderers/renderer");

GE = require("../../core/layout/solver").GE;

logger = require("../../core/logging").logger;

p = require("../../core/properties");

AxisView = (function(superClass) {
  extend(AxisView, superClass);

  function AxisView() {
    return AxisView.__super__.constructor.apply(this, arguments);
  }

  AxisView.prototype.initialize = function(options) {
    AxisView.__super__.initialize.call(this, options);
    this._x_range_name = this.mget('x_range_name');
    return this._y_range_name = this.mget('y_range_name');
  };

  AxisView.prototype.render = function() {
    var ctx;
    if (this.model.visible === false) {
      return;
    }
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    this._draw_rule(ctx);
    this._draw_major_ticks(ctx);
    this._draw_minor_ticks(ctx);
    this._draw_major_labels(ctx);
    this._draw_axis_label(ctx);
    return ctx.restore();
  };

  AxisView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change', this.plot_view.request_render);
  };

  AxisView.prototype._get_size = function() {
    return this._tick_extent() + this._tick_label_extent() + this._axis_label_extent();
  };

  AxisView.prototype._draw_rule = function(ctx) {
    var coords, i, k, nx, ny, ref, ref1, ref2, ref3, ref4, sx, sy, x, xoff, y, yoff;
    if (!this.visuals.axis_line.doit) {
      return;
    }
    ref = coords = this.mget('rule_coords'), x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this._x_range_name, this._y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    this.visuals.axis_line.set_value(ctx);
    ctx.beginPath();
    ctx.moveTo(Math.round(sx[0] + nx * xoff), Math.round(sy[0] + ny * yoff));
    for (i = k = 1, ref4 = sx.length; 1 <= ref4 ? k < ref4 : k > ref4; i = 1 <= ref4 ? ++k : --k) {
      ctx.lineTo(Math.round(sx[i] + nx * xoff), Math.round(sy[i] + ny * yoff));
    }
    return ctx.stroke();
  };

  AxisView.prototype._draw_major_ticks = function(ctx) {
    var coords, i, k, nx, ny, ref, ref1, ref2, ref3, ref4, results, sx, sy, tin, tout, x, xoff, y, yoff;
    if (!this.visuals.major_tick_line.doit) {
      return;
    }
    coords = this.mget('tick_coords');
    ref = coords.major, x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this._x_range_name, this._y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    tin = this.mget('major_tick_in');
    tout = this.mget('major_tick_out');
    this.visuals.major_tick_line.set_value(ctx);
    results = [];
    for (i = k = 0, ref4 = sx.length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
      ctx.beginPath();
      ctx.moveTo(Math.round(sx[i] + nx * tout + nx * xoff), Math.round(sy[i] + ny * tout + ny * yoff));
      ctx.lineTo(Math.round(sx[i] - nx * tin + nx * xoff), Math.round(sy[i] - ny * tin + ny * yoff));
      results.push(ctx.stroke());
    }
    return results;
  };

  AxisView.prototype._draw_minor_ticks = function(ctx) {
    var coords, i, k, nx, ny, ref, ref1, ref2, ref3, ref4, results, sx, sy, tin, tout, x, xoff, y, yoff;
    if (!this.visuals.minor_tick_line.doit) {
      return;
    }
    coords = this.mget('tick_coords');
    ref = coords.minor, x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this._x_range_name, this._y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    tin = this.mget('minor_tick_in');
    tout = this.mget('minor_tick_out');
    this.visuals.minor_tick_line.set_value(ctx);
    results = [];
    for (i = k = 0, ref4 = sx.length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
      ctx.beginPath();
      ctx.moveTo(Math.round(sx[i] + nx * tout + nx * xoff), Math.round(sy[i] + ny * tout + ny * yoff));
      ctx.lineTo(Math.round(sx[i] - nx * tin + nx * xoff), Math.round(sy[i] - ny * tin + ny * yoff));
      results.push(ctx.stroke());
    }
    return results;
  };

  AxisView.prototype._draw_major_labels = function(ctx) {
    var angle, coords, dim, i, k, labels, nx, ny, orient, ref, ref1, ref2, ref3, ref4, results, side, standoff, sx, sy, x, xoff, y, yoff;
    coords = this.mget('tick_coords');
    ref = coords.major, x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this._x_range_name, this._y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    dim = this.mget('dimension');
    side = this.mget('panel_side');
    orient = this.mget('major_label_orientation');
    if (_.isString(orient)) {
      angle = this.model.panel.get_label_angle_heuristic(orient);
    } else {
      angle = -orient;
    }
    standoff = this._tick_extent() + this.mget('major_label_standoff');
    labels = this.mget('formatter').doFormat(coords.major[dim]);
    this.visuals.major_label_text.set_value(ctx);
    this.model.panel.apply_label_text_heuristics(ctx, orient);
    results = [];
    for (i = k = 0, ref4 = sx.length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
      if (angle) {
        ctx.translate(sx[i] + nx * standoff + nx * xoff, sy[i] + ny * standoff + ny * yoff);
        ctx.rotate(angle);
        ctx.fillText(labels[i], 0, 0);
        ctx.rotate(-angle);
        results.push(ctx.translate(-sx[i] - nx * standoff + nx * xoff, -sy[i] - ny * standoff + ny * yoff));
      } else {
        results.push(ctx.fillText(labels[i], Math.round(sx[i] + nx * standoff + nx * xoff), Math.round(sy[i] + ny * standoff + ny * yoff)));
      }
    }
    return results;
  };

  AxisView.prototype._draw_axis_label = function(ctx) {
    var angle, label, nx, ny, orient, ref, ref1, ref2, ref3, side, standoff, sx, sy, x, xoff, y, yoff;
    label = this.mget('axis_label');
    if (label == null) {
      return;
    }
    ref = this.mget('rule_coords'), x = ref[0], y = ref[1];
    ref1 = this.plot_view.map_to_screen(x, y, this._x_range_name, this._y_range_name), sx = ref1[0], sy = ref1[1];
    ref2 = this.mget('normals'), nx = ref2[0], ny = ref2[1];
    ref3 = this.mget('offsets'), xoff = ref3[0], yoff = ref3[1];
    side = this.mget('panel_side');
    orient = 'parallel';
    angle = this.model.panel.get_label_angle_heuristic(orient);
    standoff = this._tick_extent() + this._tick_label_extent() + this.mget('axis_label_standoff');
    sx = (sx[0] + sx[sx.length - 1]) / 2;
    sy = (sy[0] + sy[sy.length - 1]) / 2;
    this.visuals.axis_label_text.set_value(ctx);
    this.model.panel.apply_label_text_heuristics(ctx, orient);
    x = sx + nx * standoff + nx * xoff;
    y = sy + ny * standoff + ny * yoff;
    if (isNaN(x) || isNaN(y)) {
      return;
    }
    if (angle) {
      ctx.translate(x, y);
      ctx.rotate(angle);
      ctx.fillText(label, 0, 0);
      ctx.rotate(-angle);
      return ctx.translate(-x, -y);
    } else {
      return ctx.fillText(label, x, y);
    }
  };

  AxisView.prototype._tick_extent = function() {
    return this.mget('major_tick_out');
  };

  AxisView.prototype._tick_label_extent = function() {
    var angle, c, coords, ctx, dim, extent, h, hfactor, hscale, i, k, labels, orient, ref, s, side, val, w, wfactor;
    extent = 0;
    ctx = this.plot_view.canvas_view.ctx;
    dim = this.mget('dimension');
    coords = this.mget('tick_coords').major;
    side = this.mget('panel_side');
    orient = this.mget('major_label_orientation');
    labels = this.mget('formatter').doFormat(coords[dim]);
    this.visuals.major_label_text.set_value(ctx);
    if (_.isString(orient)) {
      hscale = 1;
      angle = this.model.panel.get_label_angle_heuristic(orient);
    } else {
      hscale = 2;
      angle = -orient;
    }
    angle = Math.abs(angle);
    c = Math.cos(angle);
    s = Math.sin(angle);
    if (side === "above" || side === "below") {
      wfactor = s;
      hfactor = c;
    } else {
      wfactor = c;
      hfactor = s;
    }
    for (i = k = 0, ref = labels.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      if (labels[i] == null) {
        continue;
      }
      w = ctx.measureText(labels[i]).width * 1.1;
      h = ctx.measureText(labels[i]).ascent * 0.9;
      val = w * wfactor + (h / hscale) * hfactor;
      if (val > extent) {
        extent = val;
      }
    }
    if (extent > 0) {
      extent += this.mget('major_label_standoff');
    }
    return extent;
  };

  AxisView.prototype._axis_label_extent = function() {
    var angle, axis_label, c, ctx, extent, h, orient, s, side, w;
    extent = 0;
    side = this.mget('panel_side');
    axis_label = this.mget('axis_label');
    orient = 'parallel';
    ctx = this.plot_view.canvas_view.ctx;
    this.visuals.axis_label_text.set_value(ctx);
    angle = Math.abs(this.model.panel.get_label_angle_heuristic(orient));
    c = Math.cos(angle);
    s = Math.sin(angle);
    if (axis_label) {
      extent += this.mget('axis_label_standoff');
      this.visuals.axis_label_text.set_value(ctx);
      w = ctx.measureText(axis_label).width * 1.1;
      h = ctx.measureText(axis_label).ascent * 0.9;
      if (side === "above" || side === "below") {
        extent += w * s + h * c;
      } else {
        extent += w * c + h * s;
      }
    }
    return extent;
  };

  return AxisView;

})(Renderer.View);

Axis = (function(superClass) {
  extend(Axis, superClass);

  function Axis() {
    return Axis.__super__.constructor.apply(this, arguments);
  }

  Axis.prototype.default_view = AxisView;

  Axis.prototype.type = 'Axis';

  Axis.mixins(['line:axis_', 'line:major_tick_', 'line:minor_tick_', 'text:major_label_', 'text:axis_label_']);

  Axis.define({
    bounds: [p.Any, 'auto'],
    ticker: [p.Instance, null],
    formatter: [p.Instance, null],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default'],
    axis_label: [p.String, ''],
    axis_label_standoff: [p.Int, 5],
    major_label_standoff: [p.Int, 5],
    major_label_orientation: [p.Any, "horizontal"],
    major_tick_in: [p.Number, 2],
    major_tick_out: [p.Number, 6],
    minor_tick_in: [p.Number, 0],
    minor_tick_out: [p.Number, 4]
  });

  Axis.override({
    axis_line_color: 'black',
    major_tick_line_color: 'black',
    minor_tick_line_color: 'black',
    major_label_text_font_size: "8pt",
    major_label_text_align: "center",
    major_label_text_baseline: "alphabetic",
    axis_label_text_font_size: "10pt",
    axis_label_text_font_style: "italic"
  });

  Axis.internal({
    panel_side: [p.Any]
  });

  Axis.prototype.initialize = function(attrs, options) {
    Axis.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('computed_bounds', this._computed_bounds, false);
    this.add_dependencies('computed_bounds', this, ['bounds']);
    this.add_dependencies('computed_bounds', this.get('plot'), ['x_range', 'y_range']);
    this.define_computed_property('rule_coords', this._rule_coords, false);
    this.add_dependencies('rule_coords', this, ['computed_bounds', 'side']);
    this.define_computed_property('tick_coords', this._tick_coords, false);
    this.add_dependencies('tick_coords', this, ['computed_bounds', 'panel_side']);
    this.define_computed_property('ranges', this._ranges, true);
    this.define_computed_property('normals', (function() {
      return this.panel._normals;
    }), true);
    this.define_computed_property('dimension', (function() {
      return this.panel._dim;
    }), true);
    return this.define_computed_property('offsets', this._offsets, true);
  };

  Axis.prototype.add_panel = function(side) {
    this.panel = new SidePanel.Model({
      side: side
    });
    this.panel.attach_document(this.document);
    return this.set('panel_side', side);
  };

  Axis.prototype._offsets = function() {
    var frame, ref, side, xoff, yoff;
    side = this.get('panel_side');
    ref = [0, 0], xoff = ref[0], yoff = ref[1];
    frame = this.plot.plot_canvas.get('frame');
    if (side === "below") {
      yoff = Math.abs(this.panel.get("top") - frame.get("bottom"));
    } else if (side === "above") {
      yoff = Math.abs(this.panel.get("bottom") - frame.get("top"));
    } else if (side === "right") {
      xoff = Math.abs(this.panel.get("left") - frame.get("right"));
    } else if (side === "left") {
      xoff = Math.abs(this.panel.get("right") - frame.get("left"));
    }
    return [xoff, yoff];
  };

  Axis.prototype._ranges = function() {
    var frame, i, j, ranges;
    i = this.get('dimension');
    j = (i + 1) % 2;
    frame = this.plot.plot_canvas.get('frame');
    ranges = [frame.get('x_ranges')[this.get('x_range_name')], frame.get('y_ranges')[this.get('y_range_name')]];
    return [ranges[i], ranges[j]];
  };

  Axis.prototype._computed_bounds = function() {
    var cross_range, end, range, range_bounds, ref, ref1, start, user_bounds;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.get('bounds')) != null ? ref1 : 'auto';
    range_bounds = [range.get('min'), range.get('max')];
    if (user_bounds === 'auto') {
      return range_bounds;
    }
    if (_.isArray(user_bounds)) {
      if (Math.abs(user_bounds[0] - user_bounds[1]) > Math.abs(range_bounds[0] - range_bounds[1])) {
        start = Math.max(Math.min(user_bounds[0], user_bounds[1]), range_bounds[0]);
        end = Math.min(Math.max(user_bounds[0], user_bounds[1]), range_bounds[1]);
      } else {
        start = Math.min(user_bounds[0], user_bounds[1]);
        end = Math.max(user_bounds[0], user_bounds[1]);
      }
      return [start, end];
    }
    logger.error("user bounds '" + user_bounds + "' not understood");
    return null;
  };

  Axis.prototype._rule_coords = function() {
    var coords, cross_range, end, i, j, loc, range, ref, ref1, start, xs, ys;
    i = this.get('dimension');
    j = (i + 1) % 2;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    ref1 = this.get('computed_bounds'), start = ref1[0], end = ref1[1];
    xs = new Array(2);
    ys = new Array(2);
    coords = [xs, ys];
    loc = this._get_loc(cross_range);
    coords[i][0] = Math.max(start, range.get('min'));
    coords[i][1] = Math.min(end, range.get('max'));
    if (coords[i][0] > coords[i][1]) {
      coords[i][0] = coords[i][1] = NaN;
    }
    coords[j][0] = loc;
    coords[j][1] = loc;
    return coords;
  };

  Axis.prototype._tick_coords = function() {
    var coords, cross_range, end, i, ii, j, k, l, loc, m, majors, minor_coords, minor_xs, minor_ys, minors, range, range_max, range_min, ref, ref1, ref2, ref3, ref4, ref5, start, ticks, xs, ys;
    i = this.get('dimension');
    j = (i + 1) % 2;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    ref1 = this.get('computed_bounds'), start = ref1[0], end = ref1[1];
    ticks = this.get('ticker').get_ticks(start, end, range, {});
    majors = ticks.major;
    minors = ticks.minor;
    loc = this._get_loc(cross_range);
    xs = [];
    ys = [];
    coords = [xs, ys];
    minor_xs = [];
    minor_ys = [];
    minor_coords = [minor_xs, minor_ys];
    if (range.type === "FactorRange") {
      for (ii = k = 0, ref2 = majors.length; 0 <= ref2 ? k < ref2 : k > ref2; ii = 0 <= ref2 ? ++k : --k) {
        coords[i].push(majors[ii]);
        coords[j].push(loc);
      }
    } else {
      ref3 = [range.get('min'), range.get('max')], range_min = ref3[0], range_max = ref3[1];
      for (ii = l = 0, ref4 = majors.length; 0 <= ref4 ? l < ref4 : l > ref4; ii = 0 <= ref4 ? ++l : --l) {
        if (majors[ii] < range_min || majors[ii] > range_max) {
          continue;
        }
        coords[i].push(majors[ii]);
        coords[j].push(loc);
      }
      for (ii = m = 0, ref5 = minors.length; 0 <= ref5 ? m < ref5 : m > ref5; ii = 0 <= ref5 ? ++m : --m) {
        if (minors[ii] < range_min || minors[ii] > range_max) {
          continue;
        }
        minor_coords[i].push(minors[ii]);
        minor_coords[j].push(loc);
      }
    }
    return {
      "major": coords,
      "minor": minor_coords
    };
  };

  Axis.prototype._get_loc = function(cross_range) {
    var cend, cstart, loc, side;
    cstart = cross_range.get('start');
    cend = cross_range.get('end');
    side = this.get('panel_side');
    if (side === 'left' || side === 'below') {
      loc = 'start';
    } else if (side === 'right' || side === 'above') {
      loc = 'end';
    }
    return cross_range.get(loc);
  };

  return Axis;

})(GuideRenderer.Model);

module.exports = {
  Model: Axis,
  View: AxisView
};

},{"../../core/layout/side_panel":"core/layout/side_panel","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../renderers/guide_renderer":"models/renderers/guide_renderer","../renderers/renderer":"models/renderers/renderer","underscore":"underscore"}],"models/axes/categorical_axis":[function(require,module,exports){
var Axis, CategoricalAxis, CategoricalAxisView, CategoricalTickFormatter, CategoricalTicker, _, logger,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Axis = require("./axis");

CategoricalTickFormatter = require("../formatters/categorical_tick_formatter");

CategoricalTicker = require("../tickers/categorical_ticker");

logger = require("../../core/logging").logger;

CategoricalAxisView = (function(superClass) {
  extend(CategoricalAxisView, superClass);

  function CategoricalAxisView() {
    return CategoricalAxisView.__super__.constructor.apply(this, arguments);
  }

  return CategoricalAxisView;

})(Axis.View);

CategoricalAxis = (function(superClass) {
  extend(CategoricalAxis, superClass);

  function CategoricalAxis() {
    return CategoricalAxis.__super__.constructor.apply(this, arguments);
  }

  CategoricalAxis.prototype.default_view = CategoricalAxisView;

  CategoricalAxis.prototype.type = 'CategoricalAxis';

  CategoricalAxis.override({
    ticker: function() {
      return new CategoricalTicker.Model();
    },
    formatter: function() {
      return new CategoricalTickFormatter.Model();
    }
  });

  CategoricalAxis.prototype._computed_bounds = function() {
    var cross_range, range, range_bounds, ref, ref1, user_bounds;
    ref = this.get('ranges'), range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.get('bounds')) != null ? ref1 : 'auto';
    range_bounds = [range.get('min'), range.get('max')];
    if (user_bounds !== 'auto') {
      logger.warn("Categorical Axes only support user_bounds='auto', ignoring");
    }
    return range_bounds;
  };

  return CategoricalAxis;

})(Axis.Model);

module.exports = {
  Model: CategoricalAxis,
  View: CategoricalAxisView
};

},{"../../core/logging":"core/logging","../formatters/categorical_tick_formatter":"models/formatters/categorical_tick_formatter","../tickers/categorical_ticker":"models/tickers/categorical_ticker","./axis":"models/axes/axis","underscore":"underscore"}],"models/axes/continuous_axis":[function(require,module,exports){
var Axis, ContinuousAxis,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Axis = require("./axis");

ContinuousAxis = (function(superClass) {
  extend(ContinuousAxis, superClass);

  function ContinuousAxis() {
    return ContinuousAxis.__super__.constructor.apply(this, arguments);
  }

  ContinuousAxis.prototype.type = 'ContinuousAxis';

  return ContinuousAxis;

})(Axis.Model);

module.exports = {
  Model: ContinuousAxis
};

},{"./axis":"models/axes/axis"}],"models/axes/datetime_axis":[function(require,module,exports){
var DatetimeAxis, DatetimeAxisView, DatetimeTickFormatter, DatetimeTicker, LinearAxis, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

LinearAxis = require("./axis");

DatetimeTickFormatter = require("../formatters/datetime_tick_formatter");

DatetimeTicker = require("../tickers/datetime_ticker");

DatetimeAxisView = (function(superClass) {
  extend(DatetimeAxisView, superClass);

  function DatetimeAxisView() {
    return DatetimeAxisView.__super__.constructor.apply(this, arguments);
  }

  return DatetimeAxisView;

})(LinearAxis.View);

DatetimeAxis = (function(superClass) {
  extend(DatetimeAxis, superClass);

  function DatetimeAxis() {
    return DatetimeAxis.__super__.constructor.apply(this, arguments);
  }

  DatetimeAxis.prototype.default_view = DatetimeAxisView;

  DatetimeAxis.prototype.type = 'DatetimeAxis';

  DatetimeAxis.override({
    ticker: function() {
      return new DatetimeTicker.Model();
    },
    formatter: function() {
      return new DatetimeTickFormatter.Model();
    }
  });

  return DatetimeAxis;

})(LinearAxis.Model);

module.exports = {
  Model: DatetimeAxis,
  View: DatetimeAxisView
};

},{"../formatters/datetime_tick_formatter":"models/formatters/datetime_tick_formatter","../tickers/datetime_ticker":"models/tickers/datetime_ticker","./axis":"models/axes/axis","underscore":"underscore"}],"models/axes/linear_axis":[function(require,module,exports){
var Axis, BasicTickFormatter, BasicTicker, ContinuousAxis, LinearAxis, LinearAxisView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Axis = require("./axis");

ContinuousAxis = require("./continuous_axis");

BasicTickFormatter = require("../formatters/basic_tick_formatter");

BasicTicker = require("../tickers/basic_ticker");

LinearAxisView = (function(superClass) {
  extend(LinearAxisView, superClass);

  function LinearAxisView() {
    return LinearAxisView.__super__.constructor.apply(this, arguments);
  }

  return LinearAxisView;

})(Axis.View);

LinearAxis = (function(superClass) {
  extend(LinearAxis, superClass);

  function LinearAxis() {
    return LinearAxis.__super__.constructor.apply(this, arguments);
  }

  LinearAxis.prototype.default_view = LinearAxisView;

  LinearAxis.prototype.type = 'LinearAxis';

  LinearAxis.override({
    ticker: function() {
      return new BasicTicker.Model();
    },
    formatter: function() {
      return new BasicTickFormatter.Model();
    }
  });

  return LinearAxis;

})(ContinuousAxis.Model);

module.exports = {
  Model: LinearAxis,
  View: LinearAxisView
};

},{"../formatters/basic_tick_formatter":"models/formatters/basic_tick_formatter","../tickers/basic_ticker":"models/tickers/basic_ticker","./axis":"models/axes/axis","./continuous_axis":"models/axes/continuous_axis","underscore":"underscore"}],"models/axes/log_axis":[function(require,module,exports){
var Axis, ContinuousAxis, LogAxis, LogAxisView, LogTickFormatter, LogTicker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Axis = require("./axis");

ContinuousAxis = require("./continuous_axis");

LogTickFormatter = require("../formatters/log_tick_formatter");

LogTicker = require("../tickers/log_ticker");

LogAxisView = (function(superClass) {
  extend(LogAxisView, superClass);

  function LogAxisView() {
    return LogAxisView.__super__.constructor.apply(this, arguments);
  }

  return LogAxisView;

})(Axis.View);

LogAxis = (function(superClass) {
  extend(LogAxis, superClass);

  function LogAxis() {
    return LogAxis.__super__.constructor.apply(this, arguments);
  }

  LogAxis.prototype.default_view = LogAxisView;

  LogAxis.prototype.type = 'LogAxis';

  LogAxis.override({
    ticker: function() {
      return new LogTicker.Model();
    },
    formatter: function() {
      return new LogTickFormatter.Model();
    }
  });

  return LogAxis;

})(ContinuousAxis.Model);

module.exports = {
  Model: LogAxis,
  View: LogAxisView
};

},{"../formatters/log_tick_formatter":"models/formatters/log_tick_formatter","../tickers/log_ticker":"models/tickers/log_ticker","./axis":"models/axes/axis","./continuous_axis":"models/axes/continuous_axis","underscore":"underscore"}],"models/callbacks/customjs":[function(require,module,exports){
var CustomJS, Model, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  slice = [].slice;

_ = require("underscore");

p = require("../../core/properties");

Model = require("../../model");

CustomJS = (function(superClass) {
  extend(CustomJS, superClass);

  function CustomJS() {
    return CustomJS.__super__.constructor.apply(this, arguments);
  }

  CustomJS.prototype.type = 'CustomJS';

  CustomJS.define({
    args: [p.Any, {}],
    code: [p.String, ''],
    lang: [p.String, 'javascript']
  });

  CustomJS.prototype.initialize = function(attrs, options) {
    CustomJS.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('values', this._make_values, true);
    this.add_dependencies('values', this, ['args']);
    this.define_computed_property('func', this._make_func, true);
    return this.add_dependencies('func', this, ['args', 'code']);
  };

  CustomJS.prototype.execute = function(cb_obj, cb_data) {
    return this.get('func').apply(null, slice.call(this.get('values')).concat([cb_obj], [cb_data], [require]));
  };

  CustomJS.prototype._make_values = function() {
    return _.values(this.get("args"));
  };

  CustomJS.prototype._make_func = function() {
    var code, coffee;
    code = this.get("code");
    code = (function() {
      switch (this.get("lang")) {
        case "javascript":
          return code;
        case "coffeescript":
          coffee = require("coffee-script");
          return coffee.compile(code, {
            bare: true,
            shiftLine: true
          });
      }
    }).call(this);
    return (function(func, args, ctor) {
      ctor.prototype = func.prototype;
      var child = new ctor, result = func.apply(child, args);
      return Object(result) === result ? result : child;
    })(Function, slice.call(_.keys(this.get("args"))).concat(["cb_obj"], ["cb_data"], ["require"], [code]), function(){});
  };

  return CustomJS;

})(Model);

module.exports = {
  Model: CustomJS
};

},{"../../core/properties":"core/properties","../../model":"model","coffee-script":undefined,"underscore":"underscore"}],"models/callbacks/open_url":[function(require,module,exports){
var Model, OpenURL, Util, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

p = require("../../core/properties");

Model = require("../../model");

Util = require("../../util/util");

OpenURL = (function(superClass) {
  extend(OpenURL, superClass);

  function OpenURL() {
    return OpenURL.__super__.constructor.apply(this, arguments);
  }

  OpenURL.prototype.type = 'OpenURL';

  OpenURL.define({
    url: [p.String, 'http://']
  });

  OpenURL.prototype.execute = function(data_source) {
    var i, j, len, ref, url;
    ref = Util.get_indices(data_source);
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      url = Util.replace_placeholders(this.get("url"), data_source, i);
      window.open(url);
    }
    return null;
  };

  return OpenURL;

})(Model);

module.exports = {
  Model: OpenURL
};

},{"../../core/properties":"core/properties","../../model":"model","../../util/util":"util/util","underscore":"underscore"}],"models/canvas/canvas":[function(require,module,exports){
var BokehView, Canvas, CanvasView, EQ, GE, LayoutCanvas, _, canvas_template, fixup_ellipse, fixup_image_smoothing, fixup_line_dash, fixup_line_dash_offset, fixup_measure_text, get_scale_ratio, logger, p, ref, ref1,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

canvas_template = require("./canvas_template");

LayoutCanvas = require("../../core/layout/layout_canvas");

BokehView = require("../../core/bokeh_view");

ref = require("../../core/layout/solver"), GE = ref.GE, EQ = ref.EQ;

logger = require("../../core/logging").logger;

p = require("../../core/properties");

ref1 = require("../../core/util/canvas"), fixup_image_smoothing = ref1.fixup_image_smoothing, fixup_line_dash = ref1.fixup_line_dash, fixup_line_dash_offset = ref1.fixup_line_dash_offset, fixup_measure_text = ref1.fixup_measure_text, get_scale_ratio = ref1.get_scale_ratio, fixup_ellipse = ref1.fixup_ellipse;

CanvasView = (function(superClass) {
  extend(CanvasView, superClass);

  function CanvasView() {
    return CanvasView.__super__.constructor.apply(this, arguments);
  }

  CanvasView.prototype.className = "bk-canvas-wrapper";

  CanvasView.prototype.template = canvas_template;

  CanvasView.prototype.initialize = function(options) {
    var html, ref2;
    CanvasView.__super__.initialize.call(this, options);
    html = this.template({
      map: this.mget('map')
    });
    this.$el.html(html);
    this.ctx = this.get_ctx();
    this.ctx.glcanvas = null;
    fixup_line_dash(this.ctx);
    fixup_line_dash_offset(this.ctx);
    fixup_image_smoothing(this.ctx);
    fixup_measure_text(this.ctx);
    fixup_ellipse(this.ctx);
    this.map_div = (ref2 = this.$('div.bk-canvas-map')) != null ? ref2 : null;
    this.set_dims([this.model.initial_width, this.model.initial_height]);
    return logger.debug("CanvasView initialized");
  };

  CanvasView.prototype.get_canvas_element = function() {
    return this.$('canvas.bk-canvas')[0];
  };

  CanvasView.prototype.get_ctx = function() {
    var canvas_el, ctx;
    canvas_el = this.$('canvas.bk-canvas');
    ctx = canvas_el[0].getContext('2d');
    return ctx;
  };

  CanvasView.prototype.prepare_canvas = function(force) {
    var canvas_el, dpr, height, ratio, width;
    if (force == null) {
      force = false;
    }
    width = this.model._width._value;
    height = this.model._height._value;
    dpr = window.devicePixelRatio;
    if (!_.isEqual(this.last_dims, [width, height, dpr]) || force) {
      this.$el.css({
        width: width,
        height: height
      });
      this.pixel_ratio = ratio = get_scale_ratio(this.ctx, this.mget('use_hidpi'));
      canvas_el = this.$('.bk-canvas');
      canvas_el.css({
        width: width,
        height: height
      });
      canvas_el.attr('width', width * ratio);
      canvas_el.attr('height', height * ratio);
      logger.debug("Rendering CanvasView [force=" + force + "] with width: " + width + ", height: " + height + ", ratio: " + ratio);
      this.model.pixel_ratio = this.pixel_ratio;
      return this.last_dims = [width, height, dpr];
    }
  };

  CanvasView.prototype.set_dims = function(dims, trigger) {
    if (trigger == null) {
      trigger = true;
    }
    this.requested_width = dims[0];
    this.requested_height = dims[1];
    this.update_constraints(trigger);
  };

  CanvasView.prototype.update_constraints = function(trigger) {
    var MIN_SIZE, requested_height, requested_width, s;
    if (trigger == null) {
      trigger = true;
    }
    requested_width = this.requested_width;
    requested_height = this.requested_height;
    if ((requested_width == null) || (requested_height == null)) {
      return;
    }
    MIN_SIZE = 50;
    if (requested_width < MIN_SIZE || requested_height < MIN_SIZE) {
      return;
    }
    if (_.isEqual(this.last_requested_dims, [requested_width, requested_height])) {
      return;
    }
    s = this.model.document.solver();
    if (this._width_constraint != null) {
      s.remove_constraint(this._width_constraint);
    }
    this._width_constraint = EQ(this.model._width, -requested_width);
    s.add_constraint(this._width_constraint);
    if (this._height_constraint != null) {
      s.remove_constraint(this._height_constraint);
    }
    this._height_constraint = EQ(this.model._height, -requested_height);
    s.add_constraint(this._height_constraint);
    this.last_requested_dims = [requested_width, requested_height];
    return s.update_variables(trigger);
  };

  return CanvasView;

})(BokehView);

Canvas = (function(superClass) {
  extend(Canvas, superClass);

  function Canvas() {
    return Canvas.__super__.constructor.apply(this, arguments);
  }

  Canvas.prototype.type = 'Canvas';

  Canvas.prototype.default_view = CanvasView;

  Canvas.internal({
    map: [p.Boolean, false],
    initial_width: [p.Number],
    initial_height: [p.Number],
    use_hidpi: [p.Boolean, true],
    pixel_ratio: [p.Number]
  });

  Canvas.prototype.initialize = function(attrs, options) {
    Canvas.__super__.initialize.call(this, attrs, options);
    return this.panel = this;
  };

  Canvas.prototype.vx_to_sx = function(x) {
    return x;
  };

  Canvas.prototype.vy_to_sy = function(y) {
    return this._height._value - (y + 1);
  };

  Canvas.prototype.v_vx_to_sx = function(xx) {
    var i, idx, len, x;
    for (idx = i = 0, len = xx.length; i < len; idx = ++i) {
      x = xx[idx];
      xx[idx] = x;
    }
    return xx;
  };

  Canvas.prototype.v_vy_to_sy = function(yy) {
    var height, i, idx, len, y;
    height = this._height._value;
    for (idx = i = 0, len = yy.length; i < len; idx = ++i) {
      y = yy[idx];
      yy[idx] = height - (y + 1);
    }
    return yy;
  };

  Canvas.prototype.sx_to_vx = function(x) {
    return x;
  };

  Canvas.prototype.sy_to_vy = function(y) {
    return this.get('height') - (y + 1);
  };

  Canvas.prototype.v_sx_to_vx = function(xx) {
    var i, idx, len, x;
    for (idx = i = 0, len = xx.length; i < len; idx = ++i) {
      x = xx[idx];
      xx[idx] = x;
    }
    return xx;
  };

  Canvas.prototype.v_sy_to_vy = function(yy) {
    var height, i, idx, len, y;
    height = this._height._value;
    for (idx = i = 0, len = yy.length; i < len; idx = ++i) {
      y = yy[idx];
      yy[idx] = height - (y + 1);
    }
    return yy;
  };

  Canvas.prototype.get_constraints = function() {
    var constraints;
    constraints = Canvas.__super__.get_constraints.call(this);
    constraints.push(GE(this._top));
    constraints.push(GE(this._bottom));
    constraints.push(GE(this._left));
    constraints.push(GE(this._right));
    constraints.push(GE(this._width));
    constraints.push(GE(this._height));
    constraints.push(EQ(this._width, [-1, this._right]));
    constraints.push(EQ(this._height, [-1, this._top]));
    return constraints;
  };

  return Canvas;

})(LayoutCanvas.Model);

module.exports = {
  Model: Canvas,
  View: CanvasView
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/layout/layout_canvas":"core/layout/layout_canvas","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/util/canvas":"core/util/canvas","./canvas_template":"models/canvas/canvas_template","underscore":"underscore"}],"models/canvas/canvas_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [];
  var __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  };
  var __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  };
  var __safe = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else {
      if (!(typeof value !== 'undefined' && value != null)) value = '';
      var result = new String(value);
      result.ecoSafe = true;
      return result;
    }
  };
  var __escape = function(value) {
    return ('' + value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  };
  (function() {
    (function() {
      if (this.map) {
        __out.push('\n<div class="bk-canvas-map"></div>\n');
      }
    
      __out.push('\n<div class="bk-canvas-events" />\n<div class="bk-canvas-overlays" />\n<canvas class=\'bk-canvas\'></canvas>');
    
    }).call(this);
    
  }).call(__obj);
  return __out.join('');
};
},{}],"models/canvas/cartesian_frame":[function(require,module,exports){
var CartesianFrame, CategoricalMapper, EQ, GE, GridMapper, LayoutCanvas, LinearMapper, LogMapper, Range1d, _, logging, p, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

CategoricalMapper = require("../mappers/categorical_mapper");

GridMapper = require("../mappers/grid_mapper");

LinearMapper = require("../mappers/linear_mapper");

LogMapper = require("../mappers/log_mapper");

Range1d = require("../ranges/range1d");

ref = require("../../core/layout/solver"), EQ = ref.EQ, GE = ref.GE;

LayoutCanvas = require("../../core/layout/layout_canvas");

logging = require("../../core/logging").logging;

p = require("../../core/properties");

CartesianFrame = (function(superClass) {
  extend(CartesianFrame, superClass);

  function CartesianFrame() {
    return CartesianFrame.__super__.constructor.apply(this, arguments);
  }

  CartesianFrame.prototype.type = 'CartesianFrame';

  CartesianFrame.prototype.initialize = function(attrs, options) {
    CartesianFrame.__super__.initialize.call(this, attrs, options);
    this.panel = this;
    this.define_computed_property('x_ranges', function() {
      return this._get_ranges('x');
    }, true);
    this.add_dependencies('x_ranges', this, ['x_range', 'extra_x_ranges']);
    this.define_computed_property('y_ranges', function() {
      return this._get_ranges('y');
    }, true);
    this.add_dependencies('y_ranges', this, ['y_range', 'extra_y_ranges']);
    this.define_computed_property('x_mappers', function() {
      return this._get_mappers('x', this.get('x_ranges'), this.get('h_range'));
    }, true);
    this.add_dependencies('x_ranges', this, ['x_ranges', 'h_range']);
    this.define_computed_property('y_mappers', function() {
      return this._get_mappers('y', this.get('y_ranges'), this.get('v_range'));
    }, true);
    this.add_dependencies('y_ranges', this, ['y_ranges', 'v_range']);
    this.define_computed_property('mapper', function() {
      return new GridMapper.Model({
        domain_mapper: this.get('x_mapper'),
        codomain_mapper: this.get('y_mapper')
      });
    }, true);
    this.add_dependencies('mapper', this, ['x_mapper', 'y_mapper']);
    this._h_range = new Range1d.Model({
      start: this.get('left'),
      end: this.get('left') + this.get('width')
    });
    this.define_computed_property('h_range', (function(_this) {
      return function() {
        _this._h_range.set('start', _this.get('left'));
        _this._h_range.set('end', _this.get('left') + _this.get('width'));
        return _this._h_range;
      };
    })(this), false);
    this.add_dependencies('h_range', this, ['left', 'width']);
    this._v_range = new Range1d.Model({
      start: this.get('bottom'),
      end: this.get('bottom') + this.get('height')
    });
    this.define_computed_property('v_range', (function(_this) {
      return function() {
        _this._v_range.set('start', _this.get('bottom'));
        _this._v_range.set('end', _this.get('bottom') + _this.get('height'));
        return _this._v_range;
      };
    })(this), false);
    this.add_dependencies('v_range', this, ['bottom', 'height']);
    return null;
  };

  CartesianFrame.prototype._doc_attached = function() {
    this.listenTo(this.document.solver(), 'layout_update', this._update_mappers);
    return null;
  };

  CartesianFrame.prototype.contains = function(vx, vy) {
    return vx >= this.get('left') && vx <= this.get('right') && vy >= this.get('bottom') && vy <= this.get('top');
  };

  CartesianFrame.prototype.map_to_screen = function(x, y, canvas, x_name, y_name) {
    var sx, sy, vx, vy;
    if (x_name == null) {
      x_name = 'default';
    }
    if (y_name == null) {
      y_name = 'default';
    }
    vx = this.get('x_mappers')[x_name].v_map_to_target(x);
    sx = canvas.v_vx_to_sx(vx);
    vy = this.get('y_mappers')[y_name].v_map_to_target(y);
    sy = canvas.v_vy_to_sy(vy);
    return [sx, sy];
  };

  CartesianFrame.prototype._get_ranges = function(dim) {
    var extra_ranges, name, range, ranges;
    ranges = {};
    ranges['default'] = this.get(dim + "_range");
    extra_ranges = this.get("extra_" + dim + "_ranges");
    if (extra_ranges != null) {
      for (name in extra_ranges) {
        range = extra_ranges[name];
        ranges[name] = range;
      }
    }
    return ranges;
  };

  CartesianFrame.prototype._get_mappers = function(dim, ranges, frame_range) {
    var mapper_type, mappers, name, range;
    mappers = {};
    for (name in ranges) {
      range = ranges[name];
      if (range.type === "Range1d" || range.type === "DataRange1d") {
        if (this.get(dim + "_mapper_type") === "log") {
          mapper_type = LogMapper.Model;
        } else {
          mapper_type = LinearMapper.Model;
        }
      } else if (range.type === "FactorRange") {
        mapper_type = CategoricalMapper.Model;
      } else {
        logger.warn("unknown range type for range '" + name + "': " + range);
        return null;
      }
      mappers[name] = new mapper_type({
        source_range: range,
        target_range: frame_range
      });
    }
    return mappers;
  };

  CartesianFrame.prototype._update_mappers = function() {
    var mapper, name, ref1, ref2;
    ref1 = this.get('x_mappers');
    for (name in ref1) {
      mapper = ref1[name];
      mapper.set('target_range', this.get('h_range'));
    }
    ref2 = this.get('y_mappers');
    for (name in ref2) {
      mapper = ref2[name];
      mapper.set('target_range', this.get('v_range'));
    }
    return null;
  };

  CartesianFrame.internal({
    extra_x_ranges: [p.Any, {}],
    extra_y_ranges: [p.Any, {}],
    x_range: [p.Instance],
    y_range: [p.Instance],
    x_mapper_type: [p.Any],
    y_mapper_type: [p.Any]
  });

  CartesianFrame.prototype.get_constraints = function() {
    var constraints;
    constraints = [];
    constraints.push(GE(this._top));
    constraints.push(GE(this._bottom));
    constraints.push(GE(this._left));
    constraints.push(GE(this._right));
    constraints.push(GE(this._width));
    constraints.push(GE(this._height));
    constraints.push(EQ(this._left, this._width, [-1, this._right]));
    constraints.push(EQ(this._bottom, this._height, [-1, this._top]));
    return constraints;
  };

  return CartesianFrame;

})(LayoutCanvas.Model);

module.exports = {
  Model: CartesianFrame
};

},{"../../core/layout/layout_canvas":"core/layout/layout_canvas","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../mappers/categorical_mapper":"models/mappers/categorical_mapper","../mappers/grid_mapper":"models/mappers/grid_mapper","../mappers/linear_mapper":"models/mappers/linear_mapper","../mappers/log_mapper":"models/mappers/log_mapper","../ranges/range1d":"models/ranges/range1d","underscore":"underscore"}],"models/formatters/basic_tick_formatter":[function(require,module,exports){
var BasicTickFormatter, TickFormatter, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

TickFormatter = require("./tick_formatter");

p = require("../../core/properties");

BasicTickFormatter = (function(superClass) {
  extend(BasicTickFormatter, superClass);

  function BasicTickFormatter() {
    return BasicTickFormatter.__super__.constructor.apply(this, arguments);
  }

  BasicTickFormatter.prototype.type = 'BasicTickFormatter';

  BasicTickFormatter.define({
    precision: [p.Any, 'auto'],
    use_scientific: [p.Bool, true],
    power_limit_high: [p.Number, 5],
    power_limit_low: [p.Number, -3]
  });

  BasicTickFormatter.prototype.initialize = function(attrs, options) {
    BasicTickFormatter.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('scientific_limit_low', function() {
      return Math.pow(10.0, this.get('power_limit_low'));
    }, true);
    this.add_dependencies('scientific_limit_low', this, ['power_limit_low']);
    this.define_computed_property('scientific_limit_high', function() {
      return Math.pow(10.0, this.get('power_limit_high'));
    }, true);
    this.add_dependencies('scientific_limit_high', this, ['power_limit_high']);
    return this.last_precision = 3;
  };

  BasicTickFormatter.prototype.doFormat = function(ticks) {
    var i, is_ok, j, k, l, labels, len, m, n, need_sci, o, precision, ref, ref1, ref2, ref3, ref4, tick, tick_abs, x, zero_eps;
    if (ticks.length === 0) {
      return [];
    }
    zero_eps = 0;
    if (ticks.length >= 2) {
      zero_eps = Math.abs(ticks[1] - ticks[0]) / 10000;
    }
    need_sci = false;
    if (this.get('use_scientific')) {
      for (j = 0, len = ticks.length; j < len; j++) {
        tick = ticks[j];
        tick_abs = Math.abs(tick);
        if (tick_abs > zero_eps && (tick_abs >= this.get('scientific_limit_high') || tick_abs <= this.get('scientific_limit_low'))) {
          need_sci = true;
          break;
        }
      }
    }
    precision = this.get('precision');
    if ((precision == null) || _.isNumber(precision)) {
      labels = new Array(ticks.length);
      if (need_sci) {
        for (i = k = 0, ref = ticks.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
          labels[i] = ticks[i].toExponential(precision || void 0);
        }
      } else {
        for (i = l = 0, ref1 = ticks.length; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {
          labels[i] = ticks[i].toFixed(precision || void 0).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
        }
      }
      return labels;
    } else if (precision === 'auto') {
      labels = new Array(ticks.length);
      for (x = m = ref2 = this.last_precision; ref2 <= 15 ? m <= 15 : m >= 15; x = ref2 <= 15 ? ++m : --m) {
        is_ok = true;
        if (need_sci) {
          for (i = n = 0, ref3 = ticks.length; 0 <= ref3 ? n < ref3 : n > ref3; i = 0 <= ref3 ? ++n : --n) {
            labels[i] = ticks[i].toExponential(x);
            if (i > 0) {
              if (labels[i] === labels[i - 1]) {
                is_ok = false;
                break;
              }
            }
          }
          if (is_ok) {
            break;
          }
        } else {
          for (i = o = 0, ref4 = ticks.length; 0 <= ref4 ? o < ref4 : o > ref4; i = 0 <= ref4 ? ++o : --o) {
            labels[i] = ticks[i].toFixed(x).replace(/(\.[0-9]*?)0+$/, "$1").replace(/\.$/, "");
            if (i > 0) {
              if (labels[i] === labels[i - 1]) {
                is_ok = false;
                break;
              }
            }
          }
          if (is_ok) {
            break;
          }
        }
        if (is_ok) {
          this.last_precision = x;
          return labels;
        }
      }
    }
    return labels;
  };

  return BasicTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: BasicTickFormatter
};

},{"../../core/properties":"core/properties","./tick_formatter":"models/formatters/tick_formatter","underscore":"underscore"}],"models/formatters/categorical_tick_formatter":[function(require,module,exports){
var CategoricalTickFormatter, TickFormatter,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

TickFormatter = require("../formatters/tick_formatter");

CategoricalTickFormatter = (function(superClass) {
  extend(CategoricalTickFormatter, superClass);

  function CategoricalTickFormatter() {
    return CategoricalTickFormatter.__super__.constructor.apply(this, arguments);
  }

  CategoricalTickFormatter.prototype.type = 'CategoricalTickFormatter';

  CategoricalTickFormatter.prototype.doFormat = function(ticks) {
    return ticks;
  };

  return CategoricalTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: CategoricalTickFormatter
};

},{"../formatters/tick_formatter":"models/formatters/tick_formatter"}],"models/formatters/datetime_tick_formatter":[function(require,module,exports){
var DEFAULT_DATETIME_FORMATS, DatetimeTickFormatter, SPrintf, TickFormatter, _, _array, _strftime, _us, logger, p, tz,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SPrintf = require("sprintf");

tz = require("timezone");

TickFormatter = require("./tick_formatter");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

_us = function(t) {
  return Math.round(((t / 1000) % 1) * 1000000);
};

_array = function(t) {
  return tz(t, "%Y %m %d %H %M %S").split(/\s+/).map(function(e) {
    return parseInt(e, 10);
  });
};

_strftime = function(t, format) {
  var microsecond_replacement_string;
  if (_.isFunction(format)) {
    return format(t);
  } else {
    microsecond_replacement_string = SPrintf.sprintf("$1%06d", _us(t));
    format = format.replace(/((^|[^%])(%%)*)%f/, microsecond_replacement_string);
    if (format.indexOf("%") === -1) {
      return format;
    }
    return tz(t, format);
  }
};

DEFAULT_DATETIME_FORMATS = {
  'microseconds': ['%fus'],
  'milliseconds': ['%3Nms', '%S.%3Ns'],
  'seconds': ['%Ss'],
  'minsec': [':%M:%S'],
  'minutes': [':%M', '%Mm'],
  'hourmin': ['%H:%M'],
  'hours': ['%Hh', '%H:%M'],
  'days': ['%m/%d', '%a%d'],
  'months': ['%m/%Y', '%b%y'],
  'years': ['%Y']
};

DatetimeTickFormatter = (function(superClass) {
  extend(DatetimeTickFormatter, superClass);

  function DatetimeTickFormatter() {
    return DatetimeTickFormatter.__super__.constructor.apply(this, arguments);
  }

  DatetimeTickFormatter.prototype.type = 'DatetimeTickFormatter';

  DatetimeTickFormatter.define({
    formats: [p.Any, DEFAULT_DATETIME_FORMATS]
  });

  DatetimeTickFormatter.prototype.format_order = ['microseconds', 'milliseconds', 'seconds', 'minsec', 'minutes', 'hourmin', 'hours', 'days', 'months', 'years'];

  DatetimeTickFormatter.prototype.strip_leading_zeros = true;

  DatetimeTickFormatter.prototype.initialize = function(attrs, options) {
    DatetimeTickFormatter.__super__.initialize.call(this, attrs, options);
    return this._update_width_formats();
  };

  DatetimeTickFormatter.prototype._update_width_formats = function() {
    var fmt_name, fmt_string, fmt_strings, now, ref, results, sizes, sorted;
    now = tz(new Date());
    this._width_formats = {};
    ref = this.formats;
    results = [];
    for (fmt_name in ref) {
      fmt_strings = ref[fmt_name];
      sizes = (function() {
        var j, len, results1;
        results1 = [];
        for (j = 0, len = fmt_strings.length; j < len; j++) {
          fmt_string = fmt_strings[j];
          results1.push(_strftime(now, fmt_string).length);
        }
        return results1;
      })();
      sorted = _.sortBy(_.zip(sizes, fmt_strings), function(arg) {
        var fmt, size;
        size = arg[0], fmt = arg[1];
        return size;
      });
      results.push(this._width_formats[fmt_name] = _.zip.apply(_, sorted));
    }
    return results;
  };

  DatetimeTickFormatter.prototype._get_resolution_str = function(resolution_secs, span_secs) {
    var adjusted_resolution_secs, str;
    adjusted_resolution_secs = resolution_secs * 1.1;
    if (adjusted_resolution_secs < 1e-3) {
      str = "microseconds";
    } else if (adjusted_resolution_secs < 1.0) {
      str = "milliseconds";
    } else if (adjusted_resolution_secs < 60) {
      if (span_secs >= 60) {
        str = "minsec";
      } else {
        str = "seconds";
      }
    } else if (adjusted_resolution_secs < 3600) {
      if (span_secs >= 3600) {
        str = "hourmin";
      } else {
        str = "minutes";
      }
    } else if (adjusted_resolution_secs < 24 * 3600) {
      str = "hours";
    } else if (adjusted_resolution_secs < 31 * 24 * 3600) {
      str = "days";
    } else if (adjusted_resolution_secs < 365 * 24 * 3600) {
      str = "months";
    } else {
      str = "years";
    }
    return str;
  };

  DatetimeTickFormatter.prototype.doFormat = function(ticks, num_labels, char_width, fill_ratio, ticker) {
    var error, error1, fmt, format, formats, good_formats, hybrid_handled, i, j, k, l, labels, len, len1, next_format, next_ndx, r, ref, ref1, ref2, resol, resol_ndx, s, span, ss, t, time_tuple_ndx_for_resol, tm, widths;
    if (num_labels == null) {
      num_labels = null;
    }
    if (char_width == null) {
      char_width = null;
    }
    if (fill_ratio == null) {
      fill_ratio = 0.3;
    }
    if (ticker == null) {
      ticker = null;
    }
    if (ticks.length === 0) {
      return [];
    }
    span = Math.abs(ticks[ticks.length - 1] - ticks[0]) / 1000.0;
    if (ticker) {
      r = ticker.resolution;
    } else {
      r = span / (ticks.length - 1);
    }
    resol = this._get_resolution_str(r, span);
    ref = this._width_formats[resol], widths = ref[0], formats = ref[1];
    format = formats[0];
    if (char_width) {
      good_formats = [];
      for (i = j = 0, ref1 = widths.length; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
        if (widths[i] * ticks.length < fill_ratio * char_width) {
          good_formats.push(this._width_formats[i]);
        }
      }
      if (good_formats.length > 0) {
        format = _.last(good_formats);
      }
    }
    labels = [];
    resol_ndx = this.format_order.indexOf(resol);
    time_tuple_ndx_for_resol = {};
    ref2 = this.format_order;
    for (k = 0, len = ref2.length; k < len; k++) {
      fmt = ref2[k];
      time_tuple_ndx_for_resol[fmt] = 0;
    }
    time_tuple_ndx_for_resol["seconds"] = 5;
    time_tuple_ndx_for_resol["minsec"] = 4;
    time_tuple_ndx_for_resol["minutes"] = 4;
    time_tuple_ndx_for_resol["hourmin"] = 3;
    time_tuple_ndx_for_resol["hours"] = 3;
    for (l = 0, len1 = ticks.length; l < len1; l++) {
      t = ticks[l];
      try {
        tm = _array(t);
        s = _strftime(t, format);
      } catch (error1) {
        error = error1;
        logger.warn("unable to format tick for timestamp value " + t);
        logger.warn(" - " + error);
        labels.push("ERR");
        continue;
      }
      hybrid_handled = false;
      next_ndx = resol_ndx;
      while (tm[time_tuple_ndx_for_resol[this.format_order[next_ndx]]] === 0) {
        next_ndx += 1;
        if (next_ndx === this.format_order.length) {
          break;
        }
        if ((resol === "minsec" || resol === "hourmin") && !hybrid_handled) {
          if ((resol === "minsec" && tm[4] === 0 && tm[5] !== 0) || (resol === "hourmin" && tm[3] === 0 && tm[4] !== 0)) {
            next_format = this._width_formats[this.format_order[resol_ndx - 1]][1][0];
            s = _strftime(t, next_format);
            break;
          } else {
            hybrid_handled = true;
          }
        }
        next_format = this._width_formats[this.format_order[next_ndx]][1][0];
        s = _strftime(t, next_format);
      }
      if (this.strip_leading_zeros) {
        ss = s.replace(/^0+/g, "");
        if (ss !== s && isNaN(parseInt(ss))) {
          ss = '0' + ss;
        }
        labels.push(ss);
      } else {
        labels.push(s);
      }
    }
    return labels;
  };

  return DatetimeTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: DatetimeTickFormatter
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./tick_formatter":"models/formatters/tick_formatter","sprintf":"sprintf","timezone":"timezone/index","underscore":"underscore"}],"models/formatters/func_tick_formatter":[function(require,module,exports){
var FuncTickFormatter, TickFormatter, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

p = require("../../core/properties");

TickFormatter = require("../formatters/tick_formatter");

FuncTickFormatter = (function(superClass) {
  extend(FuncTickFormatter, superClass);

  function FuncTickFormatter() {
    return FuncTickFormatter.__super__.constructor.apply(this, arguments);
  }

  FuncTickFormatter.prototype.type = 'FuncTickFormatter';

  FuncTickFormatter.define({
    code: [p.String, ''],
    lang: [p.String, 'javascript']
  });

  FuncTickFormatter.prototype.doFormat = function(ticks) {
    var code, coffee, func;
    code = this.get("code");
    code = (function() {
      switch (this.get("lang")) {
        case "javascript":
          return code;
        case "coffeescript":
          coffee = require("coffee-script");
          return coffee.compile(code, {
            bare: true,
            shiftLine: true
          });
      }
    }).call(this);
    func = new Function("tick", "var func = " + code + "return func(tick)");
    return _.map(ticks, func);
  };

  return FuncTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: FuncTickFormatter
};

},{"../../core/properties":"core/properties","../formatters/tick_formatter":"models/formatters/tick_formatter","coffee-script":undefined,"underscore":"underscore"}],"models/formatters/log_tick_formatter":[function(require,module,exports){
var BasicTickFormatter, LogTickFormatter, TickFormatter, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

BasicTickFormatter = require("./basic_tick_formatter");

TickFormatter = require("./tick_formatter");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

LogTickFormatter = (function(superClass) {
  extend(LogTickFormatter, superClass);

  function LogTickFormatter() {
    return LogTickFormatter.__super__.constructor.apply(this, arguments);
  }

  LogTickFormatter.prototype.type = 'LogTickFormatter';

  LogTickFormatter.define({
    ticker: [p.Instance, null]
  });

  LogTickFormatter.prototype.initialize = function(attrs, options) {
    LogTickFormatter.__super__.initialize.call(this, attrs, options);
    this.basic_formatter = new BasicTickFormatter.Model();
    if (this.get('ticker') == null) {
      return logger.warn("LogTickFormatter not configured with a ticker, using default base of 10 (labels will be incorrect if ticker base is not 10)");
    }
  };

  LogTickFormatter.prototype.doFormat = function(ticks) {
    var base, i, j, labels, ref, small_interval;
    if (ticks.length === 0) {
      return [];
    }
    if (this.get('ticker') != null) {
      base = this.get('ticker').get('base');
    } else {
      base = 10;
    }
    small_interval = false;
    labels = new Array(ticks.length);
    for (i = j = 0, ref = ticks.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      labels[i] = base + "^" + (Math.round(Math.log(ticks[i]) / Math.log(base)));
      if ((i > 0) && (labels[i] === labels[i - 1])) {
        small_interval = true;
        break;
      }
    }
    if (small_interval) {
      labels = this.basic_formatter.doFormat(ticks);
    }
    return labels;
  };

  return LogTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: LogTickFormatter
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./basic_tick_formatter":"models/formatters/basic_tick_formatter","./tick_formatter":"models/formatters/tick_formatter","underscore":"underscore"}],"models/formatters/numeral_tick_formatter":[function(require,module,exports){
var Numbro, NumeralTickFormatter, TickFormatter, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Numbro = require("numbro");

TickFormatter = require("./tick_formatter");

p = require("../../core/properties");

NumeralTickFormatter = (function(superClass) {
  extend(NumeralTickFormatter, superClass);

  function NumeralTickFormatter() {
    return NumeralTickFormatter.__super__.constructor.apply(this, arguments);
  }

  NumeralTickFormatter.prototype.type = 'NumeralTickFormatter';

  NumeralTickFormatter.define({
    format: [p.String, '0,0'],
    language: [p.String, 'en'],
    rounding: [p.String, 'round']
  });

  NumeralTickFormatter.prototype.doFormat = function(ticks) {
    var format, labels, language, rounding, tick;
    format = this.get("format");
    language = this.get("language");
    rounding = (function() {
      switch (this.get("rounding")) {
        case "round":
        case "nearest":
          return Math.round;
        case "floor":
        case "rounddown":
          return Math.floor;
        case "ceil":
        case "roundup":
          return Math.ceil;
      }
    }).call(this);
    labels = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = ticks.length; i < len; i++) {
        tick = ticks[i];
        results.push(Numbro.format(tick, format, language, rounding));
      }
      return results;
    })();
    return labels;
  };

  return NumeralTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: NumeralTickFormatter
};

},{"../../core/properties":"core/properties","./tick_formatter":"models/formatters/tick_formatter","numbro":"numbro/numbro","underscore":"underscore"}],"models/formatters/printf_tick_formatter":[function(require,module,exports){
var PrintfTickFormatter, SPrintf, TickFormatter, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SPrintf = require("sprintf");

TickFormatter = require("./tick_formatter");

p = require("../../core/properties");

PrintfTickFormatter = (function(superClass) {
  extend(PrintfTickFormatter, superClass);

  function PrintfTickFormatter() {
    return PrintfTickFormatter.__super__.constructor.apply(this, arguments);
  }

  PrintfTickFormatter.prototype.type = 'PrintfTickFormatter';

  PrintfTickFormatter.define({
    format: [p.String, '%s']
  });

  PrintfTickFormatter.prototype.doFormat = function(ticks) {
    var format, labels, tick;
    format = this.get("format");
    labels = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = ticks.length; i < len; i++) {
        tick = ticks[i];
        results.push(SPrintf.sprintf(format, tick));
      }
      return results;
    })();
    return labels;
  };

  return PrintfTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: PrintfTickFormatter
};

},{"../../core/properties":"core/properties","./tick_formatter":"models/formatters/tick_formatter","sprintf":"sprintf","underscore":"underscore"}],"models/formatters/tick_formatter":[function(require,module,exports){
var Model, TickFormatter, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../../model");

TickFormatter = (function(superClass) {
  extend(TickFormatter, superClass);

  function TickFormatter() {
    return TickFormatter.__super__.constructor.apply(this, arguments);
  }

  TickFormatter.prototype.type = 'TickFormatter';

  TickFormatter.prototype.doFormat = function(ticks) {};

  return TickFormatter;

})(Model);

module.exports = {
  Model: TickFormatter
};

},{"../../model":"model","underscore":"underscore"}],"models/glyphs/annular_wedge":[function(require,module,exports){
var AnnularWedge, AnnularWedgeView, Glyph, _, angle_between, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

angle_between = require("../../core/util/math").angle_between;

AnnularWedgeView = (function(superClass) {
  extend(AnnularWedgeView, superClass);

  function AnnularWedgeView() {
    return AnnularWedgeView.__super__.constructor.apply(this, arguments);
  }

  AnnularWedgeView.prototype._index_data = function() {
    return this._xy_index();
  };

  AnnularWedgeView.prototype._map_data = function() {
    var i, j, ref, results;
    if (this.model.properties.inner_radius.units === "data") {
      this.sinner_radius = this.sdist(this.renderer.xmapper, this._x, this._inner_radius);
    } else {
      this.sinner_radius = this._inner_radius;
    }
    if (this.model.properties.outer_radius.units === "data") {
      this.souter_radius = this.sdist(this.renderer.xmapper, this._x, this._outer_radius);
    } else {
      this.souter_radius = this._outer_radius;
    }
    this._angle = new Float32Array(this._start_angle.length);
    results = [];
    for (i = j = 0, ref = this._start_angle.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      results.push(this._angle[i] = this._end_angle[i] - this._start_angle[i]);
    }
    return results;
  };

  AnnularWedgeView.prototype._render = function(ctx, indices, arg) {
    var _angle, _start_angle, direction, i, j, len, results, sinner_radius, souter_radius, sx, sy;
    sx = arg.sx, sy = arg.sy, _start_angle = arg._start_angle, _angle = arg._angle, sinner_radius = arg.sinner_radius, souter_radius = arg.souter_radius;
    direction = this.model.properties.direction.value();
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + sinner_radius[i] + souter_radius[i] + _start_angle[i] + _angle[i])) {
        continue;
      }
      ctx.translate(sx[i], sy[i]);
      ctx.rotate(_start_angle[i]);
      ctx.moveTo(souter_radius[i], 0);
      ctx.beginPath();
      ctx.arc(0, 0, souter_radius[i], 0, _angle[i], direction);
      ctx.rotate(_angle[i]);
      ctx.lineTo(sinner_radius[i], 0);
      ctx.arc(0, 0, sinner_radius[i], 0, -_angle[i], !direction);
      ctx.closePath();
      ctx.rotate(-_angle[i] - _start_angle[i]);
      ctx.translate(-sx[i], -sy[i]);
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  AnnularWedgeView.prototype._hit_point = function(geometry) {
    var angle, bbox, candidates, direction, dist, hits, i, ir2, j, k, len, len1, or2, pt, ref, ref1, ref2, ref3, ref4, result, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx, true);
    y = this.renderer.ymapper.map_from_target(vy, true);
    if (this.model.properties.outer_radius.units === "data") {
      x0 = x - this.max_outer_radius;
      x1 = x + this.max_outer_radius;
      y0 = y - this.max_outer_radius;
      y1 = y + this.max_outer_radius;
    } else {
      vx0 = vx - this.max_outer_radius;
      vx1 = vx + this.max_outer_radius;
      ref1 = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref1[0], x1 = ref1[1];
      vy0 = vy - this.max_outer_radius;
      vy1 = vy + this.max_outer_radius;
      ref2 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref2[0], y1 = ref2[1];
    }
    candidates = [];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    ref3 = (function() {
      var k, len, ref3, results;
      ref3 = this.index.search(bbox);
      results = [];
      for (k = 0, len = ref3.length; k < len; k++) {
        pt = ref3[k];
        results.push(pt.i);
      }
      return results;
    }).call(this);
    for (j = 0, len = ref3.length; j < len; j++) {
      i = ref3[j];
      or2 = Math.pow(this.souter_radius[i], 2);
      ir2 = Math.pow(this.sinner_radius[i], 2);
      sx0 = this.renderer.xmapper.map_to_target(x, true);
      sx1 = this.renderer.xmapper.map_to_target(this._x[i], true);
      sy0 = this.renderer.ymapper.map_to_target(y, true);
      sy1 = this.renderer.ymapper.map_to_target(this._y[i], true);
      dist = Math.pow(sx0 - sx1, 2) + Math.pow(sy0 - sy1, 2);
      if (dist <= or2 && dist >= ir2) {
        candidates.push([i, dist]);
      }
    }
    direction = this.model.properties.direction.value();
    hits = [];
    for (k = 0, len1 = candidates.length; k < len1; k++) {
      ref4 = candidates[k], i = ref4[0], dist = ref4[1];
      sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
      sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
      angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
      if (angle_between(-angle, -this._start_angle[i], -this._end_angle[i], direction)) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  AnnularWedgeView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  AnnularWedgeView.prototype._scxy = function(i) {
    var a, r;
    r = (this.sinner_radius[i] + this.souter_radius[i]) / 2;
    a = (this._start_angle[i] + this._end_angle[i]) / 2;
    return {
      x: this.sx[i] + r * Math.cos(a),
      y: this.sy[i] + r * Math.sin(a)
    };
  };

  AnnularWedgeView.prototype.scx = function(i) {
    return this._scxy(i).x;
  };

  AnnularWedgeView.prototype.scy = function(i) {
    return this._scxy(i).y;
  };

  return AnnularWedgeView;

})(Glyph.View);

AnnularWedge = (function(superClass) {
  extend(AnnularWedge, superClass);

  function AnnularWedge() {
    return AnnularWedge.__super__.constructor.apply(this, arguments);
  }

  AnnularWedge.prototype.default_view = AnnularWedgeView;

  AnnularWedge.prototype.type = 'AnnularWedge';

  AnnularWedge.coords([['x', 'y']]);

  AnnularWedge.mixins(['line', 'fill']);

  AnnularWedge.define({
    direction: [p.Direction, 'anticlock'],
    inner_radius: [p.DistanceSpec],
    outer_radius: [p.DistanceSpec],
    start_angle: [p.AngleSpec],
    end_angle: [p.AngleSpec]
  });

  return AnnularWedge;

})(Glyph.Model);

module.exports = {
  Model: AnnularWedge,
  View: AnnularWedgeView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","../../core/util/math":"core/util/math","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/annulus":[function(require,module,exports){
var Annulus, AnnulusView, Glyph, _, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

AnnulusView = (function(superClass) {
  extend(AnnulusView, superClass);

  function AnnulusView() {
    return AnnulusView.__super__.constructor.apply(this, arguments);
  }

  AnnulusView.prototype._index_data = function() {
    return this._xy_index();
  };

  AnnulusView.prototype._map_data = function() {
    if (this.model.properties.inner_radius.units === "data") {
      this.sinner_radius = this.sdist(this.renderer.xmapper, this._x, this._inner_radius);
    } else {
      this.sinner_radius = this._inner_radius;
    }
    if (this.model.properties.outer_radius.units === "data") {
      return this.souter_radius = this.sdist(this.renderer.xmapper, this._x, this._outer_radius);
    } else {
      return this.souter_radius = this._outer_radius;
    }
  };

  AnnulusView.prototype._render = function(ctx, indices, arg) {
    var clockwise, i, isie, j, k, len, len1, ref, results, sinner_radius, souter_radius, sx, sy;
    sx = arg.sx, sy = arg.sy, sinner_radius = arg.sinner_radius, souter_radius = arg.souter_radius;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + sinner_radius[i] + souter_radius[i])) {
        continue;
      }
      isie = navigator.userAgent.indexOf('MSIE') >= 0 || navigator.userAgent.indexOf('Trident') > 0 || navigator.userAgent.indexOf('Edge') > 0;
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.beginPath();
        if (isie) {
          ref = [false, true];
          for (k = 0, len1 = ref.length; k < len1; k++) {
            clockwise = ref[k];
            ctx.arc(sx[i], sy[i], sinner_radius[i], 0, Math.PI, clockwise);
            ctx.arc(sx[i], sy[i], souter_radius[i], Math.PI, 0, !clockwise);
          }
        } else {
          ctx.arc(sx[i], sy[i], sinner_radius[i], 0, 2 * Math.PI, true);
          ctx.arc(sx[i], sy[i], souter_radius[i], 2 * Math.PI, 0, false);
        }
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.beginPath();
        ctx.arc(sx[i], sy[i], sinner_radius[i], 0, 2 * Math.PI);
        ctx.moveTo(sx[i] + souter_radius[i], sy[i]);
        ctx.arc(sx[i], sy[i], souter_radius[i], 0, 2 * Math.PI);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  AnnulusView.prototype._hit_point = function(geometry) {
    var bbox, dist, hits, i, ir2, j, len, or2, pt, ref, ref1, result, sx0, sx1, sy0, sy1, vx, vy, x, x0, x1, y, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx, true);
    x0 = x - this.max_radius;
    x1 = x + this.max_radius;
    y = this.renderer.ymapper.map_from_target(vy, true);
    y0 = y - this.max_radius;
    y1 = y + this.max_radius;
    hits = [];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    ref1 = (function() {
      var k, len, ref1, results;
      ref1 = this.index.search(bbox);
      results = [];
      for (k = 0, len = ref1.length; k < len; k++) {
        pt = ref1[k];
        results.push(pt.i);
      }
      return results;
    }).call(this);
    for (j = 0, len = ref1.length; j < len; j++) {
      i = ref1[j];
      or2 = Math.pow(this.souter_radius[i], 2);
      ir2 = Math.pow(this.sinner_radius[i], 2);
      sx0 = this.renderer.xmapper.map_to_target(x);
      sx1 = this.renderer.xmapper.map_to_target(this._x[i]);
      sy0 = this.renderer.ymapper.map_to_target(y);
      sy1 = this.renderer.ymapper.map_to_target(this._y[i]);
      dist = Math.pow(sx0 - sx1, 2) + Math.pow(sy0 - sy1, 2);
      if (dist <= or2 && dist >= ir2) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  AnnulusView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var data, indices, r, ref, reference_point, sinner_radius, souter_radius, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
    sinner_radius = {};
    sinner_radius[reference_point] = r * 0.4;
    souter_radius = {};
    souter_radius[reference_point] = r * 0.8;
    data = {
      sx: sx,
      sy: sy,
      sinner_radius: sinner_radius,
      souter_radius: souter_radius
    };
    return this._render(ctx, indices, data);
  };

  return AnnulusView;

})(Glyph.View);

Annulus = (function(superClass) {
  extend(Annulus, superClass);

  function Annulus() {
    return Annulus.__super__.constructor.apply(this, arguments);
  }

  Annulus.prototype.default_view = AnnulusView;

  Annulus.prototype.type = 'Annulus';

  Annulus.coords([['x', 'y']]);

  Annulus.mixins(['line', 'fill']);

  Annulus.define({
    inner_radius: [p.DistanceSpec],
    outer_radius: [p.DistanceSpec]
  });

  return Annulus;

})(Glyph.Model);

module.exports = {
  Model: Annulus,
  View: AnnulusView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/arc":[function(require,module,exports){
var Arc, ArcView, Glyph, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

p = require("../../core/properties");

ArcView = (function(superClass) {
  extend(ArcView, superClass);

  function ArcView() {
    return ArcView.__super__.constructor.apply(this, arguments);
  }

  ArcView.prototype._index_data = function() {
    return this._xy_index();
  };

  ArcView.prototype._map_data = function() {
    if (this.model.properties.radius.units === "data") {
      return this.sradius = this.sdist(this.renderer.xmapper, this._x, this._radius);
    } else {
      return this.sradius = this._radius;
    }
  };

  ArcView.prototype._render = function(ctx, indices, arg) {
    var _end_angle, _start_angle, direction, i, j, len, results, sradius, sx, sy;
    sx = arg.sx, sy = arg.sy, sradius = arg.sradius, _start_angle = arg._start_angle, _end_angle = arg._end_angle;
    if (this.visuals.line.doit) {
      direction = this.model.properties.direction.value();
      results = [];
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (isNaN(sx[i] + sy[i] + sradius[i] + _start_angle[i] + _end_angle[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.arc(sx[i], sy[i], sradius[i], _start_angle[i], _end_angle[i], direction);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  ArcView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return ArcView;

})(Glyph.View);

Arc = (function(superClass) {
  extend(Arc, superClass);

  function Arc() {
    return Arc.__super__.constructor.apply(this, arguments);
  }

  Arc.prototype.default_view = ArcView;

  Arc.prototype.type = 'Arc';

  Arc.coords([['x', 'y']]);

  Arc.mixins(['line']);

  Arc.define({
    direction: [p.Direction, 'anticlock'],
    radius: [p.DistanceSpec],
    start_angle: [p.AngleSpec],
    end_angle: [p.AngleSpec]
  });

  return Arc;

})(Glyph.Model);

module.exports = {
  Model: Arc,
  View: ArcView
};

},{"../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/bezier":[function(require,module,exports){
var Bezier, BezierView, Glyph, _, _cbb, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

_cbb = function(x0, y0, x1, y1, x2, y2, x3, y3) {
  var a, b, b2ac, bounds, c, i, j, jlen, k, mt, sqrtb2ac, t, t1, t2, tvalues, x, y;
  tvalues = [];
  bounds = [[], []];
  for (i = k = 0; k <= 2; i = ++k) {
    if (i === 0) {
      b = 6 * x0 - 12 * x1 + 6 * x2;
      a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3;
      c = 3 * x1 - 3 * x0;
    } else {
      b = 6 * y0 - 12 * y1 + 6 * y2;
      a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3;
      c = 3 * y1 - 3 * y0;
    }
    if (Math.abs(a) < 1e-12) {
      if (Math.abs(b) < 1e-12) {
        continue;
      }
      t = -c / b;
      if (0 < t && t < 1) {
        tvalues.push(t);
      }
      continue;
    }
    b2ac = b * b - 4 * c * a;
    sqrtb2ac = Math.sqrt(b2ac);
    if (b2ac < 0) {
      continue;
    }
    t1 = (-b + sqrtb2ac) / (2 * a);
    if (0 < t1 && t1 < 1) {
      tvalues.push(t1);
    }
    t2 = (-b - sqrtb2ac) / (2 * a);
    if (0 < t2 && t2 < 1) {
      tvalues.push(t2);
    }
  }
  j = tvalues.length;
  jlen = j;
  while (j--) {
    t = tvalues[j];
    mt = 1 - t;
    x = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3);
    bounds[0][j] = x;
    y = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3);
    bounds[1][j] = y;
  }
  bounds[0][jlen] = x0;
  bounds[1][jlen] = y0;
  bounds[0][jlen + 1] = x3;
  bounds[1][jlen + 1] = y3;
  return [Math.min.apply(null, bounds[0]), Math.max.apply(null, bounds[1]), Math.max.apply(null, bounds[0]), Math.min.apply(null, bounds[1])];
};

BezierView = (function(superClass) {
  extend(BezierView, superClass);

  function BezierView() {
    return BezierView.__super__.constructor.apply(this, arguments);
  }

  BezierView.prototype._index_data = function() {
    var i, index, k, pts, ref, ref1, x0, x1, y0, y1;
    index = rbush();
    pts = [];
    for (i = k = 0, ref = this._x0.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      if (isNaN(this._x0[i] + this._x1[i] + this._y0[i] + this._y1[i] + this._cx0[i] + this._cy0[i] + this._cx1[i] + this._cy1[i])) {
        continue;
      }
      ref1 = _cbb(this._x0[i], this._y0[i], this._x1[i], this._y1[i], this._cx0[i], this._cy0[i], this._cx1[i], this._cy1[i]), x0 = ref1[0], y0 = ref1[1], x1 = ref1[2], y1 = ref1[3];
      pts.push({
        minX: x0,
        minY: y0,
        maxX: x1,
        maxY: y1,
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  BezierView.prototype._render = function(ctx, indices, arg) {
    var i, k, len, results, scx, scx0, scx1, scy0, scy1, sx0, sx1, sy0, sy1;
    sx0 = arg.sx0, sy0 = arg.sy0, sx1 = arg.sx1, sy1 = arg.sy1, scx = arg.scx, scx0 = arg.scx0, scy0 = arg.scy0, scx1 = arg.scx1, scy1 = arg.scy1;
    if (this.visuals.line.doit) {
      results = [];
      for (k = 0, len = indices.length; k < len; k++) {
        i = indices[k];
        if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i] + scx0[i] + scy0[i] + scx1[i] + scy1[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.moveTo(sx0[i], sy0[i]);
        ctx.bezierCurveTo(scx0[i], scy0[i], scx1[i], scy1[i], sx1[i], sy1[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  BezierView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return BezierView;

})(Glyph.View);

Bezier = (function(superClass) {
  extend(Bezier, superClass);

  function Bezier() {
    return Bezier.__super__.constructor.apply(this, arguments);
  }

  Bezier.prototype.default_view = BezierView;

  Bezier.prototype.type = 'Bezier';

  Bezier.coords([['x0', 'y0'], ['x1', 'y1'], ['cx0', 'cy0'], ['cx1', 'cy1']]);

  Bezier.mixins(['line']);

  return Bezier;

})(Glyph.Model);

module.exports = {
  Model: Bezier,
  View: BezierView
};

},{"./glyph":"models/glyphs/glyph","rbush":"rbush","underscore":"underscore"}],"models/glyphs/circle":[function(require,module,exports){
var Circle, CircleView, Glyph, _, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

CircleView = (function(superClass) {
  extend(CircleView, superClass);

  function CircleView() {
    return CircleView.__super__.constructor.apply(this, arguments);
  }

  CircleView.prototype._index_data = function() {
    return this._xy_index();
  };

  CircleView.prototype._map_data = function() {
    var rd, s;
    if (this._radius != null) {
      if (this.model.properties.radius.spec.units === "data") {
        rd = this.model.properties.radius_dimension.spec.value;
        return this.sradius = this.sdist(this.renderer[rd + "mapper"], this["_" + rd], this._radius);
      } else {
        this.sradius = this._radius;
        return this.max_size = 2 * this.max_radius;
      }
    } else {
      return this.sradius = (function() {
        var j, len, ref, results;
        ref = this._size;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          s = ref[j];
          results.push(s / 2);
        }
        return results;
      }).call(this);
    }
  };

  CircleView.prototype._mask_data = function(all_indices) {
    var bbox, hr, ref, ref1, ref2, ref3, sx0, sx1, sy0, sy1, vr, x, x0, x1, y0, y1;
    hr = this.renderer.plot_view.frame.get('h_range');
    vr = this.renderer.plot_view.frame.get('v_range');
    if ((this._radius != null) && this.model.properties.radius.units === "data") {
      sx0 = hr.get('start');
      sx1 = hr.get('end');
      ref = this.renderer.xmapper.v_map_from_target([sx0, sx1], true), x0 = ref[0], x1 = ref[1];
      x0 -= this.max_radius;
      x1 += this.max_radius;
      sy0 = vr.get('start');
      sy1 = vr.get('end');
      ref1 = this.renderer.ymapper.v_map_from_target([sy0, sy1], true), y0 = ref1[0], y1 = ref1[1];
      y0 -= this.max_radius;
      y1 += this.max_radius;
    } else {
      sx0 = hr.get('start') - this.max_size;
      sx1 = hr.get('end') + this.max_size;
      ref2 = this.renderer.xmapper.v_map_from_target([sx0, sx1], true), x0 = ref2[0], x1 = ref2[1];
      sy0 = vr.get('start') - this.max_size;
      sy1 = vr.get('end') + this.max_size;
      ref3 = this.renderer.ymapper.v_map_from_target([sy0, sy1], true), y0 = ref3[0], y1 = ref3[1];
    }
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    return (function() {
      var j, len, ref4, results;
      ref4 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref4.length; j < len; j++) {
        x = ref4[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
  };

  CircleView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sradius, sx, sy;
    sx = arg.sx, sy = arg.sy, sradius = arg.sradius;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + sradius[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.arc(sx[i], sy[i], sradius[i], 0, 2 * Math.PI, false);
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  CircleView.prototype._hit_point = function(geometry) {
    var bbox, candidates, dist, hits, i, j, k, len, len1, pt, r2, ref, ref1, ref2, ref3, ref4, result, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx, true);
    y = this.renderer.ymapper.map_from_target(vy, true);
    if ((this._radius != null) && this.model.properties.radius.units === "data") {
      x0 = x - this.max_radius;
      x1 = x + this.max_radius;
      y0 = y - this.max_radius;
      y1 = y + this.max_radius;
    } else {
      vx0 = vx - this.max_size;
      vx1 = vx + this.max_size;
      ref1 = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref1[0], x1 = ref1[1];
      ref2 = [Math.min(x0, x1), Math.max(x0, x1)], x0 = ref2[0], x1 = ref2[1];
      vy0 = vy - this.max_size;
      vy1 = vy + this.max_size;
      ref3 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref3[0], y1 = ref3[1];
      ref4 = [Math.min(y0, y1), Math.max(y0, y1)], y0 = ref4[0], y1 = ref4[1];
    }
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    candidates = (function() {
      var j, len, ref5, results;
      ref5 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref5.length; j < len; j++) {
        pt = ref5[j];
        results.push(pt.i);
      }
      return results;
    }).call(this);
    hits = [];
    if ((this._radius != null) && this.model.properties.radius.units === "data") {
      for (j = 0, len = candidates.length; j < len; j++) {
        i = candidates[j];
        r2 = Math.pow(this.sradius[i], 2);
        sx0 = this.renderer.xmapper.map_to_target(x, true);
        sx1 = this.renderer.xmapper.map_to_target(this._x[i], true);
        sy0 = this.renderer.ymapper.map_to_target(y, true);
        sy1 = this.renderer.ymapper.map_to_target(this._y[i], true);
        dist = Math.pow(sx0 - sx1, 2) + Math.pow(sy0 - sy1, 2);
        if (dist <= r2) {
          hits.push([i, dist]);
        }
      }
    } else {
      sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
      sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
      for (k = 0, len1 = candidates.length; k < len1; k++) {
        i = candidates[k];
        r2 = Math.pow(this.sradius[i], 2);
        dist = Math.pow(this.sx[i] - sx, 2) + Math.pow(this.sy[i] - sy, 2);
        if (dist <= r2) {
          hits.push([i, dist]);
        }
      }
    }
    hits = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  CircleView.prototype._hit_span = function(geometry) {
    var bbox, hits, maxX, maxY, minX, minY, ms, ref, ref1, ref2, ref3, ref4, ref5, result, vx, vx0, vx1, vy, vy0, vy1, x0, x1, xx, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    ref1 = this.bounds(), minX = ref1.minX, minY = ref1.minY, maxX = ref1.maxX, maxY = ref1.maxY;
    result = hittest.create_hit_test_result();
    if (geometry.direction === 'h') {
      y0 = minY;
      y1 = maxY;
      if ((this._radius != null) && this.model.properties.radius.units === "data") {
        vx0 = vx - this.max_radius;
        vx1 = vx + this.max_radius;
        ref2 = this.renderer.xmapper.v_map_from_target([vx0, vx1]), x0 = ref2[0], x1 = ref2[1];
      } else {
        ms = this.max_size / 2;
        vx0 = vx - ms;
        vx1 = vx + ms;
        ref3 = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref3[0], x1 = ref3[1];
      }
    } else {
      x0 = minX;
      x1 = maxX;
      if ((this._radius != null) && this.model.properties.radius.units === "data") {
        vy0 = vy - this.max_radius;
        vy1 = vy + this.max_radius;
        ref4 = this.renderer.ymapper.v_map_from_target([vy0, vy1]), y0 = ref4[0], y1 = ref4[1];
      } else {
        ms = this.max_size / 2;
        vy0 = vy - ms;
        vy1 = vy + ms;
        ref5 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref5[0], y1 = ref5[1];
      }
    }
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    hits = (function() {
      var j, len, ref6, results;
      ref6 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref6.length; j < len; j++) {
        xx = ref6[j];
        results.push(xx.i);
      }
      return results;
    }).call(this);
    result['1d'].indices = hits;
    return result;
  };

  CircleView.prototype._hit_rect = function(geometry) {
    var bbox, ref, ref1, result, x, x0, x1, y0, y1;
    ref = this.renderer.xmapper.v_map_from_target([geometry.vx0, geometry.vx1], true), x0 = ref[0], x1 = ref[1];
    ref1 = this.renderer.ymapper.v_map_from_target([geometry.vy0, geometry.vy1], true), y0 = ref1[0], y1 = ref1[1];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    result = hittest.create_hit_test_result();
    result['1d'].indices = (function() {
      var j, len, ref2, results;
      ref2 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
    return result;
  };

  CircleView.prototype._hit_poly = function(geometry) {
    var candidates, hits, i, idx, j, k, ref, ref1, ref2, result, results, sx, sy, vx, vy;
    ref = [_.clone(geometry.vx), _.clone(geometry.vy)], vx = ref[0], vy = ref[1];
    sx = this.renderer.plot_view.canvas.v_vx_to_sx(vx);
    sy = this.renderer.plot_view.canvas.v_vy_to_sy(vy);
    candidates = (function() {
      results = [];
      for (var j = 0, ref1 = this.sx.length; 0 <= ref1 ? j < ref1 : j > ref1; 0 <= ref1 ? j++ : j--){ results.push(j); }
      return results;
    }).apply(this);
    hits = [];
    for (i = k = 0, ref2 = candidates.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) {
      idx = candidates[i];
      if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
        hits.push(idx);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  CircleView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var data, indices, ref, reference_point, sradius, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    sradius = {};
    sradius[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.2;
    data = {
      sx: sx,
      sy: sy,
      sradius: sradius
    };
    return this._render(ctx, indices, data);
  };

  return CircleView;

})(Glyph.View);

Circle = (function(superClass) {
  extend(Circle, superClass);

  function Circle() {
    return Circle.__super__.constructor.apply(this, arguments);
  }

  Circle.prototype.default_view = CircleView;

  Circle.prototype.type = 'Circle';

  Circle.coords([['x', 'y']]);

  Circle.mixins(['line', 'fill']);

  Circle.define({
    angle: [p.AngleSpec, 0],
    size: [
      p.DistanceSpec, {
        units: "screen",
        value: 4
      }
    ],
    radius: [p.DistanceSpec, null],
    radius_dimension: [p.String, 'x']
  });

  Circle.prototype.initialize = function(attrs, options) {
    Circle.__super__.initialize.call(this, attrs, options);
    return this.properties.radius.optional = true;
  };

  return Circle;

})(Glyph.Model);

module.exports = {
  Model: Circle,
  View: CircleView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/ellipse":[function(require,module,exports){
var Ellipse, EllipseView, Glyph, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

p = require("../../core/properties");

EllipseView = (function(superClass) {
  extend(EllipseView, superClass);

  function EllipseView() {
    return EllipseView.__super__.constructor.apply(this, arguments);
  }

  EllipseView.prototype._set_data = function() {
    this.max_w2 = 0;
    if (this.model.properties.width.units === "data") {
      this.max_w2 = this.max_width / 2;
    }
    this.max_h2 = 0;
    if (this.model.properties.height.units === "data") {
      return this.max_h2 = this.max_height / 2;
    }
  };

  EllipseView.prototype._index_data = function() {
    return this._xy_index();
  };

  EllipseView.prototype._map_data = function() {
    if (this.model.properties.width.units === "data") {
      this.sw = this.sdist(this.renderer.xmapper, this._x, this._width, 'center');
    } else {
      this.sw = this._width;
    }
    if (this.model.properties.height.units === "data") {
      return this.sh = this.sdist(this.renderer.ymapper, this._y, this._height, 'center');
    } else {
      return this.sh = this._height;
    }
  };

  EllipseView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sh, sw, sx, sy;
    sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + sw[i] + sh[i] + this._angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.ellipse(sx[i], sy[i], sw[i] / 2.0, sh[i] / 2.0, this._angle[i], 0, 2 * Math.PI);
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  EllipseView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var d, data, indices, ref, reference_point, scale, sh, sw, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    scale = this.sw[reference_point] / this.sh[reference_point];
    d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
    sw = {};
    sh = {};
    if (scale > 1) {
      sw[reference_point] = d;
      sh[reference_point] = d / scale;
    } else {
      sw[reference_point] = d * scale;
      sh[reference_point] = d;
    }
    data = {
      sx: sx,
      sy: sy,
      sw: sw,
      sh: sh
    };
    return this._render(ctx, indices, data);
  };

  EllipseView.prototype._bounds = function(bds) {
    return this.max_wh2_bounds(bds);
  };

  return EllipseView;

})(Glyph.View);

Ellipse = (function(superClass) {
  extend(Ellipse, superClass);

  function Ellipse() {
    return Ellipse.__super__.constructor.apply(this, arguments);
  }

  Ellipse.prototype.default_view = EllipseView;

  Ellipse.prototype.type = 'Ellipse';

  Ellipse.coords([['x', 'y']]);

  Ellipse.mixins(['line', 'fill']);

  Ellipse.define({
    angle: [p.AngleSpec, 0.0],
    width: [p.DistanceSpec],
    height: [p.DistanceSpec]
  });

  return Ellipse;

})(Glyph.Model);

module.exports = {
  Model: Ellipse,
  View: EllipseView
};

},{"../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/gear":[function(require,module,exports){
var Bezier, Gear, GearUtils, GearView, Glyph, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

GearUtils = require("gear_utils");

p = require("../../core/properties");

Bezier = require("../../util/bezier");

GearView = (function(superClass) {
  extend(GearView, superClass);

  function GearView() {
    return GearView.__super__.constructor.apply(this, arguments);
  }

  GearView.prototype._index_data = function() {
    return this._xy_index();
  };

  GearView.prototype._map_data = function() {
    return this.smodule = this.sdist(this.renderer.xmapper, this._x, this._module, 'edge');
  };

  GearView.prototype._render = function(ctx, indices, arg) {
    var M, _angle, _internal, _pressure_angle, _shaft_size, _teeth, fn, i, j, k, l, len, pitch_radius, ref, ref1, rim_radius, rot, seq, seq0, shaft_radius, smodule, sx, sy, x, y;
    sx = arg.sx, sy = arg.sy, smodule = arg.smodule, _angle = arg._angle, _teeth = arg._teeth, _pressure_angle = arg._pressure_angle, _shaft_size = arg._shaft_size, _internal = arg._internal;
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      if (isNaN(sx[i] + sy[i] + _angle[i] + smodule[i] + _teeth[i] + _pressure_angle[i] + _shaft_size[i] + _internal[i])) {
        continue;
      }
      pitch_radius = smodule[i] * _teeth[i] / 2;
      if (_internal[i]) {
        fn = GearUtils.create_internal_gear_tooth;
      } else {
        fn = GearUtils.create_gear_tooth;
      }
      seq0 = fn(smodule[i], _teeth[i], _pressure_angle[i]);
      ref = seq0.slice(0, 3), M = ref[0], x = ref[1], y = ref[2];
      seq = seq0.slice(3);
      ctx.save();
      ctx.translate(sx[i], sy[i]);
      ctx.rotate(_angle[i]);
      ctx.beginPath();
      rot = 2 * Math.PI / _teeth[i];
      ctx.moveTo(x, y);
      for (j = l = 0, ref1 = _teeth[i]; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        this._render_seq(ctx, seq);
        ctx.rotate(rot);
      }
      ctx.closePath();
      if (_internal[i]) {
        rim_radius = pitch_radius + 2.75 * smodule[i];
        ctx.moveTo(rim_radius, 0);
        ctx.arc(0, 0, rim_radius, 0, 2 * Math.PI, true);
      } else if (_shaft_size[i] > 0) {
        shaft_radius = pitch_radius * _shaft_size[i];
        ctx.moveTo(shaft_radius, 0);
        ctx.arc(0, 0, shaft_radius, 0, 2 * Math.PI, true);
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      ctx.restore();
    }
  };

  GearView.prototype._render_seq = function(ctx, seq) {
    var c, cx0, cx1, cy0, cy1, i, k, large_arc, len, px, py, ref, ref1, ref10, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, rx, ry, segments, sweep, x, x_rotation, y;
    i = 0;
    while (i < seq.length) {
      if (_.isString(seq[i])) {
        c = seq[i];
        i += 1;
      }
      switch (c) {
        case "M":
          ref = seq.slice(i, i + 2), x = ref[0], y = ref[1];
          ctx.moveTo(x, y);
          ref1 = [x, y], px = ref1[0], py = ref1[1];
          i += 2;
          break;
        case "L":
          ref2 = seq.slice(i, i + 2), x = ref2[0], y = ref2[1];
          ctx.lineTo(x, y);
          ref3 = [x, y], px = ref3[0], py = ref3[1];
          i += 2;
          break;
        case "C":
          ref4 = seq.slice(i, i + 6), cx0 = ref4[0], cy0 = ref4[1], cx1 = ref4[2], cy1 = ref4[3], x = ref4[4], y = ref4[5];
          ctx.bezierCurveTo(cx0, cy0, cx1, cy1, x, y);
          ref5 = [x, y], px = ref5[0], py = ref5[1];
          i += 6;
          break;
        case "Q":
          ref6 = seq.slice(i, i + 4), cx0 = ref6[0], cy0 = ref6[1], x = ref6[2], y = ref6[3];
          ctx.quadraticCurveTo(cx0, cy0, x, y);
          ref7 = [x, y], px = ref7[0], py = ref7[1];
          i += 4;
          break;
        case "A":
          ref8 = seq.slice(i, i + 7), rx = ref8[0], ry = ref8[1], x_rotation = ref8[2], large_arc = ref8[3], sweep = ref8[4], x = ref8[5], y = ref8[6];
          segments = Bezier.arc_to_bezier(px, py, rx, ry, -x_rotation, large_arc, 1 - sweep, x, y);
          for (k = 0, len = segments.length; k < len; k++) {
            ref9 = segments[k], cx0 = ref9[0], cy0 = ref9[1], cx1 = ref9[2], cy1 = ref9[3], x = ref9[4], y = ref9[5];
            ctx.bezierCurveTo(cx0, cy0, cx1, cy1, x, y);
          }
          ref10 = [x, y], px = ref10[0], py = ref10[1];
          i += 7;
          break;
        default:
          throw new Error("unexpected command: " + c);
      }
    }
  };

  GearView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return GearView;

})(Glyph.View);

Gear = (function(superClass) {
  extend(Gear, superClass);

  function Gear() {
    return Gear.__super__.constructor.apply(this, arguments);
  }

  Gear.prototype.default_view = GearView;

  Gear.prototype.type = 'Gear';

  Gear.coords([['x', 'y']]);

  Gear.mixins(['line', 'fill']);

  Gear.define({
    angle: [p.AngleSpec, 0],
    module: [p.NumberSpec, null],
    pressure_angle: [p.NumberSpec, 20],
    shaft_size: [p.NumberSpec, 0.3],
    teeth: [p.NumberSpec, null],
    internal: [p.NumberSpec, false]
  });

  return Gear;

})(Glyph.Model);

module.exports = {
  Model: Gear,
  View: GearView
};

},{"../../core/properties":"core/properties","../../util/bezier":"util/bezier","./glyph":"models/glyphs/glyph","gear_utils":"gear_utils","underscore":"underscore"}],"models/glyphs/glyph":[function(require,module,exports){
var CategoricalMapper, Glyph, GlyphView, Model, Renderer, _, bbox, bokehgl, p, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

CategoricalMapper = require("../mappers/categorical_mapper");

Renderer = require("../renderers/renderer");

p = require("../../core/properties");

bbox = require("../../core/util/bbox");

Model = require("../../model");

bokehgl = require("./webgl/main");

GlyphView = (function(superClass) {
  extend(GlyphView, superClass);

  function GlyphView() {
    return GlyphView.__super__.constructor.apply(this, arguments);
  }

  GlyphView.prototype.initialize = function(options) {
    var Cls, ctx, ref;
    GlyphView.__super__.initialize.call(this, options);
    this.renderer = options.renderer;
    if (((ref = this.renderer) != null ? ref.plot_view : void 0) != null) {
      ctx = this.renderer.plot_view.canvas_view.ctx;
      if (ctx.glcanvas != null) {
        Cls = bokehgl[this.model.type + 'GLGlyph'];
        if (Cls) {
          return this.glglyph = new Cls(ctx.glcanvas.gl, this);
        }
      }
    }
  };

  GlyphView.prototype.render = function(ctx, indices, data) {
    if (this.mget("visible")) {
      ctx.beginPath();
      if (this.glglyph != null) {
        if (this._render_gl(ctx, indices, data)) {
          return;
        }
      }
      this._render(ctx, indices, data);
    }
  };

  GlyphView.prototype._render_gl = function(ctx, indices, mainglyph) {
    var dx, dy, ref, ref1, ref2, sx, sy, trans, wx, wy;
    wx = wy = 1;
    ref = this.renderer.map_to_screen([0 * wx, 1 * wx, 2 * wx], [0 * wy, 1 * wy, 2 * wy]), dx = ref[0], dy = ref[1];
    wx = 100 / Math.min(Math.max(Math.abs(dx[1] - dx[0]), 1e-12), 1e12);
    wy = 100 / Math.min(Math.max(Math.abs(dy[1] - dy[0]), 1e-12), 1e12);
    ref1 = this.renderer.map_to_screen([0 * wx, 1 * wx, 2 * wx], [0 * wy, 1 * wy, 2 * wy]), dx = ref1[0], dy = ref1[1];
    if (Math.abs((dx[1] - dx[0]) - (dx[2] - dx[1])) > 1e-6 || Math.abs((dy[1] - dy[0]) - (dy[2] - dy[1])) > 1e-6) {
      return false;
    }
    ref2 = [(dx[1] - dx[0]) / wx, (dy[1] - dy[0]) / wy], sx = ref2[0], sy = ref2[1];
    trans = {
      pixel_ratio: ctx.pixel_ratio,
      width: ctx.glcanvas.width,
      height: ctx.glcanvas.height,
      dx: dx[0] / sx,
      dy: dy[0] / sy,
      sx: sx,
      sy: sy
    };
    this.glglyph.draw(indices, mainglyph, trans);
    return true;
  };

  GlyphView.prototype.bounds = function() {
    var bb, d;
    if (this.index == null) {
      return bbox.empty();
    }
    d = this.index.data;
    bb = {
      minX: d.minX,
      minY: d.minY,
      maxX: d.maxX,
      maxY: d.maxY
    };
    return this._bounds(bb);
  };

  GlyphView.prototype.max_wh2_bounds = function(bds) {
    return {
      minX: bds.minX - this.max_w2,
      maxX: bds.maxX + this.max_w2,
      minY: bds.minY - this.max_h2,
      maxY: bds.maxY + this.max_h2
    };
  };

  GlyphView.prototype.get_anchor_point = function(anchor, i, arg) {
    var sx, sy;
    sx = arg[0], sy = arg[1];
    switch (anchor) {
      case "center":
        return {
          x: this.scx(i, sx, sy),
          y: this.scy(i, sx, sy)
        };
      default:
        return null;
    }
  };

  GlyphView.prototype.scx = function(i) {
    return this.sx[i];
  };

  GlyphView.prototype.scy = function(i) {
    return this.sy[i];
  };

  GlyphView.prototype._xy_index = function() {
    var i, index, j, pts, ref, x, xx, y, yy;
    index = rbush();
    pts = [];
    if (this.renderer.xmapper instanceof CategoricalMapper.Model) {
      xx = this.renderer.xmapper.v_map_to_target(this._x, true);
    } else {
      xx = this._x;
    }
    if (this.renderer.ymapper instanceof CategoricalMapper.Model) {
      yy = this.renderer.ymapper.v_map_to_target(this._y, true);
    } else {
      yy = this._y;
    }
    for (i = j = 0, ref = xx.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      x = xx[i];
      if (isNaN(x) || !isFinite(x)) {
        continue;
      }
      y = yy[i];
      if (isNaN(y) || !isFinite(y)) {
        continue;
      }
      pts.push({
        minX: x,
        minY: y,
        maxX: x,
        maxY: y,
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  GlyphView.prototype.sdist = function(mapper, pts, spans, pts_location, dilate) {
    var d, halfspan, i, pt0, pt1, spt0, spt1;
    if (pts_location == null) {
      pts_location = "edge";
    }
    if (dilate == null) {
      dilate = false;
    }
    if (_.isString(pts[0])) {
      pts = mapper.v_map_to_target(pts);
    }
    if (pts_location === 'center') {
      halfspan = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = spans.length; j < len; j++) {
          d = spans[j];
          results.push(d / 2);
        }
        return results;
      })();
      pt0 = (function() {
        var j, ref, results;
        results = [];
        for (i = j = 0, ref = pts.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
          results.push(pts[i] - halfspan[i]);
        }
        return results;
      })();
      pt1 = (function() {
        var j, ref, results;
        results = [];
        for (i = j = 0, ref = pts.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
          results.push(pts[i] + halfspan[i]);
        }
        return results;
      })();
    } else {
      pt0 = pts;
      pt1 = (function() {
        var j, ref, results;
        results = [];
        for (i = j = 0, ref = pt0.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
          results.push(pt0[i] + spans[i]);
        }
        return results;
      })();
    }
    spt0 = mapper.v_map_to_target(pt0);
    spt1 = mapper.v_map_to_target(pt1);
    if (dilate) {
      return (function() {
        var j, ref, results;
        results = [];
        for (i = j = 0, ref = spt0.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
          results.push(Math.ceil(Math.abs(spt1[i] - spt0[i])));
        }
        return results;
      })();
    } else {
      return (function() {
        var j, ref, results;
        results = [];
        for (i = j = 0, ref = spt0.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
          results.push(Math.abs(spt1[i] - spt0[i]));
        }
        return results;
      })();
    }
  };

  GlyphView.prototype.get_reference_point = function() {
    return void 0;
  };

  GlyphView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return null;
  };

  GlyphView.prototype._generic_line_legend = function(ctx, x0, x1, y0, y1) {
    var ref, reference_point;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(x0, (y0 + y1) / 2);
    ctx.lineTo(x1, (y0 + y1) / 2);
    if (this.visuals.line.doit) {
      this.visuals.line.set_vectorize(ctx, reference_point);
      ctx.stroke();
    }
    return ctx.restore();
  };

  GlyphView.prototype._generic_area_legend = function(ctx, x0, x1, y0, y1) {
    var dh, dw, h, indices, ref, reference_point, sx0, sx1, sy0, sy1, w;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    w = Math.abs(x1 - x0);
    dw = w * 0.1;
    h = Math.abs(y1 - y0);
    dh = h * 0.1;
    sx0 = x0 + dw;
    sx1 = x1 - dw;
    sy0 = y0 + dh;
    sy1 = y1 - dh;
    if (this.visuals.fill.doit) {
      this.visuals.fill.set_vectorize(ctx, reference_point);
      ctx.fillRect(sx0, sy0, sx1 - sx0, sy1 - sy0);
    }
    if (this.visuals.line.doit) {
      ctx.beginPath();
      ctx.rect(sx0, sy0, sx1 - sx0, sy1 - sy0);
      this.visuals.line.set_vectorize(ctx, reference_point);
      return ctx.stroke();
    }
  };

  return GlyphView;

})(Renderer.View);

Glyph = (function(superClass) {
  extend(Glyph, superClass);

  function Glyph() {
    return Glyph.__super__.constructor.apply(this, arguments);
  }

  Glyph.define({
    visible: [p.Bool, true]
  });

  Glyph.internal({
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default']
  });

  return Glyph;

})(Model);

module.exports = {
  Model: Glyph,
  View: GlyphView
};

},{"../../core/properties":"core/properties","../../core/util/bbox":"core/util/bbox","../../model":"model","../mappers/categorical_mapper":"models/mappers/categorical_mapper","../renderers/renderer":"models/renderers/renderer","./webgl/main":"models/glyphs/webgl/main","rbush":"rbush","underscore":"underscore"}],"models/glyphs/hbar":[function(require,module,exports){
var Glyph, HBar, HBarView, Quad, _, hittest, p, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Quad = require("./quad");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

HBarView = (function(superClass) {
  extend(HBarView, superClass);

  function HBarView() {
    return HBarView.__super__.constructor.apply(this, arguments);
  }

  HBarView.prototype._map_data = function() {
    var i, j, ref, vleft, vright, vy;
    vy = this.renderer.ymapper.v_map_to_target(this._y);
    this.sy = this.plot_view.canvas.v_vy_to_sy(vy);
    vright = this.renderer.xmapper.v_map_to_target(this._right);
    vleft = this.renderer.xmapper.v_map_to_target(this._left);
    this.sright = this.plot_view.canvas.v_vx_to_sx(vright);
    this.sleft = this.plot_view.canvas.v_vx_to_sx(vleft);
    this.stop = [];
    this.sbottom = [];
    this.sh = this.sdist(this.renderer.ymapper, this._y, this._height, 'center');
    for (i = j = 0, ref = this.sy.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      this.stop.push(this.sy[i] - this.sh[i] / 2);
      this.sbottom.push(this.sy[i] + this.sh[i] / 2);
    }
    return null;
  };

  HBarView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sbottom, sleft, sright, stop;
    sleft = arg.sleft, sright = arg.sright, stop = arg.stop, sbottom = arg.sbottom;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sleft[i] + stop[i] + sright[i] + sbottom[i])) {
        continue;
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fillRect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i]);
      }
      if (this.visuals.line.doit) {
        ctx.beginPath();
        ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return HBarView;

})(Glyph.View);

HBar = (function(superClass) {
  extend(HBar, superClass);

  function HBar() {
    return HBar.__super__.constructor.apply(this, arguments);
  }

  HBar.prototype.default_view = HBarView;

  HBar.prototype.type = 'HBar';

  HBar.mixins(['line', 'fill']);

  HBar.define({
    y: [p.NumberSpec],
    height: [p.DistanceSpec],
    left: [p.NumberSpec, 0],
    right: [p.NumberSpec]
  });

  return HBar;

})(Glyph.Model);

module.exports = {
  Model: HBar,
  View: HBarView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","./quad":"models/glyphs/quad","rbush":"rbush","underscore":"underscore"}],"models/glyphs/image":[function(require,module,exports){
var Glyph, Greys, Image, ImageView, LinearColorMapper, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("../glyphs/glyph");

LinearColorMapper = require("../mappers/linear_color_mapper");

p = require("../../core/properties");

Greys = require('../../palettes/palettes').Greys;

ImageView = (function(superClass) {
  extend(ImageView, superClass);

  function ImageView() {
    return ImageView.__super__.constructor.apply(this, arguments);
  }

  ImageView.prototype._index_data = function() {
    return this._xy_index();
  };

  ImageView.prototype._set_data = function() {
    var buf, buf8, canvas, cmap, ctx, i, image_data, img, j, ref, results;
    if ((this.image_data == null) || this.image_data.length !== this._image.length) {
      this.image_data = new Array(this._image.length);
    }
    if ((this._width == null) || this._width.length !== this._image.length) {
      this._width = new Array(this._image.length);
    }
    if ((this._height == null) || this._height.length !== this._image.length) {
      this._height = new Array(this._image.length);
    }
    results = [];
    for (i = j = 0, ref = this._image.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (this._rows != null) {
        this._height[i] = this._rows[i];
        this._width[i] = this._cols[i];
      } else {
        this._height[i] = this._image[i].length;
        this._width[i] = this._image[i][0].length;
      }
      canvas = document.createElement('canvas');
      canvas.width = this._width[i];
      canvas.height = this._height[i];
      ctx = canvas.getContext('2d');
      image_data = ctx.getImageData(0, 0, this._width[i], this._height[i]);
      cmap = this.mget('color_mapper');
      if (this._rows != null) {
        img = this._image[i];
      } else {
        img = _.flatten(this._image[i]);
      }
      buf = cmap.v_map_screen(img);
      buf8 = new Uint8ClampedArray(buf);
      image_data.data.set(buf8);
      ctx.putImageData(image_data, 0, 0);
      this.image_data[i] = canvas;
      this.max_dw = 0;
      if (this._dw.units === "data") {
        this.max_dw = _.max(this._dw);
      }
      this.max_dh = 0;
      if (this._dh.units === "data") {
        this.max_dh = _.max(this._dh);
      }
      results.push(this._xy_index());
    }
    return results;
  };

  ImageView.prototype._map_data = function() {
    this.sw = this.sdist(this.renderer.xmapper, this._x, this._dw, 'edge', this.mget('dilate'));
    return this.sh = this.sdist(this.renderer.ymapper, this._y, this._dh, 'edge', this.mget('dilate'));
  };

  ImageView.prototype._render = function(ctx, indices, arg) {
    var i, image_data, j, len, old_smoothing, sh, sw, sx, sy, y_offset;
    image_data = arg.image_data, sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh;
    old_smoothing = ctx.getImageSmoothingEnabled();
    ctx.setImageSmoothingEnabled(false);
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (image_data[i] == null) {
        continue;
      }
      if (isNaN(sx[i] + sy[i] + sw[i] + sh[i])) {
        continue;
      }
      y_offset = sy[i];
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
      ctx.drawImage(image_data[i], sx[i] | 0, sy[i] | 0, sw[i], sh[i]);
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
    }
    return ctx.setImageSmoothingEnabled(old_smoothing);
  };

  ImageView.prototype.bounds = function() {
    var d;
    d = this.index.data;
    return {
      minX: d.minX,
      minY: d.minY,
      maxX: d.maxX + this.max_dw,
      maxY: d.maxY + this.max_dh
    };
  };

  return ImageView;

})(Glyph.View);

Image = (function(superClass) {
  extend(Image, superClass);

  function Image() {
    return Image.__super__.constructor.apply(this, arguments);
  }

  Image.prototype.default_view = ImageView;

  Image.prototype.type = 'Image';

  Image.coords([['x', 'y']]);

  Image.mixins([]);

  Image.define({
    image: [p.NumberSpec],
    dw: [p.NumberSpec],
    dh: [p.NumberSpec],
    dilate: [p.Bool, false],
    color_mapper: [
      p.Instance, function() {
        return new LinearColorMapper.Model({
          palette: Greys.Greys9
        });
      }
    ]
  });

  return Image;

})(Glyph.Model);

module.exports = {
  Model: Image,
  View: ImageView
};

},{"../../core/properties":"core/properties","../../palettes/palettes":"palettes/palettes","../glyphs/glyph":"models/glyphs/glyph","../mappers/linear_color_mapper":"models/mappers/linear_color_mapper","underscore":"underscore"}],"models/glyphs/image_rgba":[function(require,module,exports){
var Glyph, ImageRGBA, ImageRGBAView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

p = require("../../core/properties");

ImageRGBAView = (function(superClass) {
  extend(ImageRGBAView, superClass);

  function ImageRGBAView() {
    return ImageRGBAView.__super__.constructor.apply(this, arguments);
  }

  ImageRGBAView.prototype._index_data = function() {
    return this._xy_index();
  };

  ImageRGBAView.prototype._set_data = function(source, arg) {
    var buf, buf8, canvas, color, ctx, flat, i, image_data, j, k, l, ref, ref1, results;
    if ((this.image_data == null) || this.image_data.length !== this._image.length) {
      this.image_data = new Array(this._image.length);
    }
    if ((this._width == null) || this._width.length !== this._image.length) {
      this._width = new Array(this._image.length);
    }
    if ((this._height == null) || this._height.length !== this._image.length) {
      this._height = new Array(this._image.length);
    }
    results = [];
    for (i = k = 0, ref = this._image.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      if (arg != null) {
        if (i !== arg) {
          continue;
        }
      }
      if (this._rows != null) {
        this._height[i] = this._rows[i];
        this._width[i] = this._cols[i];
      } else {
        this._height[i] = this._image[i].length;
        this._width[i] = this._image[i][0].length;
      }
      canvas = document.createElement('canvas');
      canvas.width = this._width[i];
      canvas.height = this._height[i];
      ctx = canvas.getContext('2d');
      image_data = ctx.getImageData(0, 0, this._width[i], this._height[i]);
      if (this._rows != null) {
        image_data.data.set(new Uint8ClampedArray(this._image[i]));
      } else {
        flat = _.flatten(this._image[i]);
        buf = new ArrayBuffer(flat.length * 4);
        color = new Uint32Array(buf);
        for (j = l = 0, ref1 = flat.length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
          color[j] = flat[j];
        }
        buf8 = new Uint8ClampedArray(buf);
        image_data.data.set(buf8);
      }
      ctx.putImageData(image_data, 0, 0);
      this.image_data[i] = canvas;
      this.max_dw = 0;
      if (this._dw.units === "data") {
        this.max_dw = _.max(this._dw);
      }
      this.max_dh = 0;
      if (this._dh.units === "data") {
        results.push(this.max_dh = _.max(this._dh));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  ImageRGBAView.prototype._map_data = function() {
    this.sw = this.sdist(this.renderer.xmapper, this._x, this._dw, 'edge', this.mget('dilate'));
    return this.sh = this.sdist(this.renderer.ymapper, this._y, this._dh, 'edge', this.mget('dilate'));
  };

  ImageRGBAView.prototype._render = function(ctx, indices, arg1) {
    var i, image_data, k, len, old_smoothing, sh, sw, sx, sy, y_offset;
    image_data = arg1.image_data, sx = arg1.sx, sy = arg1.sy, sw = arg1.sw, sh = arg1.sh;
    old_smoothing = ctx.getImageSmoothingEnabled();
    ctx.setImageSmoothingEnabled(false);
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      if (isNaN(sx[i] + sy[i] + sw[i] + sh[i])) {
        continue;
      }
      y_offset = sy[i];
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
      ctx.drawImage(image_data[i], sx[i] | 0, sy[i] | 0, sw[i], sh[i]);
      ctx.translate(0, y_offset);
      ctx.scale(1, -1);
      ctx.translate(0, -y_offset);
    }
    return ctx.setImageSmoothingEnabled(old_smoothing);
  };

  ImageRGBAView.prototype.bounds = function() {
    var d;
    d = this.index.data;
    return {
      minX: d.minX,
      minY: d.minY,
      maxX: d.maxX + this.max_dw,
      maxY: d.maxY + this.max_dh
    };
  };

  return ImageRGBAView;

})(Glyph.View);

ImageRGBA = (function(superClass) {
  extend(ImageRGBA, superClass);

  function ImageRGBA() {
    return ImageRGBA.__super__.constructor.apply(this, arguments);
  }

  ImageRGBA.prototype.default_view = ImageRGBAView;

  ImageRGBA.prototype.type = 'ImageRGBA';

  ImageRGBA.coords([['x', 'y']]);

  ImageRGBA.mixins([]);

  ImageRGBA.define({
    image: [p.NumberSpec],
    rows: [p.NumberSpec],
    cols: [p.NumberSpec],
    dw: [p.NumberSpec],
    dh: [p.NumberSpec],
    dilate: [p.Bool, false]
  });

  ImageRGBA.prototype.initialize = function(attrs, options) {
    ImageRGBA.__super__.initialize.call(this, attrs, options);
    this.properties.rows.optional = true;
    return this.properties.cols.optional = true;
  };

  return ImageRGBA;

})(Glyph.Model);

module.exports = {
  Model: ImageRGBA,
  View: ImageRGBAView
};

},{"../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/image_url":[function(require,module,exports){
var Glyph, ImageURL, ImageURLView, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

ImageURLView = (function(superClass) {
  extend(ImageURLView, superClass);

  function ImageURLView() {
    return ImageURLView.__super__.constructor.apply(this, arguments);
  }

  ImageURLView.prototype.initialize = function(options) {
    ImageURLView.__super__.initialize.call(this, options);
    return this.listenTo(this.model, 'change:global_alpha', this.renderer.request_render);
  };

  ImageURLView.prototype._index_data = function() {};

  ImageURLView.prototype._set_data = function() {
    var i, img, j, ref, results, retry_attempts, retry_timeout;
    if ((this.image == null) || this.image.length !== this._url.length) {
      this.image = (function() {
        var j, len, ref, results;
        ref = this._url;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          img = ref[j];
          results.push(null);
        }
        return results;
      }).call(this);
    }
    retry_attempts = this.mget('retry_attempts');
    retry_timeout = this.mget('retry_timeout');
    this.retries = (function() {
      var j, len, ref, results;
      ref = this._url;
      results = [];
      for (j = 0, len = ref.length; j < len; j++) {
        img = ref[j];
        results.push(retry_attempts);
      }
      return results;
    }).call(this);
    results = [];
    for (i = j = 0, ref = this._url.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (this._url[i] == null) {
        continue;
      }
      img = new Image();
      img.onerror = (function(_this) {
        return function(i, img) {
          return function() {
            if (_this.retries[i] > 0) {
              logger.trace("ImageURL failed to load " + _this._url[i] + " image, retrying in " + retry_timeout + " ms");
              setTimeout((function() {
                return img.src = _this._url[i];
              }), retry_timeout);
            } else {
              logger.warn("ImageURL unable to load " + _this._url[i] + " image after " + retry_attempts + " retries");
            }
            return _this.retries[i] -= 1;
          };
        };
      })(this)(i, img);
      img.onload = (function(_this) {
        return function(img, i) {
          return function() {
            _this.image[i] = img;
            return _this.renderer.request_render();
          };
        };
      })(this)(img, i);
      results.push(img.src = this._url[i]);
    }
    return results;
  };

  ImageURLView.prototype._map_data = function() {
    var hs, ws, x;
    ws = ((function() {
      var j, len, ref, results;
      if (this._w != null) {
        return this._w;
      } else {
        ref = this._x;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          x = ref[j];
          results.push(NaN);
        }
        return results;
      }
    }).call(this));
    hs = ((function() {
      var j, len, ref, results;
      if (this._h != null) {
        return this._h;
      } else {
        ref = this._x;
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          x = ref[j];
          results.push(NaN);
        }
        return results;
      }
    }).call(this));
    this.sw = this.sdist(this.renderer.xmapper, this._x, ws, 'edge', this.mget('dilate'));
    return this.sh = this.sdist(this.renderer.ymapper, this._y, hs, 'edge', this.mget('dilate'));
  };

  ImageURLView.prototype._render = function(ctx, indices, arg) {
    var _angle, _url, frame, i, image, j, len, results, sh, sw, sx, sy;
    _url = arg._url, image = arg.image, sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh, _angle = arg._angle;
    frame = this.renderer.plot_view.frame;
    ctx.rect(frame.get('left') + 1, frame.get('bottom') + 1, frame.get('width') - 2, frame.get('height') - 2);
    ctx.clip();
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _angle[i])) {
        continue;
      }
      if (this.retries[i] === -1) {
        continue;
      }
      if (image[i] == null) {
        continue;
      }
      results.push(this._render_image(ctx, i, image[i], sx, sy, sw, sh, _angle));
    }
    return results;
  };

  ImageURLView.prototype._final_sx_sy = function(anchor, sx, sy, sw, sh) {
    switch (anchor) {
      case "top_left":
        return [sx, sy];
      case "top_center":
        return [sx - sw / 2, sy];
      case "top_right":
        return [sx - sw, sy];
      case "right_center":
        return [sx - sw, sy - sh / 2];
      case "bottom_right":
        return [sx - sw, sy - sh];
      case "bottom_center":
        return [sx - sw / 2, sy - sh];
      case "bottom_left":
        return [sx, sy - sh];
      case "left_center":
        return [sx, sy - sh / 2];
      case "center":
        return [sx - sw / 2, sy - sh / 2];
    }
  };

  ImageURLView.prototype._render_image = function(ctx, i, image, sx, sy, sw, sh, angle) {
    var anchor, ref;
    if (isNaN(sw[i])) {
      sw[i] = image.width;
    }
    if (isNaN(sh[i])) {
      sh[i] = image.height;
    }
    anchor = this.mget('anchor');
    ref = this._final_sx_sy(anchor, sx[i], sy[i], sw[i], sh[i]), sx = ref[0], sy = ref[1];
    ctx.save();
    ctx.globalAlpha = this.mget("global_alpha");
    if (angle[i]) {
      ctx.translate(sx, sy);
      ctx.rotate(angle[i]);
      ctx.drawImage(image, 0, 0, sw[i], sh[i]);
      ctx.rotate(-angle[i]);
      ctx.translate(-sx, -sy);
    } else {
      ctx.drawImage(image, sx, sy, sw[i], sh[i]);
    }
    return ctx.restore();
  };

  return ImageURLView;

})(Glyph.View);

ImageURL = (function(superClass) {
  extend(ImageURL, superClass);

  function ImageURL() {
    return ImageURL.__super__.constructor.apply(this, arguments);
  }

  ImageURL.prototype.default_view = ImageURLView;

  ImageURL.prototype.type = 'ImageURL';

  ImageURL.coords([['x', 'y']]);

  ImageURL.mixins([]);

  ImageURL.define({
    url: [p.StringSpec],
    anchor: [p.Anchor, 'top_left'],
    global_alpha: [p.Number, 1.0],
    angle: [p.AngleSpec, 0],
    w: [p.NumberSpec],
    h: [p.NumberSpec],
    dilate: [p.Bool, false],
    retry_attempts: [p.Number, 0],
    retry_timeout: [p.Number, 0]
  });

  return ImageURL;

})(Glyph.Model);

module.exports = {
  Model: ImageURL,
  View: ImageURLView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/line":[function(require,module,exports){
var Glyph, Line, LineView, _, hittest,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

LineView = (function(superClass) {
  extend(LineView, superClass);

  function LineView() {
    return LineView.__super__.constructor.apply(this, arguments);
  }

  LineView.prototype._index_data = function() {
    return this._xy_index();
  };

  LineView.prototype._render = function(ctx, indices, arg) {
    var drawing, i, j, len, sx, sy;
    sx = arg.sx, sy = arg.sy;
    drawing = false;
    this.visuals.line.set_value(ctx);
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (!isFinite(sx[i] + sy[i]) && drawing) {
        ctx.stroke();
        ctx.beginPath();
        drawing = false;
        continue;
      }
      if (drawing) {
        ctx.lineTo(sx[i], sy[i]);
      } else {
        ctx.beginPath();
        ctx.moveTo(sx[i], sy[i]);
        drawing = true;
      }
    }
    if (drawing) {
      return ctx.stroke();
    }
  };

  LineView.prototype._hit_point = function(geometry) {

    /* Check if the point geometry hits this line glyph and return an object
    that describes the hit result:
      Args:
        * geometry (object): object with the following keys
          * vx (float): view x coordinate of the point
          * vy (float): view y coordinate of the point
          * type (str): type of geometry (in this case it's a point)
      Output:
        Object with the following keys:
          * 0d (bool): whether the point hits the glyph or not
          * 1d (array(int)): array with the indices hit by the point
     */
    var dist, i, j, p0, p1, point, ref, ref1, result, shortest, threshold;
    result = hittest.create_hit_test_result();
    point = {
      x: this.renderer.plot_view.canvas.vx_to_sx(geometry.vx),
      y: this.renderer.plot_view.canvas.vy_to_sy(geometry.vy)
    };
    shortest = 9999;
    threshold = Math.max(2, this.visuals.line.line_width.value() / 2);
    for (i = j = 0, ref = this.sx.length - 1; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ref1 = [
        {
          x: this.sx[i],
          y: this.sy[i]
        }, {
          x: this.sx[i + 1],
          y: this.sy[i + 1]
        }
      ], p0 = ref1[0], p1 = ref1[1];
      dist = hittest.dist_to_segment(point, p0, p1);
      if (dist < threshold && dist < shortest) {
        shortest = dist;
        result['0d'].glyph = this.model;
        result['0d'].get_view = (function() {
          return this;
        }).bind(this);
        result['0d'].flag = true;
        result['0d'].indices = [i];
      }
    }
    return result;
  };

  LineView.prototype._hit_span = function(geometry) {
    var i, j, ref, ref1, result, val, values, vx, vy;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    result = hittest.create_hit_test_result();
    if (geometry.direction === 'v') {
      val = this.renderer.ymapper.map_from_target(vy);
      values = this._y;
    } else {
      val = this.renderer.xmapper.map_from_target(vx);
      values = this._x;
    }
    for (i = j = 0, ref1 = values.length - 1; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
      if ((values[i] <= val && val <= values[i + 1])) {
        result['0d'].glyph = this.model;
        result['0d'].get_view = (function() {
          return this;
        }).bind(this);
        result['0d'].flag = true;
        result['0d'].indices.push(i);
      }
    }
    return result;
  };

  LineView.prototype.get_interpolation_hit = function(i, geometry) {
    var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, res, vx, vy, x0, x1, x2, x3, y0, y1, y2, y3;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    ref1 = [this._x[i], this._y[i], this._x[i + 1], this._y[i + 1]], x2 = ref1[0], y2 = ref1[1], x3 = ref1[2], y3 = ref1[3];
    if (geometry.type === 'point') {
      ref2 = this.renderer.ymapper.v_map_from_target([vy - 1, vy + 1]), y0 = ref2[0], y1 = ref2[1];
      ref3 = this.renderer.xmapper.v_map_from_target([vx - 1, vx + 1]), x0 = ref3[0], x1 = ref3[1];
    } else {
      if (geometry.direction === 'v') {
        ref4 = this.renderer.ymapper.v_map_from_target([vy, vy]), y0 = ref4[0], y1 = ref4[1];
        ref5 = [x2, x3], x0 = ref5[0], x1 = ref5[1];
      } else {
        ref6 = this.renderer.xmapper.v_map_from_target([vx, vx]), x0 = ref6[0], x1 = ref6[1];
        ref7 = [y2, y3], y0 = ref7[0], y1 = ref7[1];
      }
    }
    res = hittest.check_2_segments_intersect(x0, y0, x1, y1, x2, y2, x3, y3);
    return [res.x, res.y];
  };

  LineView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return LineView;

})(Glyph.View);

Line = (function(superClass) {
  extend(Line, superClass);

  function Line() {
    return Line.__super__.constructor.apply(this, arguments);
  }

  Line.prototype.default_view = LineView;

  Line.prototype.type = 'Line';

  Line.coords([['x', 'y']]);

  Line.mixins(['line']);

  return Line;

})(Glyph.Model);

module.exports = {
  Model: Line,
  View: LineView
};

},{"../../common/hittest":"common/hittest","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/multi_line":[function(require,module,exports){
var Glyph, MultiLine, MultiLineView, _, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

MultiLineView = (function(superClass) {
  extend(MultiLineView, superClass);

  function MultiLineView() {
    return MultiLineView.__super__.constructor.apply(this, arguments);
  }

  MultiLineView.prototype._index_data = function() {
    var i, index, k, pts, ref, x, xs, y, ys;
    index = rbush();
    pts = [];
    for (i = k = 0, ref = this._xs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      xs = (function() {
        var l, len, ref1, results;
        ref1 = this._xs[i];
        results = [];
        for (l = 0, len = ref1.length; l < len; l++) {
          x = ref1[l];
          if (!_.isNaN(x)) {
            results.push(x);
          }
        }
        return results;
      }).call(this);
      ys = (function() {
        var l, len, ref1, results;
        ref1 = this._ys[i];
        results = [];
        for (l = 0, len = ref1.length; l < len; l++) {
          y = ref1[l];
          if (!_.isNaN(y)) {
            results.push(y);
          }
        }
        return results;
      }).call(this);
      if (xs.length === 0) {
        continue;
      }
      pts.push({
        minX: _.min(xs),
        minY: _.min(ys),
        maxX: _.max(xs),
        maxY: _.max(ys),
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  MultiLineView.prototype._render = function(ctx, indices, arg) {
    var i, j, k, l, len, ref, ref1, results, sx, sxs, sy, sys;
    sxs = arg.sxs, sys = arg.sys;
    results = [];
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      ref = [sxs[i], sys[i]], sx = ref[0], sy = ref[1];
      this.visuals.line.set_vectorize(ctx, i);
      for (j = l = 0, ref1 = sx.length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        if (j === 0) {
          ctx.beginPath();
          ctx.moveTo(sx[j], sy[j]);
          continue;
        } else if (isNaN(sx[j]) || isNaN(sy[j])) {
          ctx.stroke();
          ctx.beginPath();
          continue;
        } else {
          ctx.lineTo(sx[j], sy[j]);
        }
      }
      results.push(ctx.stroke());
    }
    return results;
  };

  MultiLineView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return MultiLineView;

})(Glyph.View);

MultiLine = (function(superClass) {
  extend(MultiLine, superClass);

  function MultiLine() {
    return MultiLine.__super__.constructor.apply(this, arguments);
  }

  MultiLine.prototype.default_view = MultiLineView;

  MultiLine.prototype.type = 'MultiLine';

  MultiLine.coords([['xs', 'ys']]);

  MultiLine.mixins(['line']);

  return MultiLine;

})(Glyph.Model);

module.exports = {
  Model: MultiLine,
  View: MultiLineView
};

},{"./glyph":"models/glyphs/glyph","rbush":"rbush","underscore":"underscore"}],"models/glyphs/oval":[function(require,module,exports){
var Glyph, Oval, OvalView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

p = require("../../core/properties");

OvalView = (function(superClass) {
  extend(OvalView, superClass);

  function OvalView() {
    return OvalView.__super__.constructor.apply(this, arguments);
  }

  OvalView.prototype._set_data = function() {
    this.max_w2 = 0;
    if (this.model.properties.width.units === "data") {
      this.max_w2 = this.max_width / 2;
    }
    this.max_h2 = 0;
    if (this.model.properties.height.units === "data") {
      return this.max_h2 = this.max_height / 2;
    }
  };

  OvalView.prototype._index_data = function() {
    return this._xy_index();
  };

  OvalView.prototype._map_data = function() {
    if (this.model.properties.width.units === "data") {
      this.sw = this.sdist(this.renderer.xmapper, this._x, this._width, 'center');
    } else {
      this.sw = this._width;
    }
    if (this.model.properties.height.units === "data") {
      return this.sh = this.sdist(this.renderer.ymapper, this._y, this._height, 'center');
    } else {
      return this.sh = this._height;
    }
  };

  OvalView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sh, sw, sx, sy;
    sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + sw[i] + sh[i] + this._angle[i])) {
        continue;
      }
      ctx.translate(sx[i], sy[i]);
      ctx.rotate(this._angle[i]);
      ctx.beginPath();
      ctx.moveTo(0, -sh[i] / 2);
      ctx.bezierCurveTo(sw[i] / 2, -sh[i] / 2, sw[i] / 2, sh[i] / 2, 0, sh[i] / 2);
      ctx.bezierCurveTo(-sw[i] / 2, sh[i] / 2, -sw[i] / 2, -sh[i] / 2, 0, -sh[i] / 2);
      ctx.closePath();
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      ctx.rotate(-this._angle[i]);
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  OvalView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var d, data, indices, ref, reference_point, scale, sh, sw, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    scale = this.sw[reference_point] / this.sh[reference_point];
    d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
    sw = {};
    sh = {};
    if (scale > 1) {
      sw[reference_point] = d;
      sh[reference_point] = d / scale;
    } else {
      sw[reference_point] = d * scale;
      sh[reference_point] = d;
    }
    data = {
      sx: sx,
      sy: sy,
      sw: sw,
      sh: sh
    };
    return this._render(ctx, indices, data);
  };

  OvalView.prototype._bounds = function(bds) {
    return this.max_wh2_bounds(bds);
  };

  return OvalView;

})(Glyph.View);

Oval = (function(superClass) {
  extend(Oval, superClass);

  function Oval() {
    return Oval.__super__.constructor.apply(this, arguments);
  }

  Oval.prototype.default_view = OvalView;

  Oval.prototype.type = 'Oval';

  Oval.coords([['x', 'y']]);

  Oval.mixins(['line', 'fill']);

  Oval.define({
    angle: [p.AngleSpec, 0.0],
    width: [p.DistanceSpec],
    height: [p.DistanceSpec]
  });

  return Oval;

})(Glyph.Model);

module.exports = {
  Model: Oval,
  View: OvalView
};

},{"../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/patch":[function(require,module,exports){
var Glyph, Patch, PatchView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

PatchView = (function(superClass) {
  extend(PatchView, superClass);

  function PatchView() {
    return PatchView.__super__.constructor.apply(this, arguments);
  }

  PatchView.prototype._index_data = function() {
    return this._xy_index();
  };

  PatchView.prototype._render = function(ctx, indices, arg) {
    var i, j, k, len, len1, sx, sy;
    sx = arg.sx, sy = arg.sy;
    if (this.visuals.fill.doit) {
      this.visuals.fill.set_value(ctx);
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (i === 0) {
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i]);
          continue;
        } else if (isNaN(sx[i] + sy[i])) {
          ctx.closePath();
          ctx.fill();
          ctx.beginPath();
          continue;
        } else {
          ctx.lineTo(sx[i], sy[i]);
        }
      }
      ctx.closePath();
      ctx.fill();
    }
    if (this.visuals.line.doit) {
      this.visuals.line.set_value(ctx);
      for (k = 0, len1 = indices.length; k < len1; k++) {
        i = indices[k];
        if (i === 0) {
          ctx.beginPath();
          ctx.moveTo(sx[i], sy[i]);
          continue;
        } else if (isNaN(sx[i] + sy[i])) {
          ctx.closePath();
          ctx.stroke();
          ctx.beginPath();
          continue;
        } else {
          ctx.lineTo(sx[i], sy[i]);
        }
      }
      ctx.closePath();
      return ctx.stroke();
    }
  };

  PatchView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return PatchView;

})(Glyph.View);

Patch = (function(superClass) {
  extend(Patch, superClass);

  function Patch() {
    return Patch.__super__.constructor.apply(this, arguments);
  }

  Patch.prototype.default_view = PatchView;

  Patch.prototype.type = 'Patch';

  Patch.coords([['x', 'y']]);

  Patch.mixins(['line', 'fill']);

  return Patch;

})(Glyph.Model);

module.exports = {
  Model: Patch,
  View: PatchView
};

},{"./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/patches":[function(require,module,exports){
var Glyph, Patches, PatchesView, _, hittest, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

PatchesView = (function(superClass) {
  extend(PatchesView, superClass);

  function PatchesView() {
    return PatchesView.__super__.constructor.apply(this, arguments);
  }

  PatchesView.prototype._build_discontinuous_object = function(nanned_qs) {
    var denanned, ds, i, k, nan_index, q, qs, qs_part, ref;
    ds = {};
    for (i = k = 0, ref = nanned_qs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      ds[i] = [];
      qs = _.toArray(nanned_qs[i]);
      while (qs.length > 0) {
        nan_index = _.findLastIndex(qs, function(q) {
          return _.isNaN(q);
        });
        if (nan_index >= 0) {
          qs_part = qs.splice(nan_index);
        } else {
          qs_part = qs;
          qs = [];
        }
        denanned = (function() {
          var l, len, results;
          results = [];
          for (l = 0, len = qs_part.length; l < len; l++) {
            q = qs_part[l];
            if (!_.isNaN(q)) {
              results.push(q);
            }
          }
          return results;
        })();
        ds[i].push(denanned);
      }
    }
    return ds;
  };

  PatchesView.prototype._index_data = function() {
    var i, index, j, k, l, pts, ref, ref1, xs, xss, ys, yss;
    index = rbush();
    pts = [];
    xss = this._build_discontinuous_object(this._xs);
    yss = this._build_discontinuous_object(this._ys);
    for (i = k = 0, ref = this._xs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      for (j = l = 0, ref1 = xss[i].length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        xs = xss[i][j];
        ys = yss[i][j];
        if (xs.length === 0) {
          continue;
        }
        pts.push({
          minX: _.min(xs),
          minY: _.min(ys),
          maxX: _.max(xs),
          maxY: _.max(ys),
          i: i
        });
      }
    }
    index.load(pts);
    return index;
  };

  PatchesView.prototype._mask_data = function(all_indices) {
    var bbox, ref, ref1, x, x0, x1, xr, y0, y1, yr;
    xr = this.renderer.plot_view.x_range;
    ref = [xr.get('min'), xr.get('max')], x0 = ref[0], x1 = ref[1];
    yr = this.renderer.plot_view.y_range;
    ref1 = [yr.get('min'), yr.get('max')], y0 = ref1[0], y1 = ref1[1];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    return (function() {
      var k, len, ref2, results;
      ref2 = this.index.search(bbox);
      results = [];
      for (k = 0, len = ref2.length; k < len; k++) {
        x = ref2[k];
        results.push(x.i);
      }
      return results;
    }).call(this);
  };

  PatchesView.prototype._render = function(ctx, indices, arg) {
    var i, j, k, l, len, m, ref, ref1, ref2, results, sx, sxs, sy, sys;
    sxs = arg.sxs, sys = arg.sys;
    this.sxss = this._build_discontinuous_object(sxs);
    this.syss = this._build_discontinuous_object(sys);
    results = [];
    for (k = 0, len = indices.length; k < len; k++) {
      i = indices[k];
      ref = [sxs[i], sys[i]], sx = ref[0], sy = ref[1];
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        for (j = l = 0, ref1 = sx.length; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
          if (j === 0) {
            ctx.beginPath();
            ctx.moveTo(sx[j], sy[j]);
            continue;
          } else if (isNaN(sx[j] + sy[j])) {
            ctx.closePath();
            ctx.fill();
            ctx.beginPath();
            continue;
          } else {
            ctx.lineTo(sx[j], sy[j]);
          }
        }
        ctx.closePath();
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        for (j = m = 0, ref2 = sx.length; 0 <= ref2 ? m < ref2 : m > ref2; j = 0 <= ref2 ? ++m : --m) {
          if (j === 0) {
            ctx.beginPath();
            ctx.moveTo(sx[j], sy[j]);
            continue;
          } else if (isNaN(sx[j] + sy[j])) {
            ctx.closePath();
            ctx.stroke();
            ctx.beginPath();
            continue;
          } else {
            ctx.lineTo(sx[j], sy[j]);
          }
        }
        ctx.closePath();
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  PatchesView.prototype._hit_point = function(geometry) {
    var candidates, hits, i, idx, j, k, l, ref, ref1, ref2, result, sx, sxs, sy, sys, vx, vy, x, y;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
    sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
    x = this.renderer.xmapper.map_from_target(vx, true);
    y = this.renderer.ymapper.map_from_target(vy, true);
    candidates = (function() {
      var k, len, ref1, results;
      ref1 = this.index.search({
        minX: x,
        minY: y,
        maxX: x,
        maxY: y
      });
      results = [];
      for (k = 0, len = ref1.length; k < len; k++) {
        x = ref1[k];
        results.push(x.i);
      }
      return results;
    }).call(this);
    hits = [];
    for (i = k = 0, ref1 = candidates.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
      idx = candidates[i];
      sxs = this.sxss[idx];
      sys = this.syss[idx];
      for (j = l = 0, ref2 = sxs.length; 0 <= ref2 ? l < ref2 : l > ref2; j = 0 <= ref2 ? ++l : --l) {
        if (hittest.point_in_poly(sx, sy, sxs[j], sys[j])) {
          hits.push(idx);
        }
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  PatchesView.prototype._get_snap_coord = function(array) {
    var k, len, s, sum;
    sum = 0;
    for (k = 0, len = array.length; k < len; k++) {
      s = array[k];
      sum += s;
    }
    return sum / array.length;
  };

  PatchesView.prototype.scx = function(i, sx, sy) {
    var j, k, ref, sxs, sys;
    if (this.sxss[i].length === 1) {
      return this._get_snap_coord(this.sxs[i]);
    } else {
      sxs = this.sxss[i];
      sys = this.syss[i];
      for (j = k = 0, ref = sxs.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
        if (hittest.point_in_poly(sx, sy, sxs[j], sys[j])) {
          return this._get_snap_coord(sxs[j]);
        }
      }
    }
    return null;
  };

  PatchesView.prototype.scy = function(i, sx, sy) {
    var j, k, ref, sxs, sys;
    if (this.syss[i].length === 1) {
      return this._get_snap_coord(this.sys[i]);
    } else {
      sxs = this.sxss[i];
      sys = this.syss[i];
      for (j = k = 0, ref = sxs.length; 0 <= ref ? k < ref : k > ref; j = 0 <= ref ? ++k : --k) {
        if (hittest.point_in_poly(sx, sy, sxs[j], sys[j])) {
          return this._get_snap_coord(sys[j]);
        }
      }
    }
  };

  PatchesView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return PatchesView;

})(Glyph.View);

Patches = (function(superClass) {
  extend(Patches, superClass);

  function Patches() {
    return Patches.__super__.constructor.apply(this, arguments);
  }

  Patches.prototype.default_view = PatchesView;

  Patches.prototype.type = 'Patches';

  Patches.coords([['xs', 'ys']]);

  Patches.mixins(['line', 'fill']);

  return Patches;

})(Glyph.Model);

module.exports = {
  Model: Patches,
  View: PatchesView
};

},{"../../common/hittest":"common/hittest","./glyph":"models/glyphs/glyph","rbush":"rbush","underscore":"underscore"}],"models/glyphs/quad":[function(require,module,exports){
var CategoricalMapper, Glyph, Quad, QuadView, _, hittest, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

CategoricalMapper = require("../mappers/categorical_mapper");

hittest = require("../../common/hittest");

QuadView = (function(superClass) {
  extend(QuadView, superClass);

  function QuadView() {
    return QuadView.__super__.constructor.apply(this, arguments);
  }

  QuadView.prototype._index_data = function() {
    var b, bottom, i, index, j, l, left, map_to_synthetic, pts, r, ref, right, t, top;
    map_to_synthetic = function(mapper, array) {
      if (mapper instanceof CategoricalMapper.Model) {
        return mapper.v_map_to_target(array, true);
      } else {
        return array;
      }
    };
    left = map_to_synthetic(this.renderer.xmapper, this._left);
    right = map_to_synthetic(this.renderer.xmapper, this._right);
    top = map_to_synthetic(this.renderer.ymapper, this._top);
    bottom = map_to_synthetic(this.renderer.ymapper, this._bottom);
    index = rbush();
    pts = [];
    for (i = j = 0, ref = left.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      l = left[i];
      if (isNaN(l) || !isFinite(l)) {
        continue;
      }
      r = right[i];
      if (isNaN(r) || !isFinite(r)) {
        continue;
      }
      t = top[i];
      if (isNaN(t) || !isFinite(t)) {
        continue;
      }
      b = bottom[i];
      if (isNaN(b) || !isFinite(b)) {
        continue;
      }
      pts.push({
        minX: l,
        minY: b,
        maxX: r,
        maxY: t,
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  QuadView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sbottom, sleft, sright, stop;
    sleft = arg.sleft, sright = arg.sright, stop = arg.stop, sbottom = arg.sbottom;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sleft[i] + stop[i] + sright[i] + sbottom[i])) {
        continue;
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fillRect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i]);
      }
      if (this.visuals.line.doit) {
        ctx.beginPath();
        ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  QuadView.prototype._hit_point = function(geometry) {
    var hits, ref, result, vx, vy, x, y;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx, true);
    y = this.renderer.ymapper.map_from_target(vy, true);
    hits = (function() {
      var j, len, ref1, results;
      ref1 = this.index.search({
        minX: x,
        minY: y,
        maxX: x,
        maxY: y
      });
      results = [];
      for (j = 0, len = ref1.length; j < len; j++) {
        x = ref1[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  QuadView.prototype.get_anchor_point = function(anchor, i, spt) {
    var bottom, left, right, top;
    left = Math.min(this.sleft[i], this.sright[i]);
    right = Math.max(this.sright[i], this.sleft[i]);
    top = Math.min(this.stop[i], this.sbottom[i]);
    bottom = Math.max(this.sbottom[i], this.stop[i]);
    switch (anchor) {
      case "top_left":
        return {
          x: left,
          y: top
        };
      case "top_center":
        return {
          x: (left + right) / 2,
          y: top
        };
      case "top_right":
        return {
          x: right,
          y: top
        };
      case "right_center":
        return {
          x: right,
          y: (top + bottom) / 2
        };
      case "bottom_right":
        return {
          x: right,
          y: bottom
        };
      case "bottom_center":
        return {
          x: (left + right) / 2,
          y: bottom
        };
      case "bottom_left":
        return {
          x: left,
          y: bottom
        };
      case "left_center":
        return {
          x: left,
          y: (top + bottom) / 2
        };
      case "center":
        return {
          x: (left + right) / 2,
          y: (top + bottom) / 2
        };
    }
  };

  QuadView.prototype.scx = function(i) {
    return (this.sleft[i] + this.sright[i]) / 2;
  };

  QuadView.prototype.scy = function(i) {
    return (this.stop[i] + this.sbottom[i]) / 2;
  };

  QuadView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return QuadView;

})(Glyph.View);

Quad = (function(superClass) {
  extend(Quad, superClass);

  function Quad() {
    return Quad.__super__.constructor.apply(this, arguments);
  }

  Quad.prototype.default_view = QuadView;

  Quad.prototype.type = 'Quad';

  Quad.coords([['right', 'bottom'], ['left', 'top']]);

  Quad.mixins(['line', 'fill']);

  return Quad;

})(Glyph.Model);

module.exports = {
  Model: Quad,
  View: QuadView
};

},{"../../common/hittest":"common/hittest","../mappers/categorical_mapper":"models/mappers/categorical_mapper","./glyph":"models/glyphs/glyph","rbush":"rbush","underscore":"underscore"}],"models/glyphs/quadratic":[function(require,module,exports){
var Glyph, Quadratic, QuadraticView, _, _qbb, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

_qbb = function(u, v, w) {
  var bd, t;
  if (v === (u + w) / 2) {
    return [u, w];
  } else {
    t = (u - v) / (u - 2 * v + w);
    bd = u * Math.pow(1 - t, 2) + 2 * v * (1 - t) * t + w * Math.pow(t, 2);
    return [Math.min(u, w, bd), Math.max(u, w, bd)];
  }
};

QuadraticView = (function(superClass) {
  extend(QuadraticView, superClass);

  function QuadraticView() {
    return QuadraticView.__super__.constructor.apply(this, arguments);
  }

  QuadraticView.prototype._index_data = function() {
    var i, index, j, pts, ref, ref1, ref2, x0, x1, y0, y1;
    index = rbush();
    pts = [];
    for (i = j = 0, ref = this._x0.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (isNaN(this._x0[i] + this._x1[i] + this._y0[i] + this._y1[i] + this._cx[i] + this._cy[i])) {
        continue;
      }
      ref1 = _qbb(this._x0[i], this._cx[i], this._x1[i]), x0 = ref1[0], x1 = ref1[1];
      ref2 = _qbb(this._y0[i], this._cy[i], this._y1[i]), y0 = ref2[0], y1 = ref2[1];
      pts.push({
        minX: x0,
        minY: y0,
        maxX: x1,
        maxY: y1,
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  QuadraticView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, scx, scy, sx0, sx1, sy0, sy1;
    sx0 = arg.sx0, sy0 = arg.sy0, sx1 = arg.sx1, sy1 = arg.sy1, scx = arg.scx, scy = arg.scy;
    if (this.visuals.line.doit) {
      results = [];
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i] + scx[i] + scy[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.moveTo(sx0[i], sy0[i]);
        ctx.quadraticCurveTo(scx[i], scy[i], sx1[i], sy1[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  QuadraticView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return QuadraticView;

})(Glyph.View);

Quadratic = (function(superClass) {
  extend(Quadratic, superClass);

  function Quadratic() {
    return Quadratic.__super__.constructor.apply(this, arguments);
  }

  Quadratic.prototype.default_view = QuadraticView;

  Quadratic.prototype.type = 'Quadratic';

  Quadratic.coords([['x0', 'y0'], ['x1', 'y1'], ['cx', 'cy']]);

  Quadratic.mixins(['line']);

  return Quadratic;

})(Glyph.Model);

module.exports = {
  Model: Quadratic,
  View: QuadraticView
};

},{"./glyph":"models/glyphs/glyph","rbush":"rbush","underscore":"underscore"}],"models/glyphs/ray":[function(require,module,exports){
var Glyph, Ray, RayView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

p = require("../../core/properties");

RayView = (function(superClass) {
  extend(RayView, superClass);

  function RayView() {
    return RayView.__super__.constructor.apply(this, arguments);
  }

  RayView.prototype._index_data = function() {
    return this._xy_index();
  };

  RayView.prototype._map_data = function() {
    return this.slength = this.sdist(this.renderer.xmapper, this._x, this._length);
  };

  RayView.prototype._render = function(ctx, indices, arg) {
    var _angle, height, i, inf_len, j, k, len, ref, results, slength, sx, sy, width;
    sx = arg.sx, sy = arg.sy, slength = arg.slength, _angle = arg._angle;
    if (this.visuals.line.doit) {
      width = this.renderer.plot_view.frame.get('width');
      height = this.renderer.plot_view.frame.get('height');
      inf_len = 2 * (width + height);
      for (i = j = 0, ref = slength.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        if (slength[i] === 0) {
          slength[i] = inf_len;
        }
      }
      results = [];
      for (k = 0, len = indices.length; k < len; k++) {
        i = indices[k];
        if (isNaN(sx[i] + sy[i] + _angle[i] + slength[i])) {
          continue;
        }
        ctx.translate(sx[i], sy[i]);
        ctx.rotate(_angle[i]);
        ctx.beginPath();
        ctx.moveTo(0, 0);
        ctx.lineTo(slength[i], 0);
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
        ctx.rotate(-_angle[i]);
        results.push(ctx.translate(-sx[i], -sy[i]));
      }
      return results;
    }
  };

  RayView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return RayView;

})(Glyph.View);

Ray = (function(superClass) {
  extend(Ray, superClass);

  function Ray() {
    return Ray.__super__.constructor.apply(this, arguments);
  }

  Ray.prototype.default_view = RayView;

  Ray.prototype.type = 'Ray';

  Ray.coords([['x', 'y']]);

  Ray.mixins(['line']);

  Ray.define({
    length: [p.DistanceSpec],
    angle: [p.AngleSpec]
  });

  return Ray;

})(Glyph.Model);

module.exports = {
  Model: Ray,
  View: RayView
};

},{"../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/rect":[function(require,module,exports){
var Glyph, Rect, RectView, _, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

RectView = (function(superClass) {
  extend(RectView, superClass);

  function RectView() {
    return RectView.__super__.constructor.apply(this, arguments);
  }

  RectView.prototype._set_data = function() {
    this.max_w2 = 0;
    if (this.model.properties.width.units === "data") {
      this.max_w2 = this.max_width / 2;
    }
    this.max_h2 = 0;
    if (this.model.properties.height.units === "data") {
      return this.max_h2 = this.max_height / 2;
    }
  };

  RectView.prototype._index_data = function() {
    return this._xy_index();
  };

  RectView.prototype._map_data = function() {
    if (this.model.properties.width.units === "data") {
      this.sw = this.sdist(this.renderer.xmapper, this._x, this._width, 'center', this.mget('dilate'));
    } else {
      this.sw = this._width;
    }
    if (this.model.properties.height.units === "data") {
      return this.sh = this.sdist(this.renderer.ymapper, this._y, this._height, 'center', this.mget('dilate'));
    } else {
      return this.sh = this._height;
    }
  };

  RectView.prototype._render = function(ctx, indices, arg) {
    var _angle, i, j, k, len, len1, sh, sw, sx, sy;
    sx = arg.sx, sy = arg.sy, sw = arg.sw, sh = arg.sh, _angle = arg._angle;
    if (this.visuals.fill.doit) {
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (isNaN(sx[i] + sy[i] + sw[i] + sh[i] + _angle[i])) {
          continue;
        }
        this.visuals.fill.set_vectorize(ctx, i);
        if (_angle[i]) {
          ctx.translate(sx[i], sy[i]);
          ctx.rotate(_angle[i]);
          ctx.fillRect(-sw[i] / 2, -sh[i] / 2, sw[i], sh[i]);
          ctx.rotate(-_angle[i]);
          ctx.translate(-sx[i], -sy[i]);
        } else {
          ctx.fillRect(sx[i] - sw[i] / 2, sy[i] - sh[i] / 2, sw[i], sh[i]);
        }
      }
    }
    if (this.visuals.line.doit) {
      ctx.beginPath();
      for (k = 0, len1 = indices.length; k < len1; k++) {
        i = indices[k];
        if (isNaN(sx[i] + sy[i] + sw[i] + sh[i] + _angle[i])) {
          continue;
        }
        if (sw[i] === 0 || sh[i] === 0) {
          continue;
        }
        if (_angle[i]) {
          ctx.translate(sx[i], sy[i]);
          ctx.rotate(_angle[i]);
          ctx.rect(-sw[i] / 2, -sh[i] / 2, sw[i], sh[i]);
          ctx.rotate(-_angle[i]);
          ctx.translate(-sx[i], -sy[i]);
        } else {
          ctx.rect(sx[i] - sw[i] / 2, sy[i] - sh[i] / 2, sw[i], sh[i]);
        }
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
        ctx.beginPath();
      }
      return ctx.stroke();
    }
  };

  RectView.prototype._hit_rect = function(geometry) {
    var bbox, ref, ref1, result, x, x0, x1, y0, y1;
    ref = this.renderer.xmapper.v_map_from_target([geometry.vx0, geometry.vx1], true), x0 = ref[0], x1 = ref[1];
    ref1 = this.renderer.ymapper.v_map_from_target([geometry.vy0, geometry.vy1], true), y0 = ref1[0], y1 = ref1[1];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    result = hittest.create_hit_test_result();
    result['1d'].indices = (function() {
      var j, len, ref2, results;
      ref2 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
    return result;
  };

  RectView.prototype._hit_point = function(geometry) {
    var bbox, c, d, height_in, hits, i, j, len, pt, px, py, ref, ref1, ref2, ref3, result, s, sx, sy, vx, vx0, vx1, vy, vy0, vy1, width_in, x, x0, x1, y, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx, true);
    y = this.renderer.ymapper.map_from_target(vy, true);
    if (this.model.properties.width.units === "screen") {
      vx0 = vx - 2 * this.max_width;
      vx1 = vx + 2 * this.max_width;
      ref1 = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref1[0], x1 = ref1[1];
    } else {
      x0 = x - 2 * this.max_width;
      x1 = x + 2 * this.max_width;
    }
    if (this.model.properties.height.units === "screen") {
      vy0 = vy - 2 * this.max_height;
      vy1 = vy + 2 * this.max_height;
      ref2 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref2[0], y1 = ref2[1];
    } else {
      y0 = y - 2 * this.max_height;
      y1 = y + 2 * this.max_height;
    }
    hits = [];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    ref3 = (function() {
      var k, len, ref3, results;
      ref3 = this.index.search(bbox);
      results = [];
      for (k = 0, len = ref3.length; k < len; k++) {
        pt = ref3[k];
        results.push(pt.i);
      }
      return results;
    }).call(this);
    for (j = 0, len = ref3.length; j < len; j++) {
      i = ref3[j];
      sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
      sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
      if (this._angle[i]) {
        d = Math.sqrt(Math.pow(sx - this.sx[i], 2) + Math.pow(sy - this.sy[i], 2));
        s = Math.sin(-this._angle[i]);
        c = Math.cos(-this._angle[i]);
        px = c * (sx - this.sx[i]) - s * (sy - this.sy[i]) + this.sx[i];
        py = s * (sx - this.sx[i]) + c * (sy - this.sy[i]) + this.sy[i];
        sx = px;
        sy = py;
      }
      width_in = Math.abs(this.sx[i] - sx) <= this.sw[i] / 2;
      height_in = Math.abs(this.sy[i] - sy) <= this.sh[i] / 2;
      if (height_in && width_in) {
        hits.push(i);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  RectView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  RectView.prototype._bounds = function(bds) {
    return this.max_wh2_bounds(bds);
  };

  return RectView;

})(Glyph.View);

Rect = (function(superClass) {
  extend(Rect, superClass);

  function Rect() {
    return Rect.__super__.constructor.apply(this, arguments);
  }

  Rect.prototype.default_view = RectView;

  Rect.prototype.type = 'Rect';

  Rect.coords([['x', 'y']]);

  Rect.mixins(['line', 'fill']);

  Rect.define({
    angle: [p.AngleSpec, 0],
    width: [p.DistanceSpec],
    height: [p.DistanceSpec],
    dilate: [p.Bool, false]
  });

  return Rect;

})(Glyph.Model);

module.exports = {
  Model: Rect,
  View: RectView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/segment":[function(require,module,exports){
var Glyph, Segment, SegmentView, _, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Glyph = require("./glyph");

SegmentView = (function(superClass) {
  extend(SegmentView, superClass);

  function SegmentView() {
    return SegmentView.__super__.constructor.apply(this, arguments);
  }

  SegmentView.prototype._index_data = function() {
    var i, index, j, pts, ref;
    index = rbush();
    pts = [];
    for (i = j = 0, ref = this._x0.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      if (!isNaN(this._x0[i] + this._x1[i] + this._y0[i] + this._y1[i])) {
        pts.push({
          minX: Math.min(this._x0[i], this._x1[i]),
          minY: Math.min(this._y0[i], this._y1[i]),
          maxX: Math.max(this._x0[i], this._x1[i]),
          maxY: Math.max(this._y0[i], this._y1[i]),
          i: i
        });
      }
    }
    index.load(pts);
    return index;
  };

  SegmentView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sx0, sx1, sy0, sy1;
    sx0 = arg.sx0, sy0 = arg.sy0, sx1 = arg.sx1, sy1 = arg.sy1;
    if (this.visuals.line.doit) {
      results = [];
      for (j = 0, len = indices.length; j < len; j++) {
        i = indices[j];
        if (isNaN(sx0[i] + sy0[i] + sx1[i] + sy1[i])) {
          continue;
        }
        ctx.beginPath();
        ctx.moveTo(sx0[i], sy0[i]);
        ctx.lineTo(sx1[i], sy1[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      }
      return results;
    }
  };

  SegmentView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1);
  };

  return SegmentView;

})(Glyph.View);

Segment = (function(superClass) {
  extend(Segment, superClass);

  function Segment() {
    return Segment.__super__.constructor.apply(this, arguments);
  }

  Segment.prototype.default_view = SegmentView;

  Segment.prototype.type = 'Segment';

  Segment.coords([['x0', 'y0'], ['x1', 'y1']]);

  Segment.mixins(['line']);

  return Segment;

})(Glyph.Model);

module.exports = {
  Model: Segment,
  View: SegmentView
};

},{"./glyph":"models/glyphs/glyph","rbush":"rbush","underscore":"underscore"}],"models/glyphs/text":[function(require,module,exports){
var Glyph, Text, TextView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

p = require("../../core/properties");

TextView = (function(superClass) {
  extend(TextView, superClass);

  function TextView() {
    return TextView.__super__.constructor.apply(this, arguments);
  }

  TextView.prototype._index_data = function() {
    return this._xy_index();
  };

  TextView.prototype._render = function(ctx, indices, arg) {
    var _angle, _text, _x_offset, _y_offset, i, j, len, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _x_offset = arg._x_offset, _y_offset = arg._y_offset, _angle = arg._angle, _text = arg._text;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _x_offset[i] + _y_offset[i] + _angle[i]) || (_text[i] == null)) {
        continue;
      }
      if (this.visuals.text.doit) {
        ctx.save();
        ctx.translate(sx[i] + _x_offset[i], sy[i] + _y_offset[i]);
        ctx.rotate(_angle[i]);
        this.visuals.text.set_vectorize(ctx, i);
        ctx.fillText(_text[i], 0, 0);
        results.push(ctx.restore());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  TextView.prototype.draw_legend = function(ctx, x1, x2, y1, y2) {
    ctx.save();
    this.text_props.set_value(ctx);
    ctx.font = this.text_props.font_value();
    ctx.font = ctx.font.replace(/\b[\d\.]+[\w]+\b/, '10pt');
    ctx.textAlign = "right";
    ctx.textBaseline = "middle";
    ctx.fillText("text", x2, (y1 + y2) / 2);
    return ctx.restore();
  };

  return TextView;

})(Glyph.View);

Text = (function(superClass) {
  extend(Text, superClass);

  function Text() {
    return Text.__super__.constructor.apply(this, arguments);
  }

  Text.prototype.default_view = TextView;

  Text.prototype.type = 'Text';

  Text.coords([['x', 'y']]);

  Text.mixins(['text']);

  Text.define({
    text: [
      p.StringSpec, {
        field: "text"
      }
    ],
    angle: [p.AngleSpec, 0],
    x_offset: [p.NumberSpec, 0],
    y_offset: [p.NumberSpec, 0]
  });

  return Text;

})(Glyph.Model);

module.exports = {
  Model: Text,
  View: TextView
};

},{"../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/vbar":[function(require,module,exports){
var Glyph, Quad, VBar, VBarView, _, hittest, p, rbush,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

rbush = require("rbush");

Quad = require("./quad");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

VBarView = (function(superClass) {
  extend(VBarView, superClass);

  function VBarView() {
    return VBarView.__super__.constructor.apply(this, arguments);
  }

  VBarView.prototype._map_data = function() {
    var i, j, ref, vbottom, vtop;
    this.sx = this.renderer.xmapper.v_map_to_target(this._x);
    vtop = this.renderer.ymapper.v_map_to_target(this._top);
    vbottom = this.renderer.ymapper.v_map_to_target(this._bottom);
    this.stop = this.plot_view.canvas.v_vy_to_sy(vtop);
    this.sbottom = this.plot_view.canvas.v_vy_to_sy(vbottom);
    this.sleft = [];
    this.sright = [];
    this.sw = this.sdist(this.renderer.xmapper, this._x, this._width, 'center');
    for (i = j = 0, ref = this.sx.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      this.sleft.push(this.sx[i] - this.sw[i] / 2);
      this.sright.push(this.sx[i] + this.sw[i] / 2);
    }
    return null;
  };

  VBarView.prototype._render = function(ctx, indices, arg) {
    var i, j, len, results, sbottom, sleft, sright, stop;
    sleft = arg.sleft, sright = arg.sright, stop = arg.stop, sbottom = arg.sbottom;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sleft[i] + stop[i] + sright[i] + sbottom[i])) {
        continue;
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fillRect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i]);
      }
      if (this.visuals.line.doit) {
        ctx.beginPath();
        ctx.rect(sleft[i], stop[i], sright[i] - sleft[i], sbottom[i] - stop[i]);
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return VBarView;

})(Glyph.View);

VBar = (function(superClass) {
  extend(VBar, superClass);

  function VBar() {
    return VBar.__super__.constructor.apply(this, arguments);
  }

  VBar.prototype.default_view = VBarView;

  VBar.prototype.type = 'VBar';

  VBar.mixins(['line', 'fill']);

  VBar.define({
    x: [p.NumberSpec],
    width: [p.DistanceSpec],
    top: [p.NumberSpec],
    bottom: [p.NumberSpec, 0]
  });

  return VBar;

})(Glyph.Model);

module.exports = {
  Model: VBar,
  View: VBarView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","./glyph":"models/glyphs/glyph","./quad":"models/glyphs/quad","rbush":"rbush","underscore":"underscore"}],"models/glyphs/webgl/base":[function(require,module,exports){
var BaseGLGlyph, _, attach_color, attach_float, color, color2rgba, fill_array_with_float, fill_array_with_vec, line_width, visual_prop_is_singular;

_ = require("underscore");

color = require("../../../core/util/color");

color2rgba = color.color2rgba;

BaseGLGlyph = (function() {
  BaseGLGlyph.prototype.GLYPH = '';

  BaseGLGlyph.prototype.VERT = '';

  BaseGLGlyph.prototype.FRAG = '';

  function BaseGLGlyph(gl, glyph) {
    this.gl = gl;
    this.glyph = glyph;
    this.nvertices = 0;
    this.size_changed = false;
    this.data_changed = false;
    this.visuals_changed = false;
    this.init();
  }

  BaseGLGlyph.prototype.set_data_changed = function(n) {
    if (n !== this.nvertices) {
      this.nvertices = n;
      this.size_changed = true;
    }
    return this.data_changed = true;
  };

  BaseGLGlyph.prototype.set_visuals_changed = function() {
    return this.visuals_changed = true;
  };

  return BaseGLGlyph;

})();

line_width = function(width) {
  if (width < 2) {
    width = Math.sqrt(width * 2);
  }
  return width;
};

fill_array_with_float = function(n, val) {
  var a, i, k, ref;
  a = new Float32Array(n);
  for (i = k = 0, ref = n; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
    a[i] = val;
  }
  return a;
};

fill_array_with_vec = function(n, m, val) {
  var a, i, j, k, l, ref, ref1;
  a = new Float32Array(n * m);
  for (i = k = 0, ref = n; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
    for (j = l = 0, ref1 = m; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
      a[i * m + j] = val[j];
    }
  }
  return a;
};

visual_prop_is_singular = function(visual, propname) {
  return !_.isUndefined(visual[propname].spec.value);
};

attach_float = function(prog, vbo, att_name, n, visual, name) {
  var a;
  if (!visual.doit) {
    vbo.used = false;
    return prog.set_attribute(att_name, 'float', [0]);
  } else if (visual_prop_is_singular(visual, name)) {
    vbo.used = false;
    return prog.set_attribute(att_name, 'float', visual[name].value());
  } else {
    vbo.used = true;
    a = new Float32Array(visual.cache[name + '_array']);
    vbo.set_size(n * 4);
    vbo.set_data(0, a);
    return prog.set_attribute(att_name, 'float', vbo);
  }
};

attach_color = function(prog, vbo, att_name, n, visual, prefix) {
  var a, alphaname, alphas, colorname, colors, i, j, k, l, m, ref, ref1, rgba;
  m = 4;
  colorname = prefix + '_color';
  alphaname = prefix + '_alpha';
  if (!visual.doit) {
    vbo.used = false;
    return prog.set_attribute(att_name, 'vec4', [0, 0, 0, 0]);
  } else if (visual_prop_is_singular(visual, colorname) && visual_prop_is_singular(visual, alphaname)) {
    vbo.used = false;
    rgba = color2rgba(visual[colorname].value(), visual[alphaname].value());
    return prog.set_attribute(att_name, 'vec4', rgba);
  } else {
    vbo.used = true;
    if (visual_prop_is_singular(visual, colorname)) {
      colors = (function() {
        var k, ref, results;
        results = [];
        for (i = k = 0, ref = n; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
          results.push(visual[colorname].value());
        }
        return results;
      })();
    } else {
      colors = visual.cache[colorname + '_array'];
    }
    if (visual_prop_is_singular(visual, alphaname)) {
      alphas = fill_array_with_float(n, visual[alphaname].value());
    } else {
      alphas = visual.cache[alphaname + '_array'];
    }
    a = new Float32Array(n * m);
    for (i = k = 0, ref = n; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      rgba = color2rgba(colors[i], alphas[i]);
      for (j = l = 0, ref1 = m; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        a[i * m + j] = rgba[j];
      }
    }
    vbo.set_size(n * m * 4);
    vbo.set_data(0, a);
    return prog.set_attribute(att_name, 'vec4', vbo);
  }
};

module.exports = {
  BaseGLGlyph: BaseGLGlyph,
  line_width: line_width,
  attach_float: attach_float,
  attach_color: attach_color,
  color2rgba: color2rgba
};

},{"../../../core/util/color":"core/util/color","underscore":"underscore"}],"models/glyphs/webgl/line":[function(require,module,exports){
var BaseGLGlyph, DashAtlas, LineGLGlyph, attach_color, attach_float, color2rgba, gloo2, line_width, logger, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

gloo2 = require("gloo2");

logger = require("../../../core/logging").logger;

ref = require("./base"), BaseGLGlyph = ref.BaseGLGlyph, line_width = ref.line_width, attach_float = ref.attach_float, attach_color = ref.attach_color, color2rgba = ref.color2rgba;

DashAtlas = (function() {
  function DashAtlas(gl) {
    this._atlas = {};
    this._index = 0;
    this._width = 256;
    this._height = 256;
    this.tex = new gloo2.Texture2D(gl);
    this.tex.set_wrapping(gl.REPEAT, gl.REPEAT);
    this.tex.set_interpolation(gl.NEAREST, gl.NEAREST);
    this.tex.set_size([this._height, this._width], gl.RGBA);
    this.tex.set_data([0, 0], [this._height, this._width], new Uint8Array(this._height * this._width * 4));
    this.get_atlas_data([1]);
  }

  DashAtlas.prototype.get_atlas_data = function(pattern) {
    var data, findex_period, key, period, ref1, x;
    key = pattern.join('-');
    findex_period = this._atlas[key];
    if (findex_period === void 0) {
      ref1 = this.make_pattern(pattern), data = ref1[0], period = ref1[1];
      this.tex.set_data([this._index, 0], [1, this._width], new Uint8Array((function() {
        var l, len, results;
        results = [];
        for (l = 0, len = data.length; l < len; l++) {
          x = data[l];
          results.push(x + 10);
        }
        return results;
      })()));
      this._atlas[key] = [this._index / this._height, period];
      this._index += 1;
    }
    return this._atlas[key];
  };

  DashAtlas.prototype.make_pattern = function(pattern) {
    var C, Z, a, b, c, dash_end, dash_start, dash_type, i, index, j, l, len, n, p, period, q, r, ref1, ref2, ref3, v, val, val_at_index, x;
    if (pattern.length > 1 && pattern.length % 2) {
      pattern = pattern.concat(pattern);
    }
    period = 0;
    for (l = 0, len = pattern.length; l < len; l++) {
      v = pattern[l];
      period += v;
    }
    C = [];
    c = 0;
    for (i = p = 0, ref1 = pattern.length + 2; p < ref1; i = p += 2) {
      a = Math.max(0.0001, pattern[i % pattern.length]);
      b = Math.max(0.0001, pattern[(i + 1) % pattern.length]);
      C.push.apply(C, [c, c + a]);
      c += a + b;
    }
    n = this._width;
    Z = new Float32Array(n * 4);
    for (i = q = 0, ref2 = n; 0 <= ref2 ? q < ref2 : q > ref2; i = 0 <= ref2 ? ++q : --q) {
      x = period * i / (n - 1);
      index = 0;
      val_at_index = 1e16;
      for (j = r = 0, ref3 = C.length; 0 <= ref3 ? r < ref3 : r > ref3; j = 0 <= ref3 ? ++r : --r) {
        val = Math.abs(C[j] - x);
        if (val < val_at_index) {
          index = j;
          val_at_index = val;
        }
      }
      if (index % 2 === 0) {
        dash_type = x <= C[index] ? +1 : 0;
        dash_start = C[index];
        dash_end = C[index + 1];
      } else {
        dash_type = x > C[index] ? -1 : 0;
        dash_start = C[index - 1];
        dash_end = C[index];
      }
      Z[i * 4 + 0] = C[index];
      Z[i * 4 + 1] = dash_type;
      Z[i * 4 + 2] = dash_start;
      Z[i * 4 + 3] = dash_end;
    }
    return [Z, period];
  };

  return DashAtlas;

})();

LineGLGlyph = (function(superClass) {
  extend(LineGLGlyph, superClass);

  function LineGLGlyph() {
    return LineGLGlyph.__super__.constructor.apply(this, arguments);
  }

  LineGLGlyph.prototype.GLYPH = 'line';

  LineGLGlyph.prototype.JOINS = {
    'miter': 0,
    'round': 1,
    'bevel': 2
  };

  LineGLGlyph.prototype.CAPS = {
    '': 0,
    'none': 0,
    '.': 0,
    'round': 1,
    ')': 1,
    '(': 1,
    'o': 1,
    'triangle in': 2,
    '<': 2,
    'triangle out': 3,
    '>': 3,
    'square': 4,
    '[': 4,
    ']': 4,
    '=': 4,
    'butt': 5,
    '|': 5
  };

  LineGLGlyph.prototype.VERT = "precision mediump float;\n\nconst float PI = 3.14159265358979323846264;\nconst float THETA = 15.0 * 3.14159265358979323846264/180.0;\n\nuniform float u_pixel_ratio;\nuniform vec2 u_canvas_size, u_offset;\nuniform vec2 u_scale_aspect;\nuniform float u_scale_length;\n\nuniform vec4 u_color;\nuniform float u_antialias;\nuniform float u_length;\nuniform float u_linewidth;\nuniform float u_dash_index;\nuniform float u_closed;\n\nattribute vec2 a_position;\nattribute vec4 a_tangents;\nattribute vec2 a_segment;\nattribute vec2 a_angles;\nattribute vec2 a_texcoord;\n\nvarying vec4  v_color;\nvarying vec2  v_segment;\nvarying vec2  v_angles;\nvarying vec2  v_texcoord;\nvarying vec2  v_miter;\nvarying float v_length;\nvarying float v_linewidth;\n\nfloat cross(in vec2 v1, in vec2 v2)\n{\n    return v1.x*v2.y - v1.y*v2.x;\n}\n\nfloat signed_distance(in vec2 v1, in vec2 v2, in vec2 v3)\n{\n    return cross(v2-v1,v1-v3) / length(v2-v1);\n}\n\nvoid rotate( in vec2 v, in float alpha, out vec2 result )\n{\n    float c = cos(alpha);\n    float s = sin(alpha);\n    result = vec2( c*v.x - s*v.y,\n                   s*v.x + c*v.y );\n}\n\nvoid main()\n{\n    bool closed = (u_closed > 0.0);\n\n    // Attributes and uniforms to varyings\n    v_color = u_color;\n    v_linewidth = u_linewidth;\n    v_segment = a_segment * u_scale_length;\n    v_length = u_length * u_scale_length;\n\n    // Scale to map to pixel coordinates. The original algorithm from the paper\n    // assumed isotropic scale. We obviously do not have this.\n    vec2 abs_scale_aspect = abs(u_scale_aspect);\n    vec2 abs_scale = u_scale_length * abs_scale_aspect;\n\n    // Correct angles for aspect ratio\n    vec2 av;\n    av = vec2(1.0, tan(a_angles.x)) / abs_scale_aspect;\n    v_angles.x = atan(av.y, av.x);\n    av = vec2(1.0, tan(a_angles.y)) / abs_scale_aspect;\n    v_angles.y = atan(av.y, av.x);\n\n    // Thickness below 1 pixel are represented using a 1 pixel thickness\n    // and a modified alpha\n    v_color.a = min(v_linewidth, v_color.a);\n    v_linewidth = max(v_linewidth, 1.0);\n\n    // If color is fully transparent we just will discard the fragment anyway\n    if( v_color.a <= 0.0 ) {\n        gl_Position = vec4(0.0,0.0,0.0,1.0);\n        return;\n    }\n\n    // This is the actual half width of the line\n    float w = ceil(u_antialias+v_linewidth)/2.0;\n\n    vec2 position = (a_position + u_offset) * abs_scale;\n\n    vec2 t1 = normalize(a_tangents.xy * abs_scale_aspect);  // note the scaling for aspect ratio here\n    vec2 t2 = normalize(a_tangents.zw * abs_scale_aspect);\n    float u = a_texcoord.x;\n    float v = a_texcoord.y;\n    vec2 o1 = vec2( +t1.y, -t1.x);\n    vec2 o2 = vec2( +t2.y, -t2.x);\n\n    // This is a join\n    // ----------------------------------------------------------------\n    if( t1 != t2 ) {\n        float angle = atan (t1.x*t2.y-t1.y*t2.x, t1.x*t2.x+t1.y*t2.y);  // Angle needs recalculation for some reason\n        vec2 t  = normalize(t1+t2);\n        vec2 o  = vec2( + t.y, - t.x);\n\n        if ( u_dash_index > 0.0 )\n        {\n            // Broken angle\n            // ----------------------------------------------------------------\n            if( (abs(angle) > THETA) ) {\n                position += v * w * o / cos(angle/2.0);\n                float s = sign(angle);\n                if( angle < 0.0 ) {\n                    if( u == +1.0 ) {\n                        u = v_segment.y + v * w * tan(angle/2.0);\n                        if( v == 1.0 ) {\n                            position -= 2.0 * w * t1 / sin(angle);\n                            u -= 2.0 * w / sin(angle);\n                        }\n                    } else {\n                        u = v_segment.x - v * w * tan(angle/2.0);\n                        if( v == 1.0 ) {\n                            position += 2.0 * w * t2 / sin(angle);\n                            u += 2.0*w / sin(angle);\n                        }\n                    }\n                } else {\n                    if( u == +1.0 ) {\n                        u = v_segment.y + v * w * tan(angle/2.0);\n                        if( v == -1.0 ) {\n                            position += 2.0 * w * t1 / sin(angle);\n                            u += 2.0 * w / sin(angle);\n                        }\n                    } else {\n                        u = v_segment.x - v * w * tan(angle/2.0);\n                        if( v == -1.0 ) {\n                            position -= 2.0 * w * t2 / sin(angle);\n                            u -= 2.0*w / sin(angle);\n                        }\n                    }\n                }\n                // Continuous angle\n                // ------------------------------------------------------------\n            } else {\n                position += v * w * o / cos(angle/2.0);\n                if( u == +1.0 ) u = v_segment.y;\n                else            u = v_segment.x;\n            }\n        }\n\n        // Solid line\n        // --------------------------------------------------------------------\n        else\n        {\n            position.xy += v * w * o / cos(angle/2.0);\n            if( angle < 0.0 ) {\n                if( u == +1.0 ) {\n                    u = v_segment.y + v * w * tan(angle/2.0);\n                } else {\n                    u = v_segment.x - v * w * tan(angle/2.0);\n                }\n            } else {\n                if( u == +1.0 ) {\n                    u = v_segment.y + v * w * tan(angle/2.0);\n                } else {\n                    u = v_segment.x - v * w * tan(angle/2.0);\n                }\n            }\n        }\n\n    // This is a line start or end (t1 == t2)\n    // ------------------------------------------------------------------------\n    } else {\n        position += v * w * o1;\n        if( u == -1.0 ) {\n            u = v_segment.x - w;\n            position -= w * t1;\n        } else {\n            u = v_segment.y + w;\n            position += w * t2;\n        }\n    }\n\n    // Miter distance\n    // ------------------------------------------------------------------------\n    vec2 t;\n    vec2 curr = a_position * abs_scale;\n    if( a_texcoord.x < 0.0 ) {\n        vec2 next = curr + t2*(v_segment.y-v_segment.x);\n\n        rotate( t1, +v_angles.x/2.0, t);\n        v_miter.x = signed_distance(curr, curr+t, position);\n\n        rotate( t2, +v_angles.y/2.0, t);\n        v_miter.y = signed_distance(next, next+t, position);\n    } else {\n        vec2 prev = curr - t1*(v_segment.y-v_segment.x);\n\n        rotate( t1, -v_angles.x/2.0,t);\n        v_miter.x = signed_distance(prev, prev+t, position);\n\n        rotate( t2, -v_angles.y/2.0,t);\n        v_miter.y = signed_distance(curr, curr+t, position);\n    }\n\n    if (!closed && v_segment.x <= 0.0) {\n        v_miter.x = 1e10;\n    }\n    if (!closed && v_segment.y >= v_length)\n    {\n        v_miter.y = 1e10;\n    }\n\n    v_texcoord = vec2( u, v*w );\n\n    // Calculate position in device coordinates. Note that we\n    // already scaled with abs scale above.\n    vec2 normpos = position * sign(u_scale_aspect);\n    normpos += 0.5;  // make up for Bokeh's offset\n    normpos /= u_canvas_size / u_pixel_ratio;  // in 0..1\n    gl_Position = vec4(normpos*2.0-1.0, 0.0, 1.0);\n    gl_Position.y *= -1.0;\n}\n";

  LineGLGlyph.prototype.FRAG_ = "// Fragment shader that can be convenient during debugging to show the line skeleton.\nprecision mediump float;\nuniform vec4  u_color;\nvoid main () {\n  gl_FragColor = u_color;\n}";

  LineGLGlyph.prototype.FRAG = "precision mediump float;\n\nconst float PI = 3.14159265358979323846264;\nconst float THETA = 15.0 * 3.14159265358979323846264/180.0;\n\nuniform sampler2D u_dash_atlas;\n\nuniform vec2 u_linecaps;\nuniform float u_miter_limit;\nuniform float u_linejoin;\nuniform float u_antialias;\nuniform float u_dash_phase;\nuniform float u_dash_period;\nuniform float u_dash_index;\nuniform vec2 u_dash_caps;\nuniform float u_closed;\n\nvarying vec4  v_color;\nvarying vec2  v_segment;\nvarying vec2  v_angles;\nvarying vec2  v_texcoord;\nvarying vec2  v_miter;\nvarying float v_length;\nvarying float v_linewidth;\n\n// Compute distance to cap ----------------------------------------------------\nfloat cap( int type, float dx, float dy, float t, float linewidth )\n{\n    float d = 0.0;\n    dx = abs(dx);\n    dy = abs(dy);\n    if      (type == 0)  discard;  // None\n    else if (type == 1)  d = sqrt(dx*dx+dy*dy);  // Round\n    else if (type == 3)  d = (dx+abs(dy));  // Triangle in\n    else if (type == 2)  d = max(abs(dy),(t+dx-abs(dy)));  // Triangle out\n    else if (type == 4)  d = max(dx,dy);  // Square\n    else if (type == 5)  d = max(dx+t,dy);  // Butt\n    return d;\n}\n\n// Compute distance to join -------------------------------------------------\nfloat join( in int type, in float d, in vec2 segment, in vec2 texcoord, in vec2 miter,\n           in float linewidth )\n{\n    // texcoord.x is distance from start\n    // texcoord.y is distance from centerline\n    // segment.x and y indicate the limits (as for texcoord.x) for this segment\n\n    float dx = texcoord.x;\n\n    // Round join\n    if( type == 1 ) {\n        if (dx < segment.x) {\n            d = max(d,length( texcoord - vec2(segment.x,0.0)));\n            //d = length( texcoord - vec2(segment.x,0.0));\n        } else if (dx > segment.y) {\n            d = max(d,length( texcoord - vec2(segment.y,0.0)));\n            //d = length( texcoord - vec2(segment.y,0.0));\n        }\n    }\n    // Bevel join\n    else if ( type == 2 ) {\n        if (dx < segment.x) {\n            vec2 x = texcoord - vec2(segment.x,0.0);\n            d = max(d, max(abs(x.x), abs(x.y)));\n\n        } else if (dx > segment.y) {\n            vec2 x = texcoord - vec2(segment.y,0.0);\n            d = max(d, max(abs(x.x), abs(x.y)));\n        }\n        /*  Original code for bevel which does not work for us\n        if( (dx < segment.x) ||  (dx > segment.y) )\n            d = max(d, min(abs(x.x),abs(x.y)));\n        */\n    }\n\n    return d;\n}\n\nvoid main()\n{\n    // If color is fully transparent we just discard the fragment\n    if( v_color.a <= 0.0 ) {\n        discard;\n    }\n\n    // Test if dash pattern is the solid one (0)\n    bool solid =  (u_dash_index == 0.0);\n\n    // Test if path is closed\n    bool closed = (u_closed > 0.0);\n\n    vec4 color = v_color;\n    float dx = v_texcoord.x;\n    float dy = v_texcoord.y;\n    float t = v_linewidth/2.0-u_antialias;\n    float width = 1.0;  //v_linewidth; original code had dashes scale with line width, we do not\n    float d = 0.0;\n\n    vec2 linecaps = u_linecaps;\n    vec2 dash_caps = u_dash_caps;\n    float line_start = 0.0;\n    float line_stop = v_length;\n\n    // Apply miter limit; fragments too far into the miter are simply discarded\n    if( (dx < v_segment.x) || (dx > v_segment.y) ) {\n        float into_miter = max(v_segment.x - dx, dx - v_segment.y);\n        if (into_miter > u_miter_limit*v_linewidth/2.0)\n          discard;\n    }\n\n    // Solid line --------------------------------------------------------------\n    if( solid ) {\n        d = abs(dy);\n        if( (!closed) && (dx < line_start) ) {\n            d = cap( int(u_linecaps.x), abs(dx), abs(dy), t, v_linewidth );\n        }\n        else if( (!closed) &&  (dx > line_stop) ) {\n            d = cap( int(u_linecaps.y), abs(dx)-line_stop, abs(dy), t, v_linewidth );\n        }\n        else {\n            d = join( int(u_linejoin), abs(dy), v_segment, v_texcoord, v_miter, v_linewidth );\n        }\n\n    // Dash line --------------------------------------------------------------\n    } else {\n        float segment_start = v_segment.x;\n        float segment_stop  = v_segment.y;\n        float segment_center= (segment_start+segment_stop)/2.0;\n        float freq          = u_dash_period*width;\n        float u = mod( dx + u_dash_phase*width, freq);\n        vec4 tex = texture2D(u_dash_atlas, vec2(u/freq, u_dash_index)) * 255.0 -10.0;  // conversion to int-like\n        float dash_center= tex.x * width;\n        float dash_type  = tex.y;\n        float _start = tex.z * width;\n        float _stop  = tex.a * width;\n        float dash_start = dx - u + _start;\n        float dash_stop  = dx - u + _stop;\n\n        // Compute extents of the first dash (the one relative to v_segment.x)\n        // Note: this could be computed in the vertex shader\n        if( (dash_stop < segment_start) && (dash_caps.x != 5.0) ) {\n            float u = mod(segment_start + u_dash_phase*width, freq);\n            vec4 tex = texture2D(u_dash_atlas, vec2(u/freq, u_dash_index)) * 255.0 -10.0;  // conversion to int-like\n            dash_center= tex.x * width;\n            //dash_type  = tex.y;\n            float _start = tex.z * width;\n            float _stop  = tex.a * width;\n            dash_start = segment_start - u + _start;\n            dash_stop = segment_start - u + _stop;\n        }\n\n        // Compute extents of the last dash (the one relatives to v_segment.y)\n        // Note: This could be computed in the vertex shader\n        else if( (dash_start > segment_stop)  && (dash_caps.y != 5.0) ) {\n            float u = mod(segment_stop + u_dash_phase*width, freq);\n            vec4 tex = texture2D(u_dash_atlas, vec2(u/freq, u_dash_index)) * 255.0 -10.0;  // conversion to int-like\n            dash_center= tex.x * width;\n            //dash_type  = tex.y;\n            float _start = tex.z * width;\n            float _stop  = tex.a * width;\n            dash_start = segment_stop - u + _start;\n            dash_stop  = segment_stop - u + _stop;\n        }\n\n        // This test if the we are dealing with a discontinuous angle\n        bool discontinuous = ((dx <  segment_center) && abs(v_angles.x) > THETA) ||\n                             ((dx >= segment_center) && abs(v_angles.y) > THETA);\n        //if( dx < line_start) discontinuous = false;\n        //if( dx > line_stop)  discontinuous = false;\n\n        float d_join = join( int(u_linejoin), abs(dy),\n                            v_segment, v_texcoord, v_miter, v_linewidth );\n\n        // When path is closed, we do not have room for linecaps, so we make room\n        // by shortening the total length\n        if (closed) {\n             line_start += v_linewidth/2.0;\n             line_stop  -= v_linewidth/2.0;\n        }\n\n        // We also need to take antialias area into account\n        //line_start += u_antialias;\n        //line_stop  -= u_antialias;\n\n        // Check is dash stop is before line start\n        if( dash_stop <= line_start ) {\n            discard;\n        }\n        // Check is dash start is beyond line stop\n        if( dash_start >= line_stop ) {\n            discard;\n        }\n\n        // Check if current dash start is beyond segment stop\n        if( discontinuous ) {\n            // Dash start is beyond segment, we discard\n            if( (dash_start > segment_stop) ) {\n                discard;\n                //gl_FragColor = vec4(1.0,0.0,0.0,.25); return;\n            }\n\n            // Dash stop is before segment, we discard\n            if( (dash_stop < segment_start) ) {\n                discard;  //gl_FragColor = vec4(0.0,1.0,0.0,.25); return;\n            }\n\n            // Special case for round caps (nicer with this)\n            if( dash_caps.x == 1.0 ) {\n                if( (u > _stop) && (dash_stop > segment_stop )  && (abs(v_angles.y) < PI/2.0)) {\n                    discard;\n                }\n            }\n\n            // Special case for round caps  (nicer with this)\n            if( dash_caps.y == 1.0 ) {\n                if( (u < _start) && (dash_start < segment_start )  && (abs(v_angles.x) < PI/2.0)) {\n                    discard;\n                }\n            }\n\n            // Special case for triangle caps (in & out) and square\n            // We make sure the cap stop at crossing frontier\n            if( (dash_caps.x != 1.0) && (dash_caps.x != 5.0) ) {\n                if( (dash_start < segment_start )  && (abs(v_angles.x) < PI/2.0) ) {\n                    float a = v_angles.x/2.0;\n                    float x = (segment_start-dx)*cos(a) - dy*sin(a);\n                    float y = (segment_start-dx)*sin(a) + dy*cos(a);\n                    if( x > 0.0 ) discard;\n                    // We transform the cap into square to avoid holes\n                    dash_caps.x = 4.0;\n                }\n            }\n\n            // Special case for triangle caps (in & out) and square\n            // We make sure the cap stop at crossing frontier\n            if( (dash_caps.y != 1.0) && (dash_caps.y != 5.0) ) {\n                if( (dash_stop > segment_stop )  && (abs(v_angles.y) < PI/2.0) ) {\n                    float a = v_angles.y/2.0;\n                    float x = (dx-segment_stop)*cos(a) - dy*sin(a);\n                    float y = (dx-segment_stop)*sin(a) + dy*cos(a);\n                    if( x > 0.0 ) discard;\n                    // We transform the caps into square to avoid holes\n                    dash_caps.y = 4.0;\n                }\n            }\n        }\n\n        // Line cap at start\n        if( (dx < line_start) && (dash_start < line_start) && (dash_stop > line_start) ) {\n            d = cap( int(linecaps.x), dx-line_start, dy, t, v_linewidth);\n        }\n        // Line cap at stop\n        else if( (dx > line_stop) && (dash_stop > line_stop) && (dash_start < line_stop) ) {\n            d = cap( int(linecaps.y), dx-line_stop, dy, t, v_linewidth);\n        }\n        // Dash cap left - dash_type = -1, 0 or 1, but there may be roundoff errors\n        else if( dash_type < -0.5 ) {\n            d = cap( int(dash_caps.y), abs(u-dash_center), dy, t, v_linewidth);\n            if( (dx > line_start) && (dx < line_stop) )\n                d = max(d,d_join);\n        }\n        // Dash cap right\n        else if( dash_type > 0.5 ) {\n            d = cap( int(dash_caps.x), abs(dash_center-u), dy, t, v_linewidth);\n            if( (dx > line_start) && (dx < line_stop) )\n                d = max(d,d_join);\n        }\n        // Dash body (plain)\n        else {// if( dash_type > -0.5 &&  dash_type < 0.5) {\n            d = abs(dy);\n        }\n\n        // Line join\n        if( (dx > line_start) && (dx < line_stop)) {\n            if( (dx <= segment_start) && (dash_start <= segment_start)\n                && (dash_stop >= segment_start) ) {\n                d = d_join;\n                // Antialias at outer border\n                float angle = PI/2.+v_angles.x;\n                float f = abs( (segment_start - dx)*cos(angle) - dy*sin(angle));\n                d = max(f,d);\n            }\n            else if( (dx > segment_stop) && (dash_start <= segment_stop)\n                     && (dash_stop >= segment_stop) ) {\n                d = d_join;\n                // Antialias at outer border\n                float angle = PI/2.+v_angles.y;\n                float f = abs((dx - segment_stop)*cos(angle) - dy*sin(angle));\n                d = max(f,d);\n            }\n            else if( dx < (segment_start - v_linewidth/2.)) {\n                discard;\n            }\n            else if( dx > (segment_stop + v_linewidth/2.)) {\n                discard;\n            }\n        }\n        else if( dx < (segment_start - v_linewidth/2.)) {\n            discard;\n        }\n        else if( dx > (segment_stop + v_linewidth/2.)) {\n            discard;\n        }\n    }\n\n    // Distance to border ------------------------------------------------------\n    d = d - t;\n    if( d < 0.0 ) {\n        gl_FragColor = color;\n    } else {\n        d /= u_antialias;\n        gl_FragColor = vec4(color.rgb, exp(-d*d)*color.a);\n    }\n}";

  LineGLGlyph.prototype.init = function() {
    var gl;
    gl = this.gl;
    this._scale_aspect = 0;
    this.prog = new gloo2.Program(gl);
    this.prog.set_shaders(this.VERT, this.FRAG);
    this.index_buffer = new gloo2.IndexBuffer(gl);
    this.vbo_position = new gloo2.VertexBuffer(gl);
    this.vbo_tangents = new gloo2.VertexBuffer(gl);
    this.vbo_segment = new gloo2.VertexBuffer(gl);
    this.vbo_angles = new gloo2.VertexBuffer(gl);
    this.vbo_texcoord = new gloo2.VertexBuffer(gl);
    return this.dash_atlas = new DashAtlas(gl);
  };

  LineGLGlyph.prototype.draw = function(indices, mainGlyph, trans) {
    var baked_offset, chunk, chunks, chunksize, i, l, mainGlGlyph, nvertices, offset, p, q, ref1, ref2, ref3, results, scale_length, sx, sy, these_indices, uint16_index;
    mainGlGlyph = mainGlyph.glglyph;
    if (mainGlGlyph.data_changed) {
      if (!(isFinite(trans.dx) && isFinite(trans.dy))) {
        return;
      }
      mainGlGlyph._baked_offset = [trans.dx, trans.dy];
      mainGlGlyph._set_data();
      mainGlGlyph.data_changed = false;
    }
    if (this.visuals_changed) {
      this._set_visuals();
      this.visuals_changed = false;
    }
    sx = trans.sx;
    sy = trans.sy;
    scale_length = Math.sqrt(sx * sx + sy * sy);
    sx /= scale_length;
    sy /= scale_length;
    if (Math.abs(this._scale_aspect - (sy / sx)) > Math.abs(1e-3 * this._scale_aspect)) {
      mainGlGlyph._update_scale(sx, sy);
      this._scale_aspect = sy / sx;
    }
    this.prog.set_attribute('a_position', 'vec2', mainGlGlyph.vbo_position);
    this.prog.set_attribute('a_tangents', 'vec4', mainGlGlyph.vbo_tangents);
    this.prog.set_attribute('a_segment', 'vec2', mainGlGlyph.vbo_segment);
    this.prog.set_attribute('a_angles', 'vec2', mainGlGlyph.vbo_angles);
    this.prog.set_attribute('a_texcoord', 'vec2', mainGlGlyph.vbo_texcoord);
    this.prog.set_uniform('u_length', 'float', [mainGlGlyph.cumsum]);
    this.prog.set_texture('u_dash_atlas', this.dash_atlas.tex);
    baked_offset = mainGlGlyph._baked_offset;
    this.prog.set_uniform('u_pixel_ratio', 'float', [trans.pixel_ratio]);
    this.prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height]);
    this.prog.set_uniform('u_offset', 'vec2', [trans.dx - baked_offset[0], trans.dy - baked_offset[1]]);
    this.prog.set_uniform('u_scale_aspect', 'vec2', [sx, sy]);
    this.prog.set_uniform('u_scale_length', 'float', [scale_length]);
    this.I_triangles = mainGlGlyph.I_triangles;
    if (this.I_triangles.length < 65535) {
      this.index_buffer.set_size(this.I_triangles.length * 2);
      this.index_buffer.set_data(0, new Uint16Array(this.I_triangles));
      return this.prog.draw(this.gl.TRIANGLES, this.index_buffer);
    } else {
      indices = this.I_triangles;
      nvertices = this.I_triangles.length;
      chunksize = 64008;
      chunks = [];
      for (i = l = 0, ref1 = Math.ceil(nvertices / chunksize); 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {
        chunks.push([]);
      }
      for (i = p = 0, ref2 = indices.length; 0 <= ref2 ? p < ref2 : p > ref2; i = 0 <= ref2 ? ++p : --p) {
        uint16_index = indices[i] % chunksize;
        chunk = Math.floor(indices[i] / chunksize);
        chunks[chunk].push(uint16_index);
      }
      results = [];
      for (chunk = q = 0, ref3 = chunks.length; 0 <= ref3 ? q < ref3 : q > ref3; chunk = 0 <= ref3 ? ++q : --q) {
        these_indices = new Uint16Array(chunks[chunk]);
        offset = chunk * chunksize * 4;
        if (these_indices.length === 0) {
          continue;
        }
        this.prog.set_attribute('a_position', 'vec2', mainGlGlyph.vbo_position, 0, offset * 2);
        this.prog.set_attribute('a_tangents', 'vec4', mainGlGlyph.vbo_tangents, 0, offset * 4);
        this.prog.set_attribute('a_segment', 'vec2', mainGlGlyph.vbo_segment, 0, offset * 2);
        this.prog.set_attribute('a_angles', 'vec2', mainGlGlyph.vbo_angles, 0, offset * 2);
        this.prog.set_attribute('a_texcoord', 'vec2', mainGlGlyph.vbo_texcoord, 0, offset * 2);
        this.index_buffer.set_size(these_indices.length * 2);
        this.index_buffer.set_data(0, these_indices);
        results.push(this.prog.draw(this.gl.TRIANGLES, this.index_buffer));
      }
      return results;
    }
  };

  LineGLGlyph.prototype._set_data = function() {
    this._bake();
    this.vbo_position.set_size(this.V_position.length * 4);
    this.vbo_position.set_data(0, this.V_position);
    this.vbo_tangents.set_size(this.V_tangents.length * 4);
    this.vbo_tangents.set_data(0, this.V_tangents);
    this.vbo_angles.set_size(this.V_angles.length * 4);
    this.vbo_angles.set_data(0, this.V_angles);
    this.vbo_texcoord.set_size(this.V_texcoord.length * 4);
    return this.vbo_texcoord.set_data(0, this.V_texcoord);
  };

  LineGLGlyph.prototype._set_visuals = function() {
    var cap, color, dash_index, dash_pattern, dash_period, join, ref1;
    color = color2rgba(this.glyph.visuals.line.line_color.value(), this.glyph.visuals.line.line_alpha.value());
    cap = this.CAPS[this.glyph.visuals.line.line_cap.value()];
    join = this.JOINS[this.glyph.visuals.line.line_join.value()];
    this.prog.set_uniform('u_color', 'vec4', color);
    this.prog.set_uniform('u_linewidth', 'float', [this.glyph.visuals.line.line_width.value()]);
    this.prog.set_uniform('u_antialias', 'float', [0.9]);
    this.prog.set_uniform('u_linecaps', 'vec2', [cap, cap]);
    this.prog.set_uniform('u_linejoin', 'float', [join]);
    this.prog.set_uniform('u_miter_limit', 'float', [10.0]);
    dash_pattern = this.glyph.visuals.line.line_dash.value();
    dash_index = 0;
    dash_period = 1;
    if (dash_pattern.length) {
      ref1 = this.dash_atlas.get_atlas_data(dash_pattern), dash_index = ref1[0], dash_period = ref1[1];
    }
    this.prog.set_uniform('u_dash_index', 'float', [dash_index]);
    this.prog.set_uniform('u_dash_phase', 'float', [this.glyph.visuals.line.line_dash_offset.value()]);
    this.prog.set_uniform('u_dash_period', 'float', [dash_period]);
    this.prog.set_uniform('u_dash_caps', 'vec2', [cap, cap]);
    return this.prog.set_uniform('u_closed', 'float', [0]);
  };

  LineGLGlyph.prototype._bake = function() {
    var A, I, T, V_angles, V_angles2, V_position, V_position2, V_tangents, V_tangents2, V_texcoord, V_texcoord2, Vp, Vt, _x, _y, aa, i, j, k, l, m, n, ni, o, p, q, r, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, results, s, t, u, w, y, z;
    n = this.nvertices;
    _x = new Float64Array(this.glyph._x);
    _y = new Float64Array(this.glyph._y);
    V_position = Vp = new Float32Array(n * 2);
    V_angles = new Float32Array(n * 2);
    V_tangents = Vt = new Float32Array(n * 4);
    V_texcoord = new Float32Array(n * 2);
    for (i = l = 0, ref1 = n; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {
      V_position[i * 2 + 0] = _x[i] + this._baked_offset[0];
      V_position[i * 2 + 1] = _y[i] + this._baked_offset[1];
    }
    this.tangents = T = new Float32Array(n * 2 - 2);
    for (i = p = 0, ref2 = n - 1; 0 <= ref2 ? p < ref2 : p > ref2; i = 0 <= ref2 ? ++p : --p) {
      T[i * 2 + 0] = Vp[(i + 1) * 2 + 0] - Vp[i * 2 + 0];
      T[i * 2 + 1] = Vp[(i + 1) * 2 + 1] - Vp[i * 2 + 1];
    }
    for (i = q = 0, ref3 = n - 1; 0 <= ref3 ? q < ref3 : q > ref3; i = 0 <= ref3 ? ++q : --q) {
      V_tangents[(i + 1) * 4 + 0] = T[i * 2 + 0];
      V_tangents[(i + 1) * 4 + 1] = T[i * 2 + 1];
      V_tangents[i * 4 + 2] = T[i * 2 + 0];
      V_tangents[i * 4 + 3] = T[i * 2 + 1];
    }
    V_tangents[0 * 4 + 0] = T[0];
    V_tangents[0 * 4 + 1] = T[1];
    V_tangents[(n - 1) * 4 + 2] = T[(n - 2) * 2 + 0];
    V_tangents[(n - 1) * 4 + 3] = T[(n - 2) * 2 + 1];
    A = new Float32Array(n);
    for (i = r = 0, ref4 = n; 0 <= ref4 ? r < ref4 : r > ref4; i = 0 <= ref4 ? ++r : --r) {
      A[i] = Math.atan2(Vt[i * 4 + 0] * Vt[i * 4 + 3] - Vt[i * 4 + 1] * Vt[i * 4 + 2], Vt[i * 4 + 0] * Vt[i * 4 + 2] + Vt[i * 4 + 1] * Vt[i * 4 + 3]);
    }
    for (i = s = 0, ref5 = n - 1; 0 <= ref5 ? s < ref5 : s > ref5; i = 0 <= ref5 ? ++s : --s) {
      V_angles[i * 2 + 0] = A[i];
      V_angles[i * 2 + 1] = A[i + 1];
    }
    m = 4 * n - 4;
    this.V_position = V_position2 = new Float32Array(m * 2);
    this.V_angles = V_angles2 = new Float32Array(m * 2);
    this.V_tangents = V_tangents2 = new Float32Array(m * 4);
    this.V_texcoord = V_texcoord2 = new Float32Array(m * 2);
    o = 2;
    for (i = t = 0, ref6 = n; 0 <= ref6 ? t < ref6 : t > ref6; i = 0 <= ref6 ? ++t : --t) {
      for (j = u = 0; u < 4; j = ++u) {
        for (k = w = 0; w < 2; k = ++w) {
          V_position2[(i * 4 + j - o) * 2 + k] = V_position[i * 2 + k];
          V_angles2[(i * 4 + j) * 2 + k] = V_angles[i * 2 + k];
        }
        for (k = y = 0; y < 4; k = ++y) {
          V_tangents2[(i * 4 + j - o) * 4 + k] = V_tangents[i * 4 + k];
        }
      }
    }
    for (i = z = 0, ref7 = n; 0 <= ref7 ? z <= ref7 : z >= ref7; i = 0 <= ref7 ? ++z : --z) {
      V_texcoord2[(i * 4 + 0) * 2 + 0] = -1;
      V_texcoord2[(i * 4 + 1) * 2 + 0] = -1;
      V_texcoord2[(i * 4 + 2) * 2 + 0] = +1;
      V_texcoord2[(i * 4 + 3) * 2 + 0] = +1;
      V_texcoord2[(i * 4 + 0) * 2 + 1] = -1;
      V_texcoord2[(i * 4 + 1) * 2 + 1] = +1;
      V_texcoord2[(i * 4 + 2) * 2 + 1] = -1;
      V_texcoord2[(i * 4 + 3) * 2 + 1] = +1;
    }
    ni = (n - 1) * 6;
    this.I_triangles = I = new Uint32Array(ni);
    results = [];
    for (i = aa = 0, ref8 = n; 0 <= ref8 ? aa < ref8 : aa > ref8; i = 0 <= ref8 ? ++aa : --aa) {
      I[i * 6 + 0] = 0 + 4 * i;
      I[i * 6 + 1] = 1 + 4 * i;
      I[i * 6 + 2] = 3 + 4 * i;
      I[i * 6 + 3] = 2 + 4 * i;
      I[i * 6 + 4] = 0 + 4 * i;
      results.push(I[i * 6 + 5] = 3 + 4 * i);
    }
    return results;
  };

  LineGLGlyph.prototype._update_scale = function(sx, sy) {
    var N, T, V_segment, V_segment2, cumsum, i, j, k, l, m, n, p, q, r, ref1, ref2, ref3, s;
    n = this.nvertices;
    m = 4 * n - 4;
    T = this.tangents;
    N = new Float32Array(n - 1);
    V_segment = new Float32Array(n * 2);
    this.V_segment = V_segment2 = new Float32Array(m * 2);
    for (i = l = 0, ref1 = n - 1; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {
      N[i] = Math.sqrt(Math.pow(T[i * 2 + 0] * sx, 2) + Math.pow(T[i * 2 + 1] * sy, 2));
    }
    cumsum = 0;
    for (i = p = 0, ref2 = n - 1; 0 <= ref2 ? p < ref2 : p > ref2; i = 0 <= ref2 ? ++p : --p) {
      cumsum += N[i];
      V_segment[(i + 1) * 2 + 0] = cumsum;
      V_segment[i * 2 + 1] = cumsum;
    }
    for (i = q = 0, ref3 = n; 0 <= ref3 ? q < ref3 : q > ref3; i = 0 <= ref3 ? ++q : --q) {
      for (j = r = 0; r < 4; j = ++r) {
        for (k = s = 0; s < 2; k = ++s) {
          V_segment2[(i * 4 + j) * 2 + k] = V_segment[i * 2 + k];
        }
      }
    }
    this.cumsum = cumsum;
    this.vbo_segment.set_size(this.V_segment.length * 4);
    return this.vbo_segment.set_data(0, this.V_segment);
  };

  return LineGLGlyph;

})(BaseGLGlyph);

module.exports = {
  LineGLGlyph: LineGLGlyph
};

},{"../../../core/logging":"core/logging","./base":"models/glyphs/webgl/base","gloo2":"gloo2"}],"models/glyphs/webgl/main":[function(require,module,exports){
var line, markers;

line = require('./line');

markers = require('./markers');

module.exports = {
  LineGLGlyph: line.LineGLGlyph,
  CircleGLGlyph: markers.CircleGLGlyph,
  SquareGLGlyph: markers.SquareGLGlyph,
  AnnulusGLGlyph: markers.AnnulusGLGlyph,
  DiamondGLGlyph: markers.DiamondGLGlyph,
  TriangleGLGlyph: markers.TriangleGLGlyph,
  InvertedTriangleGLGlyph: markers.InvertedTriangleGLGlyph,
  CrossGLGlyph: markers.CrossGLGlyph,
  CircleCrossGLGlyph: markers.CircleCrossGLGlyph,
  SquareCrossGLGlyph: markers.SquareCrossGLGlyph,
  DiamondCrossGLGlyph: markers.DiamondCrossGLGlyph,
  XGLGlyph: markers.XGLGlyph,
  CircleXGLGlyph: markers.CircleXGLGlyph,
  SquareXGLGlyph: markers.SquareXGLGlyph,
  AsteriskGLGlyph: markers.AsteriskGLGlyph
};

},{"./line":"models/glyphs/webgl/line","./markers":"models/glyphs/webgl/markers"}],"models/glyphs/webgl/markers":[function(require,module,exports){
var AnnulusGLGlyph, AsteriskGLGlyph, BaseGLGlyph, CircleCrossGLGlyph, CircleGLGlyph, CircleXGLGlyph, CrossGLGlyph, DiamondCrossGLGlyph, DiamondGLGlyph, InvertedTriangleGLGlyph, MarkerGLGlyph, SquareCrossGLGlyph, SquareGLGlyph, SquareXGLGlyph, TriangleGLGlyph, XGLGlyph, attach_color, attach_float, gloo2, line_width, logger, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

gloo2 = require("gloo2");

logger = require("../../../core/logging").logger;

ref = require("./base"), BaseGLGlyph = ref.BaseGLGlyph, line_width = ref.line_width, attach_float = ref.attach_float, attach_color = ref.attach_color;

MarkerGLGlyph = (function(superClass) {
  extend(MarkerGLGlyph, superClass);

  function MarkerGLGlyph() {
    return MarkerGLGlyph.__super__.constructor.apply(this, arguments);
  }

  MarkerGLGlyph.prototype.VERT = "precision mediump float;\nconst float SQRT_2 = 1.4142135623730951;\n//\nuniform float u_pixel_ratio;\nuniform vec2 u_canvas_size;\nuniform vec2 u_offset;\nuniform vec2 u_scale;\nuniform float u_antialias;\n//\nattribute float a_x;\nattribute float a_y;\nattribute float a_size;\nattribute float a_angle;  // in radians\nattribute float a_linewidth;\nattribute vec4  a_fg_color;\nattribute vec4  a_bg_color;\n//\nvarying float v_linewidth;\nvarying float v_size;\nvarying vec4  v_fg_color;\nvarying vec4  v_bg_color;\nvarying vec2  v_rotation;\n\nvoid main (void)\n{\n    v_size = a_size * u_pixel_ratio;\n    v_linewidth = a_linewidth * u_pixel_ratio;\n    v_fg_color = a_fg_color;\n    v_bg_color = a_bg_color;\n    v_rotation = vec2(cos(-a_angle), sin(-a_angle));\n    // Calculate position - the -0.5 is to correct for canvas origin\n    vec2 pos = (vec2(a_x, a_y) + u_offset) * u_scale; // in pixels\n    pos += 0.5;  // make up for Bokeh's offset\n    pos /= u_canvas_size / u_pixel_ratio;  // in 0..1\n    gl_Position = vec4(pos*2.0-1.0, 0.0, 1.0);\n    gl_Position.y *= -1.0;\n    gl_PointSize = SQRT_2 * v_size + 2.0 * (v_linewidth + 1.5*u_antialias);\n}";

  MarkerGLGlyph.prototype.FRAG = "precision mediump float;\nconst float SQRT_2 = 1.4142135623730951;\nconst float PI = 3.14159265358979323846264;\n//\nuniform float u_antialias;\n//\nvarying vec4  v_fg_color;\nvarying vec4  v_bg_color;\nvarying float v_linewidth;\nvarying float v_size;\nvarying vec2  v_rotation;\n\nMARKERCODE\n\nvec4 outline(float distance, float linewidth, float antialias, vec4 fg_color, vec4 bg_color)\n{\n    vec4 frag_color;\n    float t = linewidth/2.0 - antialias;\n    float signed_distance = distance;\n    float border_distance = abs(signed_distance) - t;\n    float alpha = border_distance/antialias;\n    alpha = exp(-alpha*alpha);\n\n    // If fg alpha is zero, it probably means no outline. To avoid a dark outline\n    // shining through due to aa, we set the fg color to the bg color. Avoid if (i.e. branching).\n    float select = float(bool(fg_color.a));\n    fg_color.rgb = select * fg_color.rgb + (1.0  - select) * bg_color.rgb;\n    // Similarly, if we want a transparent bg\n    select = float(bool(bg_color.a));\n    bg_color.rgb = select * bg_color.rgb + (1.0  - select) * fg_color.rgb;\n\n    if( border_distance < 0.0)\n        frag_color = fg_color;\n    else if( signed_distance < 0.0 ) {\n        frag_color = mix(bg_color, fg_color, sqrt(alpha));\n    } else {\n        if( abs(signed_distance) < (linewidth/2.0 + antialias) ) {\n            frag_color = vec4(fg_color.rgb, fg_color.a * alpha);\n        } else {\n            discard;\n        }\n    }\n    return frag_color;\n}\n\nvoid main()\n{\n    vec2 P = gl_PointCoord.xy - vec2(0.5, 0.5);\n    P = vec2(v_rotation.x*P.x - v_rotation.y*P.y,\n             v_rotation.y*P.x + v_rotation.x*P.y);\n    float point_size = SQRT_2*v_size  + 2.0 * (v_linewidth + 1.5*u_antialias);\n    float distance = marker(P*point_size, v_size);\n    gl_FragColor = outline(distance, v_linewidth, u_antialias, v_fg_color, v_bg_color);\n    //gl_FragColor.rgb *= gl_FragColor.a;  // pre-multiply alpha\n}";

  MarkerGLGlyph.prototype.MARKERCODE = "<defined in subclasses>";

  MarkerGLGlyph.prototype.init = function() {
    var frag, gl;
    gl = this.gl;
    frag = this.FRAG.replace(/MARKERCODE/, this.MARKERCODE);
    this.last_trans = {};
    this.prog = new gloo2.Program(gl);
    this.prog.set_shaders(this.VERT, frag);
    this.vbo_x = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_x', 'float', this.vbo_x);
    this.vbo_y = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_y', 'float', this.vbo_y);
    this.vbo_s = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_size', 'float', this.vbo_s);
    this.vbo_a = new gloo2.VertexBuffer(gl);
    this.prog.set_attribute('a_angle', 'float', this.vbo_a);
    this.vbo_linewidth = new gloo2.VertexBuffer(gl);
    this.vbo_fg_color = new gloo2.VertexBuffer(gl);
    this.vbo_bg_color = new gloo2.VertexBuffer(gl);
    return this.index_buffer = new gloo2.IndexBuffer(gl);
  };

  MarkerGLGlyph.prototype.draw = function(indices, mainGlyph, trans) {
    var baked_offset, chunk, chunks, chunksize, i, j, k, l, mainGlGlyph, nvertices, offset, ref1, ref2, ref3, results, s, these_indices, ua, uint16_index;
    mainGlGlyph = mainGlyph.glglyph;
    nvertices = mainGlGlyph.nvertices;
    if (mainGlGlyph.data_changed) {
      if (!(isFinite(trans.dx) && isFinite(trans.dy))) {
        return;
      }
      mainGlGlyph._baked_offset = [trans.dx, trans.dy];
      mainGlGlyph._set_data(nvertices);
      mainGlGlyph.data_changed = false;
    } else if ((this.glyph._radius != null) && (trans.sx !== this.last_trans.sx || trans.sy !== this.last_trans.sy)) {
      this.last_trans = trans;
      this.vbo_s.set_data(0, new Float32Array((function() {
        var j, len, ref1, results;
        ref1 = this.glyph.sradius;
        results = [];
        for (j = 0, len = ref1.length; j < len; j++) {
          s = ref1[j];
          results.push(s * 2);
        }
        return results;
      }).call(this)));
    }
    if (this.visuals_changed) {
      this._set_visuals(nvertices);
      this.visuals_changed = false;
    }
    baked_offset = mainGlGlyph._baked_offset;
    this.prog.set_uniform('u_pixel_ratio', 'float', [trans.pixel_ratio]);
    this.prog.set_uniform('u_canvas_size', 'vec2', [trans.width, trans.height]);
    this.prog.set_uniform('u_offset', 'vec2', [trans.dx - baked_offset[0], trans.dy - baked_offset[1]]);
    this.prog.set_uniform('u_scale', 'vec2', [trans.sx, trans.sy]);
    this.prog.set_attribute('a_x', 'float', mainGlGlyph.vbo_x);
    this.prog.set_attribute('a_y', 'float', mainGlGlyph.vbo_y);
    this.prog.set_attribute('a_size', 'float', mainGlGlyph.vbo_s);
    this.prog.set_attribute('a_angle', 'float', mainGlGlyph.vbo_a);
    if (indices.length === 0) {

    } else if (indices.length === nvertices) {
      return this.prog.draw(this.gl.POINTS, [0, nvertices]);
    } else if (nvertices < 65535) {
      ua = window.navigator.userAgent;
      if (ua.indexOf("MSIE ") + ua.indexOf("Trident/") + ua.indexOf("Edge/") > 0) {
        logger.warn('WebGL warning: IE is known to produce 1px sprites whith selections.');
      }
      this.index_buffer.set_size(indices.length * 2);
      this.index_buffer.set_data(0, new Uint16Array(indices));
      return this.prog.draw(this.gl.POINTS, this.index_buffer);
    } else {
      chunksize = 64000;
      chunks = [];
      for (i = j = 0, ref1 = Math.ceil(nvertices / chunksize); 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
        chunks.push([]);
      }
      for (i = k = 0, ref2 = indices.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) {
        uint16_index = indices[i] % chunksize;
        chunk = Math.floor(indices[i] / chunksize);
        chunks[chunk].push(uint16_index);
      }
      results = [];
      for (chunk = l = 0, ref3 = chunks.length; 0 <= ref3 ? l < ref3 : l > ref3; chunk = 0 <= ref3 ? ++l : --l) {
        these_indices = new Uint16Array(chunks[chunk]);
        offset = chunk * chunksize * 4;
        if (these_indices.length === 0) {
          continue;
        }
        this.prog.set_attribute('a_x', 'float', mainGlGlyph.vbo_x, 0, offset);
        this.prog.set_attribute('a_y', 'float', mainGlGlyph.vbo_y, 0, offset);
        this.prog.set_attribute('a_size', 'float', mainGlGlyph.vbo_s, 0, offset);
        this.prog.set_attribute('a_angle', 'float', mainGlGlyph.vbo_a, 0, offset);
        if (this.vbo_linewidth.used) {
          this.prog.set_attribute('a_linewidth', 'float', this.vbo_linewidth, 0, offset);
        }
        if (this.vbo_fg_color.used) {
          this.prog.set_attribute('a_fg_color', 'vec4', this.vbo_fg_color, 0, offset * 4);
        }
        if (this.vbo_bg_color.used) {
          this.prog.set_attribute('a_bg_color', 'vec4', this.vbo_bg_color, 0, offset * 4);
        }
        this.index_buffer.set_size(these_indices.length * 2);
        this.index_buffer.set_data(0, these_indices);
        results.push(this.prog.draw(this.gl.POINTS, this.index_buffer));
      }
      return results;
    }
  };

  MarkerGLGlyph.prototype._set_data = function(nvertices) {
    var i, j, n, ref1, s, xx, yy;
    n = nvertices * 4;
    this.vbo_x.set_size(n);
    this.vbo_y.set_size(n);
    this.vbo_a.set_size(n);
    this.vbo_s.set_size(n);
    xx = new Float64Array(this.glyph._x);
    yy = new Float64Array(this.glyph._y);
    for (i = j = 0, ref1 = nvertices; 0 <= ref1 ? j < ref1 : j > ref1; i = 0 <= ref1 ? ++j : --j) {
      xx[i] += this._baked_offset[0];
      yy[i] += this._baked_offset[1];
    }
    this.vbo_x.set_data(0, new Float32Array(xx));
    this.vbo_y.set_data(0, new Float32Array(yy));
    if (this.glyph._angle != null) {
      this.vbo_a.set_data(0, new Float32Array(this.glyph._angle));
    }
    if (this.glyph._radius != null) {
      return this.vbo_s.set_data(0, new Float32Array((function() {
        var k, len, ref2, results;
        ref2 = this.glyph.sradius;
        results = [];
        for (k = 0, len = ref2.length; k < len; k++) {
          s = ref2[k];
          results.push(s * 2);
        }
        return results;
      }).call(this)));
    } else {
      return this.vbo_s.set_data(0, new Float32Array(this.glyph._size));
    }
  };

  MarkerGLGlyph.prototype._set_visuals = function(nvertices) {
    attach_float(this.prog, this.vbo_linewidth, 'a_linewidth', nvertices, this.glyph.visuals.line, 'line_width');
    attach_color(this.prog, this.vbo_fg_color, 'a_fg_color', nvertices, this.glyph.visuals.line, 'line');
    attach_color(this.prog, this.vbo_bg_color, 'a_bg_color', nvertices, this.glyph.visuals.fill, 'fill');
    return this.prog.set_uniform('u_antialias', 'float', [0.8]);
  };

  return MarkerGLGlyph;

})(BaseGLGlyph);

CircleGLGlyph = (function(superClass) {
  extend(CircleGLGlyph, superClass);

  function CircleGLGlyph() {
    return CircleGLGlyph.__super__.constructor.apply(this, arguments);
  }

  CircleGLGlyph.prototype.GLYPH = 'circle';

  CircleGLGlyph.prototype.MARKERCODE = "// --- disc\nfloat marker(vec2 P, float size)\n{\n    return length(P) - size/2.0;\n}";

  return CircleGLGlyph;

})(MarkerGLGlyph);

SquareGLGlyph = (function(superClass) {
  extend(SquareGLGlyph, superClass);

  function SquareGLGlyph() {
    return SquareGLGlyph.__super__.constructor.apply(this, arguments);
  }

  SquareGLGlyph.prototype.GLYPH = 'square';

  SquareGLGlyph.prototype.MARKERCODE = "// --- square\nfloat marker(vec2 P, float size)\n{\n    return max(abs(P.x), abs(P.y)) - size/2.0;\n}";

  return SquareGLGlyph;

})(MarkerGLGlyph);

AnnulusGLGlyph = (function(superClass) {
  extend(AnnulusGLGlyph, superClass);

  function AnnulusGLGlyph() {
    return AnnulusGLGlyph.__super__.constructor.apply(this, arguments);
  }

  AnnulusGLGlyph.prototype.GLYPH = 'annulus';

  AnnulusGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    float r1 = length(P) - size/2.0;\n    float r2 = length(P) - size/4.0;  // half width\n    return max(r1, -r2);\n}";

  return AnnulusGLGlyph;

})(MarkerGLGlyph);

DiamondGLGlyph = (function(superClass) {
  extend(DiamondGLGlyph, superClass);

  function DiamondGLGlyph() {
    return DiamondGLGlyph.__super__.constructor.apply(this, arguments);
  }

  DiamondGLGlyph.prototype.GLYPH = 'diamond';

  DiamondGLGlyph.prototype.MARKERCODE = "// --- diamond\nfloat marker(vec2 P, float size)\n{\n    float x = SQRT_2 / 2.0 * (P.x * 1.5 - P.y);\n    float y = SQRT_2 / 2.0 * (P.x * 1.5 + P.y);\n    float r1 = max(abs(x), abs(y)) - size / (2.0 * SQRT_2);\n    return r1 / SQRT_2;\n}";

  return DiamondGLGlyph;

})(MarkerGLGlyph);

TriangleGLGlyph = (function(superClass) {
  extend(TriangleGLGlyph, superClass);

  function TriangleGLGlyph() {
    return TriangleGLGlyph.__super__.constructor.apply(this, arguments);
  }

  TriangleGLGlyph.prototype.GLYPH = 'triangle';

  TriangleGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    P.y -= size * 0.3;\n    float x = SQRT_2 / 2.0 * (P.x * 1.7 - P.y);\n    float y = SQRT_2 / 2.0 * (P.x * 1.7 + P.y);\n    float r1 = max(abs(x), abs(y)) - size / 1.6;\n    float r2 = P.y;\n    return max(r1 / SQRT_2, r2);  // Instersect diamond with rectangle\n}";

  return TriangleGLGlyph;

})(MarkerGLGlyph);

InvertedTriangleGLGlyph = (function(superClass) {
  extend(InvertedTriangleGLGlyph, superClass);

  function InvertedTriangleGLGlyph() {
    return InvertedTriangleGLGlyph.__super__.constructor.apply(this, arguments);
  }

  InvertedTriangleGLGlyph.prototype.GLYPH = 'invertedtriangle';

  InvertedTriangleGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    P.y += size * 0.3;\n    float x = SQRT_2 / 2.0 * (P.x * 1.7 - P.y);\n    float y = SQRT_2 / 2.0 * (P.x * 1.7 + P.y);\n    float r1 = max(abs(x), abs(y)) - size / 1.6;\n    float r2 = - P.y;\n    return max(r1 / SQRT_2, r2);  // Instersect diamond with rectangle\n}";

  return InvertedTriangleGLGlyph;

})(MarkerGLGlyph);

CrossGLGlyph = (function(superClass) {
  extend(CrossGLGlyph, superClass);

  function CrossGLGlyph() {
    return CrossGLGlyph.__super__.constructor.apply(this, arguments);
  }

  CrossGLGlyph.prototype.GLYPH = 'cross';

  CrossGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    float square = max(abs(P.x), abs(P.y)) - size / 2.5;  // 2.5 is a tweak\n    float cross = min(abs(P.x), abs(P.y)) - size / 100.0;  // bit of \"width\" for aa\n    return max(square, cross);\n}";

  return CrossGLGlyph;

})(MarkerGLGlyph);

CircleCrossGLGlyph = (function(superClass) {
  extend(CircleCrossGLGlyph, superClass);

  function CircleCrossGLGlyph() {
    return CircleCrossGLGlyph.__super__.constructor.apply(this, arguments);
  }

  CircleCrossGLGlyph.prototype.GLYPH = 'circlecross';

  CircleCrossGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    // Define quadrants\n    float qs = size / 2.0;  // quadrant size\n    float s1 = max(abs(P.x - qs), abs(P.y - qs)) - qs;\n    float s2 = max(abs(P.x + qs), abs(P.y - qs)) - qs;\n    float s3 = max(abs(P.x - qs), abs(P.y + qs)) - qs;\n    float s4 = max(abs(P.x + qs), abs(P.y + qs)) - qs;\n    // Intersect main shape with quadrants (to form cross)\n    float circle = length(P) - size/2.0;\n    float c1 = max(circle, s1);\n    float c2 = max(circle, s2);\n    float c3 = max(circle, s3);\n    float c4 = max(circle, s4);\n    // Union\n    return min(min(min(c1, c2), c3), c4);\n}";

  return CircleCrossGLGlyph;

})(MarkerGLGlyph);

SquareCrossGLGlyph = (function(superClass) {
  extend(SquareCrossGLGlyph, superClass);

  function SquareCrossGLGlyph() {
    return SquareCrossGLGlyph.__super__.constructor.apply(this, arguments);
  }

  SquareCrossGLGlyph.prototype.GLYPH = 'squarecross';

  SquareCrossGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    // Define quadrants\n    float qs = size / 2.0;  // quadrant size\n    float s1 = max(abs(P.x - qs), abs(P.y - qs)) - qs;\n    float s2 = max(abs(P.x + qs), abs(P.y - qs)) - qs;\n    float s3 = max(abs(P.x - qs), abs(P.y + qs)) - qs;\n    float s4 = max(abs(P.x + qs), abs(P.y + qs)) - qs;\n    // Intersect main shape with quadrants (to form cross)\n    float square = max(abs(P.x), abs(P.y)) - size/2.0;\n    float c1 = max(square, s1);\n    float c2 = max(square, s2);\n    float c3 = max(square, s3);\n    float c4 = max(square, s4);\n    // Union\n    return min(min(min(c1, c2), c3), c4);\n}";

  return SquareCrossGLGlyph;

})(MarkerGLGlyph);

DiamondCrossGLGlyph = (function(superClass) {
  extend(DiamondCrossGLGlyph, superClass);

  function DiamondCrossGLGlyph() {
    return DiamondCrossGLGlyph.__super__.constructor.apply(this, arguments);
  }

  DiamondCrossGLGlyph.prototype.GLYPH = 'diamondcross';

  DiamondCrossGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    // Define quadrants\n    float qs = size / 2.0;  // quadrant size\n    float s1 = max(abs(P.x - qs), abs(P.y - qs)) - qs;\n    float s2 = max(abs(P.x + qs), abs(P.y - qs)) - qs;\n    float s3 = max(abs(P.x - qs), abs(P.y + qs)) - qs;\n    float s4 = max(abs(P.x + qs), abs(P.y + qs)) - qs;\n    // Intersect main shape with quadrants (to form cross)\n    float x = SQRT_2 / 2.0 * (P.x * 1.5 - P.y);\n    float y = SQRT_2 / 2.0 * (P.x * 1.5 + P.y);\n    float diamond = max(abs(x), abs(y)) - size / (2.0 * SQRT_2);\n    diamond /= SQRT_2;\n    float c1 = max(diamond, s1);\n    float c2 = max(diamond, s2);\n    float c3 = max(diamond, s3);\n    float c4 = max(diamond, s4);\n    // Union\n    return min(min(min(c1, c2), c3), c4);\n}";

  return DiamondCrossGLGlyph;

})(MarkerGLGlyph);

XGLGlyph = (function(superClass) {
  extend(XGLGlyph, superClass);

  function XGLGlyph() {
    return XGLGlyph.__super__.constructor.apply(this, arguments);
  }

  XGLGlyph.prototype.GLYPH = 'x';

  XGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    float circle = length(P) - size / 1.6;\n    float X = min(abs(P.x - P.y), abs(P.x + P.y)) - size / 100.0;  // bit of \"width\" for aa\n    return max(circle, X);\n}";

  return XGLGlyph;

})(MarkerGLGlyph);

CircleXGLGlyph = (function(superClass) {
  extend(CircleXGLGlyph, superClass);

  function CircleXGLGlyph() {
    return CircleXGLGlyph.__super__.constructor.apply(this, arguments);
  }

  CircleXGLGlyph.prototype.GLYPH = 'circlex';

  CircleXGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    float x = P.x - P.y;\n    float y = P.x + P.y;\n    // Define quadrants\n    float qs = size / 2.0;  // quadrant size\n    float s1 = max(abs(x - qs), abs(y - qs)) - qs;\n    float s2 = max(abs(x + qs), abs(y - qs)) - qs;\n    float s3 = max(abs(x - qs), abs(y + qs)) - qs;\n    float s4 = max(abs(x + qs), abs(y + qs)) - qs;\n    // Intersect main shape with quadrants (to form cross)\n    float circle = length(P) - size/2.0;\n    float c1 = max(circle, s1);\n    float c2 = max(circle, s2);\n    float c3 = max(circle, s3);\n    float c4 = max(circle, s4);\n    // Union\n    float almost = min(min(min(c1, c2), c3), c4);\n    // In this case, the X is also outside of the main shape\n    float Xmask = length(P) - size / 1.6;  // a circle\n    float X = min(abs(P.x - P.y), abs(P.x + P.y)) - size / 100.0;  // bit of \"width\" for aa\n    return min(max(X, Xmask), almost);\n}";

  return CircleXGLGlyph;

})(MarkerGLGlyph);

SquareXGLGlyph = (function(superClass) {
  extend(SquareXGLGlyph, superClass);

  function SquareXGLGlyph() {
    return SquareXGLGlyph.__super__.constructor.apply(this, arguments);
  }

  SquareXGLGlyph.prototype.GLYPH = 'squarex';

  SquareXGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    float x = P.x - P.y;\n    float y = P.x + P.y;\n    // Define quadrants\n    float qs = size / 2.0;  // quadrant size\n    float s1 = max(abs(x - qs), abs(y - qs)) - qs;\n    float s2 = max(abs(x + qs), abs(y - qs)) - qs;\n    float s3 = max(abs(x - qs), abs(y + qs)) - qs;\n    float s4 = max(abs(x + qs), abs(y + qs)) - qs;\n    // Intersect main shape with quadrants (to form cross)\n    float square = max(abs(P.x), abs(P.y)) - size/2.0;\n    float c1 = max(square, s1);\n    float c2 = max(square, s2);\n    float c3 = max(square, s3);\n    float c4 = max(square, s4);\n    // Union\n    return min(min(min(c1, c2), c3), c4);\n}";

  return SquareXGLGlyph;

})(MarkerGLGlyph);

AsteriskGLGlyph = (function(superClass) {
  extend(AsteriskGLGlyph, superClass);

  function AsteriskGLGlyph() {
    return AsteriskGLGlyph.__super__.constructor.apply(this, arguments);
  }

  AsteriskGLGlyph.prototype.GLYPH = 'asterisk';

  AsteriskGLGlyph.prototype.MARKERCODE = "float marker(vec2 P, float size)\n{\n    // Masks\n    float diamond = max(abs(SQRT_2 / 2.0 * (P.x - P.y)), abs(SQRT_2 / 2.0 * (P.x + P.y))) - size / (2.0 * SQRT_2);\n    float square = max(abs(P.x), abs(P.y)) - size / (2.0 * SQRT_2);\n    // Shapes\n    float X = min(abs(P.x - P.y), abs(P.x + P.y)) - size / 100.0;  // bit of \"width\" for aa\n    float cross = min(abs(P.x), abs(P.y)) - size / 100.0;  // bit of \"width\" for aa\n    // Result is union of masked shapes\n    return min(max(X, diamond), max(cross, square));\n}";

  return AsteriskGLGlyph;

})(MarkerGLGlyph);

module.exports = {
  CircleGLGlyph: CircleGLGlyph,
  SquareGLGlyph: SquareGLGlyph,
  AnnulusGLGlyph: AnnulusGLGlyph,
  DiamondGLGlyph: DiamondGLGlyph,
  TriangleGLGlyph: TriangleGLGlyph,
  InvertedTriangleGLGlyph: InvertedTriangleGLGlyph,
  CrossGLGlyph: CrossGLGlyph,
  CircleCrossGLGlyph: CircleCrossGLGlyph,
  SquareCrossGLGlyph: SquareCrossGLGlyph,
  DiamondCrossGLGlyph: DiamondCrossGLGlyph,
  XGLGlyph: XGLGlyph,
  CircleXGLGlyph: CircleXGLGlyph,
  SquareXGLGlyph: SquareXGLGlyph,
  AsteriskGLGlyph: AsteriskGLGlyph
};

},{"../../../core/logging":"core/logging","./base":"models/glyphs/webgl/base","gloo2":"gloo2"}],"models/glyphs/wedge":[function(require,module,exports){
var Glyph, Wedge, WedgeView, _, angle_between, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("./glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

angle_between = require("../../core/util/math").angle_between;

WedgeView = (function(superClass) {
  extend(WedgeView, superClass);

  function WedgeView() {
    return WedgeView.__super__.constructor.apply(this, arguments);
  }

  WedgeView.prototype._index_data = function() {
    return this._xy_index();
  };

  WedgeView.prototype._map_data = function() {
    if (this.model.properties.radius.units === "data") {
      return this.sradius = this.sdist(this.renderer.xmapper, this._x, this._radius);
    } else {
      return this.sradius = this._radius;
    }
  };

  WedgeView.prototype._render = function(ctx, indices, arg) {
    var _end_angle, _start_angle, direction, i, j, len, results, sradius, sx, sy;
    sx = arg.sx, sy = arg.sy, sradius = arg.sradius, _start_angle = arg._start_angle, _end_angle = arg._end_angle;
    direction = this.model.properties.direction.value();
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + sradius[i] + _start_angle[i] + _end_angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.arc(sx[i], sy[i], sradius[i], _start_angle[i], _end_angle[i], direction);
      ctx.lineTo(sx[i], sy[i]);
      ctx.closePath();
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  WedgeView.prototype._hit_point = function(geometry) {
    var angle, bbox, candidates, direction, dist, hits, i, j, k, len, len1, pt, r2, ref, ref1, ref2, ref3, ref4, result, sx, sx0, sx1, sy, sy0, sy1, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    x = this.renderer.xmapper.map_from_target(vx, true);
    y = this.renderer.ymapper.map_from_target(vy, true);
    if (this.model.properties.radius.units === "data") {
      x0 = x - this.max_radius;
      x1 = x + this.max_radius;
      y0 = y - this.max_radius;
      y1 = y + this.max_radius;
    } else {
      vx0 = vx - this.max_radius;
      vx1 = vx + this.max_radius;
      ref1 = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref1[0], x1 = ref1[1];
      vy0 = vy - this.max_radius;
      vy1 = vy + this.max_radius;
      ref2 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref2[0], y1 = ref2[1];
    }
    candidates = [];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    ref3 = (function() {
      var k, len, ref3, results;
      ref3 = this.index.search(bbox);
      results = [];
      for (k = 0, len = ref3.length; k < len; k++) {
        pt = ref3[k];
        results.push(pt.i);
      }
      return results;
    }).call(this);
    for (j = 0, len = ref3.length; j < len; j++) {
      i = ref3[j];
      r2 = Math.pow(this.sradius[i], 2);
      sx0 = this.renderer.xmapper.map_to_target(x, true);
      sx1 = this.renderer.xmapper.map_to_target(this._x[i], true);
      sy0 = this.renderer.ymapper.map_to_target(y, true);
      sy1 = this.renderer.ymapper.map_to_target(this._y[i], true);
      dist = Math.pow(sx0 - sx1, 2) + Math.pow(sy0 - sy1, 2);
      if (dist <= r2) {
        candidates.push([i, dist]);
      }
    }
    direction = this.model.properties.direction.value();
    hits = [];
    for (k = 0, len1 = candidates.length; k < len1; k++) {
      ref4 = candidates[k], i = ref4[0], dist = ref4[1];
      sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
      sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
      angle = Math.atan2(sy - this.sy[i], sx - this.sx[i]);
      if (angle_between(-angle, -this._start_angle[i], -this._end_angle[i], direction)) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  WedgeView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1);
  };

  return WedgeView;

})(Glyph.View);

Wedge = (function(superClass) {
  extend(Wedge, superClass);

  function Wedge() {
    return Wedge.__super__.constructor.apply(this, arguments);
  }

  Wedge.prototype.default_view = WedgeView;

  Wedge.prototype.type = 'Wedge';

  Wedge.coords([['x', 'y']]);

  Wedge.mixins(['line', 'fill']);

  Wedge.define({
    direction: [p.Direction, 'anticlock'],
    radius: [p.DistanceSpec],
    start_angle: [p.AngleSpec],
    end_angle: [p.AngleSpec]
  });

  return Wedge;

})(Glyph.Model);

module.exports = {
  Model: Wedge,
  View: WedgeView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","../../core/util/math":"core/util/math","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/grids/grid":[function(require,module,exports){
var Grid, GridView, GuideRenderer, Renderer, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

GuideRenderer = require("../renderers/guide_renderer");

Renderer = require("../renderers/renderer");

p = require("../../core/properties");

GridView = (function(superClass) {
  extend(GridView, superClass);

  function GridView() {
    return GridView.__super__.constructor.apply(this, arguments);
  }

  GridView.prototype.initialize = function(attrs, options) {
    GridView.__super__.initialize.call(this, attrs, options);
    this._x_range_name = this.mget('x_range_name');
    return this._y_range_name = this.mget('y_range_name');
  };

  GridView.prototype.render = function() {
    var ctx;
    if (this.model.visible === false) {
      return;
    }
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    this._draw_regions(ctx);
    this._draw_minor_grids(ctx);
    this._draw_grids(ctx);
    return ctx.restore();
  };

  GridView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change', this.request_render);
  };

  GridView.prototype._draw_regions = function(ctx) {
    var i, k, ref, ref1, ref2, ref3, sx0, sx1, sy0, sy1, xs, ys;
    if (!this.visuals.band_fill.doit) {
      return;
    }
    ref = this.model.grid_coords('major', false), xs = ref[0], ys = ref[1];
    this.visuals.band_fill.set_value(ctx);
    for (i = k = 0, ref1 = xs.length - 1; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
      if (i % 2 === 1) {
        ref2 = this.plot_view.map_to_screen(xs[i], ys[i], this._x_range_name, this._y_range_name), sx0 = ref2[0], sy0 = ref2[1];
        ref3 = this.plot_view.map_to_screen(xs[i + 1], ys[i + 1], this._x_range_name, this._y_range_name), sx1 = ref3[0], sy1 = ref3[1];
        ctx.fillRect(sx0[0], sy0[0], sx1[1] - sx0[0], sy1[1] - sy0[0]);
        ctx.fill();
      }
    }
  };

  GridView.prototype._draw_grids = function(ctx) {
    var ref, xs, ys;
    if (!this.visuals.grid_line.doit) {
      return;
    }
    ref = this.model.grid_coords('major'), xs = ref[0], ys = ref[1];
    return this._draw_grid_helper(ctx, this.visuals.grid_line, xs, ys);
  };

  GridView.prototype._draw_minor_grids = function(ctx) {
    var ref, xs, ys;
    if (!this.visuals.minor_grid_line.doit) {
      return;
    }
    ref = this.model.grid_coords('minor'), xs = ref[0], ys = ref[1];
    return this._draw_grid_helper(ctx, this.visuals.minor_grid_line, xs, ys);
  };

  GridView.prototype._draw_grid_helper = function(ctx, props, xs, ys) {
    var i, k, l, ref, ref1, ref2, sx, sy;
    props.set_value(ctx);
    for (i = k = 0, ref = xs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      ref1 = this.plot_view.map_to_screen(xs[i], ys[i], this._x_range_name, this._y_range_name), sx = ref1[0], sy = ref1[1];
      ctx.beginPath();
      ctx.moveTo(Math.round(sx[0]), Math.round(sy[0]));
      for (i = l = 1, ref2 = sx.length; 1 <= ref2 ? l < ref2 : l > ref2; i = 1 <= ref2 ? ++l : --l) {
        ctx.lineTo(Math.round(sx[i]), Math.round(sy[i]));
      }
      ctx.stroke();
    }
  };

  return GridView;

})(Renderer.View);

Grid = (function(superClass) {
  extend(Grid, superClass);

  function Grid() {
    return Grid.__super__.constructor.apply(this, arguments);
  }

  Grid.prototype.default_view = GridView;

  Grid.prototype.type = 'Grid';

  Grid.mixins(['line:grid_', 'line:minor_grid_', 'fill:band_']);

  Grid.define({
    bounds: [p.Any, 'auto'],
    dimension: [p.Number, 0],
    ticker: [p.Instance],
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default']
  });

  Grid.override({
    level: "underlay",
    band_fill_color: null,
    band_fill_alpha: 0,
    grid_line_color: '#e5e5e5',
    minor_grid_line_color: null
  });

  Grid.prototype.ranges = function() {
    var frame, i, j, ranges;
    i = this.get('dimension');
    j = (i + 1) % 2;
    frame = this.plot.plot_canvas.get('frame');
    ranges = [frame.get('x_ranges')[this.get('x_range_name')], frame.get('y_ranges')[this.get('y_range_name')]];
    return [ranges[i], ranges[j]];
  };

  Grid.prototype.computed_bounds = function() {
    var cross_range, end, range, range_bounds, ref, start, user_bounds;
    ref = this.ranges(), range = ref[0], cross_range = ref[1];
    user_bounds = this.get('bounds');
    range_bounds = [range.get('min'), range.get('max')];
    if (_.isArray(user_bounds)) {
      start = Math.min(user_bounds[0], user_bounds[1]);
      end = Math.max(user_bounds[0], user_bounds[1]);
      if (start < range_bounds[0]) {
        start = range_bounds[0];
      } else if (start > range_bounds[1]) {
        start = null;
      }
      if (end > range_bounds[1]) {
        end = range_bounds[1];
      } else if (end < range_bounds[0]) {
        end = null;
      }
    } else {
      start = range_bounds[0], end = range_bounds[1];
    }
    return [start, end];
  };

  Grid.prototype.grid_coords = function(location, exclude_ends) {
    var N, cmax, cmin, coords, cross_range, dim_i, dim_j, end, i, ii, j, k, l, loc, max, min, n, range, ref, ref1, ref2, ref3, start, ticks, tmp;
    if (exclude_ends == null) {
      exclude_ends = true;
    }
    i = this.get('dimension');
    j = (i + 1) % 2;
    ref = this.ranges(), range = ref[0], cross_range = ref[1];
    ref1 = this.computed_bounds(), start = ref1[0], end = ref1[1];
    tmp = Math.min(start, end);
    end = Math.max(start, end);
    start = tmp;
    ticks = this.get('ticker').get_ticks(start, end, range, {})[location];
    min = range.get('min');
    max = range.get('max');
    cmin = cross_range.get('min');
    cmax = cross_range.get('max');
    coords = [[], []];
    for (ii = k = 0, ref2 = ticks.length; 0 <= ref2 ? k < ref2 : k > ref2; ii = 0 <= ref2 ? ++k : --k) {
      if ((ticks[ii] === min || ticks[ii] === max) && exclude_ends) {
        continue;
      }
      dim_i = [];
      dim_j = [];
      N = 2;
      for (n = l = 0, ref3 = N; 0 <= ref3 ? l < ref3 : l > ref3; n = 0 <= ref3 ? ++l : --l) {
        loc = cmin + (cmax - cmin) / (N - 1) * n;
        dim_i.push(ticks[ii]);
        dim_j.push(loc);
      }
      coords[i].push(dim_i);
      coords[j].push(dim_j);
    }
    return coords;
  };

  return Grid;

})(GuideRenderer.Model);

module.exports = {
  Model: Grid,
  View: GridView
};

},{"../../core/properties":"core/properties","../renderers/guide_renderer":"models/renderers/guide_renderer","../renderers/renderer":"models/renderers/renderer","underscore":"underscore"}],"models/layouts/box":[function(require,module,exports){
var Box, BoxView, EQ, GE, LayoutDOM, Strength, Variable, WEAK_EQ, _, p, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

_ = require("underscore");

ref = require("../../core/layout/solver"), EQ = ref.EQ, GE = ref.GE, Strength = ref.Strength, Variable = ref.Variable, WEAK_EQ = ref.WEAK_EQ;

p = require("../../core/properties");

LayoutDOM = require("./layout_dom");

BoxView = (function(superClass) {
  extend(BoxView, superClass);

  function BoxView() {
    return BoxView.__super__.constructor.apply(this, arguments);
  }

  BoxView.prototype.className = "bk-grid";

  BoxView.prototype.bind_bokeh_events = function() {
    BoxView.__super__.bind_bokeh_events.call(this);
    return this.listenTo(this.model, 'change:children', this.build_child_views);
  };

  BoxView.prototype.get_height = function() {
    var child_heights, children, height;
    children = this.model.get_layoutable_children();
    child_heights = _.map(children, (function(child) {
      return child._height._value;
    }));
    if (this.model._horizontal) {
      height = _.reduce(child_heights, (function(a, b) {
        return Math.max(a, b);
      }));
    } else {
      height = _.reduce(child_heights, (function(a, b) {
        return a + b;
      }));
    }
    return height;
  };

  BoxView.prototype.get_width = function() {
    var child_widths, children, width;
    children = this.model.get_layoutable_children();
    child_widths = _.map(children, (function(child) {
      return child._width._value;
    }));
    if (this.model._horizontal) {
      width = _.reduce(child_widths, (function(a, b) {
        return a + b;
      }));
    } else {
      width = _.reduce(child_widths, (function(a, b) {
        return Math.max(a, b);
      }));
    }
    return width;
  };

  return BoxView;

})(LayoutDOM.View);

Box = (function(superClass) {
  extend(Box, superClass);

  Box.prototype.default_view = BoxView;

  function Box(attrs, options) {
    Box.__super__.constructor.call(this, attrs, options);
    this._child_equal_size_width = new Variable();
    this._child_equal_size_height = new Variable();
    this._box_equal_size_top = new Variable();
    this._box_equal_size_bottom = new Variable();
    this._box_equal_size_left = new Variable();
    this._box_equal_size_right = new Variable();
    this._box_cell_align_top = new Variable();
    this._box_cell_align_bottom = new Variable();
    this._box_cell_align_left = new Variable();
    this._box_cell_align_right = new Variable();
  }

  Box.define({
    children: [p.Array, []]
  });

  Box.internal({
    spacing: [p.Number, 6]
  });

  Box.prototype.get_layoutable_children = function() {
    return this.get('children');
  };

  Box.prototype.variables_updated = function() {
    var child, j, len, ref1;
    ref1 = this.get_layoutable_children();
    for (j = 0, len = ref1.length; j < len; j++) {
      child = ref1[j];
      child.trigger('change');
    }
    return this.trigger('change');
  };

  Box.prototype.get_edit_variables = function() {
    var child, edit_variables, j, len, ref1;
    edit_variables = Box.__super__.get_edit_variables.call(this);
    ref1 = this.get_layoutable_children();
    for (j = 0, len = ref1.length; j < len; j++) {
      child = ref1[j];
      edit_variables = edit_variables.concat(child.get_edit_variables());
    }
    return edit_variables;
  };

  Box.prototype.get_constrained_variables = function() {
    var constrained_variables;
    constrained_variables = Box.__super__.get_constrained_variables.call(this);
    constrained_variables = _.extend(constrained_variables, {
      'box-equal-size-top': this._box_equal_size_top,
      'box-equal-size-bottom': this._box_equal_size_bottom,
      'box-equal-size-left': this._box_equal_size_left,
      'box-equal-size-right': this._box_equal_size_right,
      'box-cell-align-top': this._box_cell_align_top,
      'box-cell-align-bottom': this._box_cell_align_bottom,
      'box-cell-align-left': this._box_cell_align_left,
      'box-cell-align-right': this._box_cell_align_right
    });
    return constrained_variables;
  };

  Box.prototype.get_constraints = function() {
    var child, children, constraints, i, j, k, last, len, next, rect, ref1, var_keys, vars;
    constraints = [];
    children = this.get_layoutable_children();
    if (children.length === 0) {
      return constraints;
    }
    for (j = 0, len = children.length; j < len; j++) {
      child = children[j];
      this._test_layoutable(child);
      vars = child.get_constrained_variables();
      var_keys = _.keys(vars);
      rect = this._child_rect(vars);
      if (this._horizontal) {
        if (this._has_var('height', var_keys)) {
          constraints.push(EQ(rect.height, [-1, this._height]));
        }
      } else {
        if (this._has_var('width', var_keys)) {
          constraints.push(EQ(rect.width, [-1, this._width]));
        }
      }
      if (this._horizontal) {
        if (this._has_var(['box-equal-size-left', 'box-equal-size-right', 'width'], var_keys)) {
          constraints.push(EQ([-1, vars['box-equal-size-left']], [-1, vars['box-equal-size-right']], vars['width'], this._child_equal_size_width));
        }
      } else {
        if (this._has_var(['box-equal-size-top', 'box-equal-size-bottom', 'height'], var_keys)) {
          constraints.push(EQ([-1, vars['box-equal-size-top']], [-1, vars['box-equal-size-bottom']], vars['height'], this._child_equal_size_height));
        }
      }
      constraints = constraints.concat(child.get_constraints());
    }
    last = this._info(children[0].get_constrained_variables());
    constraints.push(EQ(last.span.start, 0));
    for (i = k = 1, ref1 = children.length; 1 <= ref1 ? k < ref1 : k > ref1; i = 1 <= ref1 ? ++k : --k) {
      next = this._info(children[i].get_constrained_variables());
      if (last.span.size) {
        constraints.push(EQ(last.span.start, last.span.size, [-1, next.span.start]));
      }
      constraints.push(WEAK_EQ(last.whitespace.after, next.whitespace.before, 0 - this.spacing));
      constraints.push(GE(last.whitespace.after, next.whitespace.before, 0 - this.spacing));
      last = next;
    }
    if (this._horizontal) {
      if (this._has_var('width', var_keys)) {
        constraints.push(EQ(last.span.start, last.span.size, [-1, this._width]));
      }
    } else {
      if (this._has_var('height', var_keys)) {
        constraints.push(EQ(last.span.start, last.span.size, [-1, this._height]));
      }
    }
    constraints = constraints.concat(this._align_outer_edges_constraints(true));
    constraints = constraints.concat(this._align_outer_edges_constraints(false));
    constraints = constraints.concat(this._align_inner_cell_edges_constraints());
    constraints = constraints.concat(this._box_equal_size_bounds(true));
    constraints = constraints.concat(this._box_equal_size_bounds(false));
    constraints = constraints.concat(this._box_cell_align_bounds(true));
    constraints = constraints.concat(this._box_cell_align_bounds(false));
    constraints = constraints.concat(this._box_whitespace(true));
    constraints = constraints.concat(this._box_whitespace(false));
    return constraints;
  };

  Box.prototype._has_var = function(look_up, var_keys) {
    var look_up_list;
    if (typeof look_up === 'string') {
      look_up_list = [look_up];
    } else {
      look_up_list = look_up;
    }
    return _.every(look_up_list, function(x) {
      return indexOf.call(var_keys, x) >= 0;
    });
  };

  Box.prototype._test_layoutable = function(child) {
    var j, key, len, required_constrained_variables, vars;
    required_constrained_variables = ['origin-x', 'origin-y', 'whitespace-top', 'whitespace-right', 'whitespace-bottom', 'whitespace-left'];
    if (child.get_constrained_variables == null) {
      throw new Error(child + " is missing get_constrained_variables method");
    }
    vars = child.get_constrained_variables();
    for (j = 0, len = required_constrained_variables.length; j < len; j++) {
      key = required_constrained_variables[j];
      if (indexOf.call(_.keys(vars), key) < 0) {
        throw new Error(child + " is missing constrained_variable " + key);
      }
      if (!vars[key] instanceof Variable) {
        throw new Error(child + " " + key + " is not a solver Variable");
      }
    }
    return true;
  };

  Box.prototype._child_rect = function(vars) {
    var height, ref1, width, x, y;
    width = vars['width'];
    height = vars['height'];
    ref1 = [vars['origin-x'], vars['origin-y']], x = ref1[0], y = ref1[1];
    return {
      x: x,
      y: y,
      width: width,
      height: height
    };
  };

  Box.prototype._span = function(rect) {
    if (this._horizontal) {
      return {
        start: rect.x,
        size: rect.width
      };
    } else {
      return {
        start: rect.y,
        size: rect.height
      };
    }
  };

  Box.prototype._info = function(vars) {
    var span, whitespace;
    if (this._horizontal) {
      whitespace = {
        before: vars['whitespace-left'],
        after: vars['whitespace-right']
      };
    } else {
      whitespace = {
        before: vars['whitespace-top'],
        after: vars['whitespace-bottom']
      };
    }
    span = this._span(this._child_rect(vars));
    return {
      span: span,
      whitespace: whitespace
    };
  };

  Box.prototype._flatten_cell_edge_variables = function(horizontal) {
    var add_path, all_vars, arity, cell, cell_vars, child, children, direction, flattened, j, k, key, kind, len, len1, name, new_key, parsed, path, relevant_edges, variables;
    if (horizontal) {
      relevant_edges = Box._top_bottom_inner_cell_edge_variables;
    } else {
      relevant_edges = Box._left_right_inner_cell_edge_variables;
    }
    add_path = horizontal !== this._horizontal;
    children = this.get_layoutable_children();
    arity = children.length;
    flattened = {};
    cell = 0;
    for (j = 0, len = children.length; j < len; j++) {
      child = children[j];
      if (child instanceof Box) {
        cell_vars = child._flatten_cell_edge_variables(horizontal);
      } else {
        cell_vars = {};
      }
      all_vars = child.get_constrained_variables();
      for (k = 0, len1 = relevant_edges.length; k < len1; k++) {
        name = relevant_edges[k];
        if (name in all_vars) {
          cell_vars[name] = [all_vars[name]];
        }
      }
      for (key in cell_vars) {
        variables = cell_vars[key];
        if (add_path) {
          parsed = key.split(" ");
          kind = parsed[0];
          if (parsed.length > 1) {
            path = parsed[1];
          } else {
            path = "";
          }
          if (this._horizontal) {
            direction = "row";
          } else {
            direction = "col";
          }
          new_key = kind + " " + direction + "-" + arity + "-" + cell + "-" + path;
        } else {
          new_key = key;
        }
        if (new_key in flattened) {
          flattened[new_key] = flattened[new_key].concat(variables);
        } else {
          flattened[new_key] = variables;
        }
      }
      cell = cell + 1;
    }
    return flattened;
  };

  Box.prototype._align_inner_cell_edges_constraints = function() {
    var constraints, flattened, i, j, key, last, ref1, variables;
    constraints = [];
    if (this._is_root) {
      flattened = this._flatten_cell_edge_variables(this._horizontal);
      for (key in flattened) {
        variables = flattened[key];
        if (variables.length > 1) {
          last = variables[0];
          for (i = j = 1, ref1 = variables.length; 1 <= ref1 ? j < ref1 : j > ref1; i = 1 <= ref1 ? ++j : --j) {
            constraints.push(EQ(variables[i], [-1, last]));
          }
        }
      }
    }
    return constraints;
  };

  Box.prototype._find_edge_leaves = function(horizontal) {
    var child, child_leaves, children, end, j, leaves, len, start;
    children = this.get_layoutable_children();
    leaves = [[], []];
    if (children.length > 0) {
      if (this._horizontal === horizontal) {
        start = children[0];
        end = children[children.length - 1];
        if (start instanceof Box) {
          leaves[0] = leaves[0].concat(start._find_edge_leaves(horizontal)[0]);
        } else {
          leaves[0].push(start);
        }
        if (end instanceof Box) {
          leaves[1] = leaves[1].concat(end._find_edge_leaves(horizontal)[1]);
        } else {
          leaves[1].push(end);
        }
      } else {
        for (j = 0, len = children.length; j < len; j++) {
          child = children[j];
          if (child instanceof Box) {
            child_leaves = child._find_edge_leaves(horizontal);
            leaves[0] = leaves[0].concat(child_leaves[0]);
            leaves[1] = leaves[1].concat(child_leaves[1]);
          } else {
            leaves[0].push(child);
            leaves[1].push(child);
          }
        }
      }
    }
    return leaves;
  };

  Box.prototype._align_outer_edges_constraints = function(horizontal) {
    var add_all_equal, collect_vars, end_edges, end_leaves, end_variable, ref1, result, start_edges, start_leaves, start_variable;
    ref1 = this._find_edge_leaves(horizontal), start_leaves = ref1[0], end_leaves = ref1[1];
    if (horizontal) {
      start_variable = 'on-edge-align-left';
      end_variable = 'on-edge-align-right';
    } else {
      start_variable = 'on-edge-align-top';
      end_variable = 'on-edge-align-bottom';
    }
    collect_vars = function(leaves, name) {
      var edges, j, leaf, len, vars;
      edges = [];
      for (j = 0, len = leaves.length; j < len; j++) {
        leaf = leaves[j];
        vars = leaf.get_constrained_variables();
        if (name in vars) {
          edges.push(vars[name]);
        }
      }
      return edges;
    };
    start_edges = collect_vars(start_leaves, start_variable);
    end_edges = collect_vars(end_leaves, end_variable);
    result = [];
    add_all_equal = function(edges) {
      var edge, first, i, j, ref2;
      if (edges.length > 1) {
        first = edges[0];
        for (i = j = 1, ref2 = edges.length; 1 <= ref2 ? j < ref2 : j > ref2; i = 1 <= ref2 ? ++j : --j) {
          edge = edges[i];
          result.push(EQ([-1, first], edge));
        }
        return null;
      }
    };
    add_all_equal(start_edges);
    add_all_equal(end_edges);
    return result;
  };

  Box.prototype._box_insets_from_child_insets = function(horizontal, child_variable_prefix, our_variable_prefix, minimum) {
    var add_constraints, end_leaves, end_variable, our_end, our_start, ref1, result, start_leaves, start_variable;
    ref1 = this._find_edge_leaves(horizontal), start_leaves = ref1[0], end_leaves = ref1[1];
    if (horizontal) {
      start_variable = child_variable_prefix + "-left";
      end_variable = child_variable_prefix + "-right";
      our_start = this[our_variable_prefix + "_left"];
      our_end = this[our_variable_prefix + "_right"];
    } else {
      start_variable = child_variable_prefix + "-top";
      end_variable = child_variable_prefix + "-bottom";
      our_start = this[our_variable_prefix + "_top"];
      our_end = this[our_variable_prefix + "_bottom"];
    }
    result = [];
    add_constraints = function(ours, leaves, name) {
      var edges, j, leaf, len, vars;
      edges = [];
      for (j = 0, len = leaves.length; j < len; j++) {
        leaf = leaves[j];
        vars = leaf.get_constrained_variables();
        if (name in vars) {
          if (minimum) {
            result.push(GE([-1, ours], vars[name]));
          } else {
            result.push(EQ([-1, ours], vars[name]));
          }
        }
      }
      return null;
    };
    add_constraints(our_start, start_leaves, start_variable);
    add_constraints(our_end, end_leaves, end_variable);
    return result;
  };

  Box.prototype._box_equal_size_bounds = function(horizontal) {
    return this._box_insets_from_child_insets(horizontal, 'box-equal-size', '_box_equal_size', false);
  };

  Box.prototype._box_cell_align_bounds = function(horizontal) {
    return this._box_insets_from_child_insets(horizontal, 'box-cell-align', '_box_cell_align', false);
  };

  Box.prototype._box_whitespace = function(horizontal) {
    return this._box_insets_from_child_insets(horizontal, 'whitespace', '_whitespace', true);
  };

  Box._left_right_inner_cell_edge_variables = ['box-cell-align-left', 'box-cell-align-right'];

  Box._top_bottom_inner_cell_edge_variables = ['box-cell-align-top', 'box-cell-align-bottom'];

  return Box;

})(LayoutDOM.Model);

module.exports = {
  Model: Box,
  View: BoxView
};

},{"../../core/layout/solver":"core/layout/solver","../../core/properties":"core/properties","./layout_dom":"models/layouts/layout_dom","underscore":"underscore"}],"models/layouts/column":[function(require,module,exports){
var Box, Column, ColumnView,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Box = require("./box");

ColumnView = (function(superClass) {
  extend(ColumnView, superClass);

  function ColumnView() {
    return ColumnView.__super__.constructor.apply(this, arguments);
  }

  ColumnView.prototype.className = "bk-grid-column";

  return ColumnView;

})(Box.View);

Column = (function(superClass) {
  extend(Column, superClass);

  Column.prototype.type = 'Column';

  Column.prototype.default_view = ColumnView;

  function Column(attrs, options) {
    Column.__super__.constructor.call(this, attrs, options);
    this._horizontal = false;
  }

  return Column;

})(Box.Model);

module.exports = {
  View: ColumnView,
  Model: Column
};

},{"./box":"models/layouts/box"}],"models/layouts/layout_dom":[function(require,module,exports){
var $, BokehView, EQ, GE, LayoutDOM, LayoutDOMView, Model, Strength, Variable, _, build_views, logger, p, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

$ = require("jquery");

Model = require("../../model");

p = require("../../core/properties");

ref = require("../../core/layout/solver"), GE = ref.GE, EQ = ref.EQ, Strength = ref.Strength, Variable = ref.Variable;

build_views = require("../../common/build_views");

BokehView = require("../../core/bokeh_view");

logger = require("../../core/logging").logger;

LayoutDOMView = (function(superClass) {
  extend(LayoutDOMView, superClass);

  function LayoutDOMView() {
    return LayoutDOMView.__super__.constructor.apply(this, arguments);
  }

  LayoutDOMView.prototype.initialize = function(options) {
    LayoutDOMView.__super__.initialize.call(this, options);
    this.$el.attr("id", "modelid_" + this.model.id);
    this.$el.addClass("bk-layout-" + this.model.sizing_mode);
    this.child_views = {};
    return this.build_child_views(false);
  };

  LayoutDOMView.prototype.build_child_views = function(init_solver) {
    var child, child_view, children, i, len;
    if (init_solver == null) {
      init_solver = true;
    }
    this.unbind_bokeh_events();
    if (init_solver) {
      this.model.document._invalidate_all_models();
      this.model.document._init_solver();
    }
    children = this.model.get_layoutable_children();
    this.child_views = {};
    build_views(this.child_views, children);
    this.$el.empty();
    for (i = 0, len = children.length; i < len; i++) {
      child = children[i];
      child_view = this.child_views[child.id];
      this.$el.append(child_view.$el);
    }
    return this.bind_bokeh_events();
  };

  LayoutDOMView.prototype.unbind_bokeh_events = function() {
    var id, ref1, results, view;
    this.stopListening();
    ref1 = this.child_views;
    results = [];
    for (id in ref1) {
      view = ref1[id];
      view.stopListening();
      results.push(typeof view.unbind_bokeh_events === "function" ? view.unbind_bokeh_events() : void 0);
    }
    return results;
  };

  LayoutDOMView.prototype.bind_bokeh_events = function() {
    var sizing_mode_msg;
    this.listenTo(this.model, 'change', this.render);
    if (this.model.sizing_mode === 'fixed') {
      this.listenToOnce(this.model.document.solver(), 'resize', (function(_this) {
        return function() {
          return _this.render();
        };
      })(this));
    } else {
      this.listenTo(this.model.document.solver(), 'resize', (function(_this) {
        return function() {
          return _this.render();
        };
      })(this));
    }
    sizing_mode_msg = "Changing sizing_mode after initialization is not currently supported.";
    return this.listenTo(this.model, 'change:sizing_mode', function() {
      return logger.warn(sizing_mode_msg);
    });
  };

  LayoutDOMView.prototype.render = function() {
    var height, s, width;
    s = this.model.document.solver();
    if (this.model.sizing_mode === 'fixed') {
      if (this.model.width != null) {
        width = this.model.width;
      } else {
        width = this.get_width();
        this.model.width = width;
      }
      if (this.model.height != null) {
        height = this.model.height;
      } else {
        height = this.get_height();
        this.model.height = height;
      }
      s.suggest_value(this.model._width, width);
      s.suggest_value(this.model._height, height);
      s.update_variables();
      this.$el.css({
        width: width,
        height: height
      });
    }
    if (this.model.sizing_mode === 'scale_width') {
      height = this.get_height();
      s.suggest_value(this.model._height, height);
      s.update_variables();
      this.$el.css({
        width: this.model._width._value,
        height: this.model._height._value
      });
    }
    if (this.model.sizing_mode === 'scale_height') {
      width = this.get_width();
      s.suggest_value(this.model._width, width);
      s.update_variables();
      this.$el.css({
        width: this.model._width._value,
        height: this.model._height._value
      });
    }
    if (this.model.sizing_mode === 'stretch_both') {
      return this.$el.css({
        position: 'absolute',
        left: this.model._dom_left._value,
        top: this.model._dom_top._value,
        width: this.model._width._value,
        height: this.model._height._value
      });
    }
  };

  LayoutDOMView.prototype.get_height = function() {
    return null;
  };

  LayoutDOMView.prototype.get_width = function() {
    return null;
  };

  return LayoutDOMView;

})(BokehView);

LayoutDOM = (function(superClass) {
  extend(LayoutDOM, superClass);

  function LayoutDOM() {
    return LayoutDOM.__super__.constructor.apply(this, arguments);
  }

  LayoutDOM.prototype.type = "LayoutDOM";

  LayoutDOM.prototype.initialize = function(attrs, options) {
    LayoutDOM.__super__.initialize.call(this, attrs, options);
    this._width = new Variable("_width " + this.id);
    this._height = new Variable("_height " + this.id);
    this._left = new Variable("_left " + this.id);
    this._right = new Variable("_right " + this.id);
    this._top = new Variable("_top " + this.id);
    this._bottom = new Variable("_bottom " + this.id);
    this._dom_top = new Variable("_dom_top " + this.id);
    this._dom_left = new Variable("_dom_left " + this.id);
    this._width_minus_right = new Variable("_width_minus_right " + this.id);
    this._height_minus_bottom = new Variable("_height_minus_bottom " + this.id);
    this._whitespace_top = new Variable();
    this._whitespace_bottom = new Variable();
    this._whitespace_left = new Variable();
    return this._whitespace_right = new Variable();
  };

  LayoutDOM.prototype.get_constraints = function() {
    var constraints;
    constraints = [];
    constraints.push(GE(this._dom_left));
    constraints.push(GE(this._dom_top));
    constraints.push(GE(this._left));
    constraints.push(GE(this._width, [-1, this._right]));
    constraints.push(GE(this._top));
    constraints.push(GE(this._height, [-1, this._bottom]));
    constraints.push(EQ(this._width_minus_right, [-1, this._width], this._right));
    constraints.push(EQ(this._height_minus_bottom, [-1, this._height], this._bottom));
    return constraints;
  };

  LayoutDOM.prototype.get_layoutable_children = function() {
    return [];
  };

  LayoutDOM.prototype.get_edit_variables = function() {
    var edit_variables;
    edit_variables = [];
    if (this.sizing_mode === 'fixed') {
      edit_variables.push({
        edit_variable: this._height,
        strength: Strength.strong
      });
      edit_variables.push({
        edit_variable: this._width,
        strength: Strength.strong
      });
    }
    if (this.sizing_mode === 'scale_width') {
      edit_variables.push({
        edit_variable: this._height,
        strength: Strength.strong
      });
    }
    if (this.sizing_mode === 'scale_height') {
      edit_variables.push({
        edit_variable: this._width,
        strength: Strength.strong
      });
    }
    return edit_variables;
  };

  LayoutDOM.prototype.get_constrained_variables = function() {
    var constrained_variables;
    constrained_variables = {
      'origin-x': this._dom_left,
      'origin-y': this._dom_top,
      'whitespace-top': this._whitespace_top,
      'whitespace-bottom': this._whitespace_bottom,
      'whitespace-left': this._whitespace_left,
      'whitespace-right': this._whitespace_right
    };
    if (this.sizing_mode === 'stretch_both') {
      constrained_variables = _.extend(constrained_variables, {
        'width': this._width,
        'height': this._height
      });
    }
    if (this.sizing_mode === 'scale_width') {
      constrained_variables = _.extend(constrained_variables, {
        'width': this._width
      });
    }
    if (this.sizing_mode === 'scale_height') {
      constrained_variables = _.extend(constrained_variables, {
        'height': this._height
      });
    }
    return constrained_variables;
  };

  LayoutDOM.define({
    height: [p.Number],
    width: [p.Number],
    disabled: [p.Bool, false],
    sizing_mode: [p.SizingMode, "fixed"]
  });

  LayoutDOM.internal({
    layoutable: [p.Bool, true]
  });

  return LayoutDOM;

})(Model);

module.exports = {
  Model: LayoutDOM,
  View: LayoutDOMView
};

},{"../../common/build_views":"common/build_views","../../core/bokeh_view":"core/bokeh_view","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../../model":"model","jquery":"jquery","underscore":"underscore"}],"models/layouts/row":[function(require,module,exports){
var Box, Row, RowView,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Box = require("./box");

RowView = (function(superClass) {
  extend(RowView, superClass);

  function RowView() {
    return RowView.__super__.constructor.apply(this, arguments);
  }

  RowView.prototype.className = "bk-grid-row";

  return RowView;

})(Box.View);

Row = (function(superClass) {
  extend(Row, superClass);

  Row.prototype.type = 'Row';

  Row.prototype.default_view = RowView;

  function Row(attrs, options) {
    Row.__super__.constructor.call(this, attrs, options);
    this._horizontal = true;
  }

  return Row;

})(Box.Model);

module.exports = {
  View: RowView,
  Model: Row
};

},{"./box":"models/layouts/box"}],"models/layouts/spacer":[function(require,module,exports){
var LayoutDOM, Spacer, SpacerView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

LayoutDOM = require("./layout_dom");

SpacerView = (function(superClass) {
  extend(SpacerView, superClass);

  function SpacerView() {
    return SpacerView.__super__.constructor.apply(this, arguments);
  }

  SpacerView.prototype.className = "bk-spacer-box";

  SpacerView.prototype.render = function() {
    SpacerView.__super__.render.call(this);
    if (this.sizing_mode === 'fixed') {
      return this.$el.css({
        width: this.model.width,
        height: this.model.height
      });
    }
  };

  SpacerView.prototype.get_height = function() {
    return 1;
  };

  return SpacerView;

})(LayoutDOM.View);

Spacer = (function(superClass) {
  extend(Spacer, superClass);

  function Spacer() {
    return Spacer.__super__.constructor.apply(this, arguments);
  }

  Spacer.prototype.type = 'Spacer';

  Spacer.prototype.default_view = SpacerView;

  Spacer.prototype.get_constrained_variables = function() {
    var constrained_variables;
    constrained_variables = Spacer.__super__.get_constrained_variables.call(this);
    constrained_variables = _.extend(constrained_variables, {
      'on-edge-align-top': this._top,
      'on-edge-align-bottom': this._height_minus_bottom,
      'on-edge-align-left': this._left,
      'on-edge-align-right': this._width_minus_right,
      'box-cell-align-top': this._top,
      'box-cell-align-bottom': this._height_minus_bottom,
      'box-cell-align-left': this._left,
      'box-cell-align-right': this._width_minus_right,
      'box-equal-size-top': this._top,
      'box-equal-size-bottom': this._height_minus_bottom,
      'box-equal-size-left': this._left,
      'box-equal-size-right': this._width_minus_right
    });
    return constrained_variables;
  };

  return Spacer;

})(LayoutDOM.Model);

module.exports = {
  Model: Spacer
};

},{"./layout_dom":"models/layouts/layout_dom","underscore":"underscore"}],"models/layouts/widget_box":[function(require,module,exports){
var $, BokehView, EQ, GE, LayoutDOM, Strength, Variable, WEAK_EQ, WidgetBox, WidgetBoxView, _, build_views, logger, p, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

$ = require("jquery");

build_views = require("../../common/build_views");

BokehView = require("../../core/bokeh_view");

ref = require("../../core/layout/solver"), WEAK_EQ = ref.WEAK_EQ, GE = ref.GE, EQ = ref.EQ, Strength = ref.Strength, Variable = ref.Variable;

logger = require("../../core/logging").logger;

p = require("../../core/properties");

LayoutDOM = require("../layouts/layout_dom");

WidgetBoxView = (function(superClass) {
  extend(WidgetBoxView, superClass);

  function WidgetBoxView() {
    return WidgetBoxView.__super__.constructor.apply(this, arguments);
  }

  WidgetBoxView.prototype.className = "bk-widget-box";

  WidgetBoxView.prototype.initialize = function(options) {
    WidgetBoxView.__super__.initialize.call(this, options);
    return this.render();
  };

  WidgetBoxView.prototype.bind_bokeh_events = function() {
    WidgetBoxView.__super__.bind_bokeh_events.call(this);
    return this.listenTo(this.model, 'change:children', (function(_this) {
      return function() {
        return _this.build_child_views();
      };
    })(this));
  };

  WidgetBoxView.prototype.render = function() {
    var css_width, height, s, width;
    s = this.model.document.solver();
    if (this.model.sizing_mode === 'fixed' || this.model.sizing_mode === 'scale_height') {
      width = this.get_width();
      if (this.model._width._value !== width) {
        s.suggest_value(this.model._width, width);
        s.update_variables();
      }
    }
    if (this.model.sizing_mode === 'fixed' || this.model.sizing_mode === 'scale_width') {
      height = this.get_height();
      if (this.model._height._value !== height) {
        s.suggest_value(this.model._height, height);
        s.update_variables();
      }
    }
    if (this.model._width._value - 20 > 0) {
      css_width = this.model._width._value - 20;
    } else {
      css_width = "100%";
    }
    if (this.model.sizing_mode === 'stretch_both') {
      return this.$el.css({
        position: 'absolute',
        left: this.model._dom_left._value,
        top: this.model._dom_top._value,
        width: this.model._width._value,
        height: this.model._height._value
      });
    } else {
      return this.$el.css({
        width: css_width
      });
    }
  };

  WidgetBoxView.prototype.get_height = function() {
    var child_view, height, key, ref1;
    height = 0;
    ref1 = this.child_views;
    for (key in ref1) {
      if (!hasProp.call(ref1, key)) continue;
      child_view = ref1[key];
      height += child_view.el.scrollHeight;
    }
    return height + 20;
  };

  WidgetBoxView.prototype.get_width = function() {
    var child_view, child_width, key, ref1, width;
    if (this.model.width != null) {
      return this.model.width;
    } else {
      width = this.el.scrollWidth + 20;
      ref1 = this.child_views;
      for (key in ref1) {
        if (!hasProp.call(ref1, key)) continue;
        child_view = ref1[key];
        child_width = child_view.el.scrollWidth;
        if (child_width > width) {
          width = child_width;
        }
      }
      return width;
    }
  };

  return WidgetBoxView;

})(LayoutDOM.View);

WidgetBox = (function(superClass) {
  extend(WidgetBox, superClass);

  function WidgetBox() {
    return WidgetBox.__super__.constructor.apply(this, arguments);
  }

  WidgetBox.prototype.type = 'WidgetBox';

  WidgetBox.prototype.default_view = WidgetBoxView;

  WidgetBox.prototype.initialize = function(options) {
    WidgetBox.__super__.initialize.call(this, options);
    if (this.sizing_mode === 'fixed' && this.width === null) {
      this.width = 300;
      logger.info("WidgetBox mode is fixed, but no width specified. Using default of 300.");
    }
    if (this.sizing_mode === 'scale_height') {
      return logger.warn("sizing_mode `scale_height` is not experimental for WidgetBox. Please report your results to the bokeh dev team so we can improve.");
    }
  };

  WidgetBox.prototype.get_edit_variables = function() {
    var child, edit_variables, i, len, ref1;
    edit_variables = WidgetBox.__super__.get_edit_variables.call(this);
    ref1 = this.get_layoutable_children();
    for (i = 0, len = ref1.length; i < len; i++) {
      child = ref1[i];
      edit_variables = edit_variables.concat(child.get_edit_variables());
    }
    return edit_variables;
  };

  WidgetBox.prototype.get_constraints = function() {
    var child, constraints, i, len, ref1;
    constraints = WidgetBox.__super__.get_constraints.call(this);
    ref1 = this.get_layoutable_children();
    for (i = 0, len = ref1.length; i < len; i++) {
      child = ref1[i];
      constraints = constraints.concat(child.get_constraints());
    }
    return constraints;
  };

  WidgetBox.prototype.get_constrained_variables = function() {
    var constrained_variables;
    constrained_variables = WidgetBox.__super__.get_constrained_variables.call(this);
    constrained_variables = _.extend(constrained_variables, {
      'on-edge-align-top': this._top,
      'on-edge-align-bottom': this._height_minus_bottom,
      'on-edge-align-left': this._left,
      'on-edge-align-right': this._width_minus_right,
      'box-cell-align-top': this._top,
      'box-cell-align-bottom': this._height_minus_bottom,
      'box-cell-align-left': this._left,
      'box-cell-align-right': this._width_minus_right,
      'box-equal-size-top': this._top,
      'box-equal-size-bottom': this._height_minus_bottom
    });
    if (this.sizing_mode !== 'fixed') {
      constrained_variables = _.extend(constrained_variables, {
        'box-equal-size-left': this._left,
        'box-equal-size-right': this._width_minus_right
      });
    }
    return constrained_variables;
  };

  WidgetBox.prototype.get_layoutable_children = function() {
    return this.children;
  };

  WidgetBox.define({
    'children': [p.Array, []]
  });

  return WidgetBox;

})(LayoutDOM.Model);

module.exports = {
  Model: WidgetBox
};

},{"../../common/build_views":"common/build_views","../../core/bokeh_view":"core/bokeh_view","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../layouts/layout_dom":"models/layouts/layout_dom","jquery":"jquery","underscore":"underscore"}],"models/mappers/categorical_mapper":[function(require,module,exports){
var CategoricalMapper, LinearMapper, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

LinearMapper = require("./linear_mapper");

CategoricalMapper = (function(superClass) {
  extend(CategoricalMapper, superClass);

  function CategoricalMapper() {
    return CategoricalMapper.__super__.constructor.apply(this, arguments);
  }

  CategoricalMapper.prototype.map_to_target = function(x, return_synthetic) {
    var factor, factors, percent, range, ref, result;
    if (return_synthetic == null) {
      return_synthetic = false;
    }
    if (_.isNumber(x)) {
      if (return_synthetic) {
        return x;
      } else {
        return CategoricalMapper.__super__.map_to_target.call(this, x);
      }
    }
    range = this.get('source_range');
    factors = range.get('factors');
    if (x.indexOf(':') >= 0) {
      ref = x.split(':'), factor = ref[0], percent = ref[1];
      percent = parseFloat(percent);
      result = factors.indexOf(factor) + 0.5 + range.get('offset') + percent;
    } else {
      result = factors.indexOf(x) + 1 + range.get('offset');
    }
    if (return_synthetic) {
      return result;
    } else {
      return CategoricalMapper.__super__.map_to_target.call(this, result);
    }
  };

  CategoricalMapper.prototype.v_map_to_target = function(xs, return_synthetic) {
    var factor, factors, i, j, percent, range, ref, ref1, results, x;
    if (return_synthetic == null) {
      return_synthetic = false;
    }
    if (_.isNumber(xs[0])) {
      if (return_synthetic) {
        return xs;
      } else {
        return CategoricalMapper.__super__.v_map_to_target.call(this, xs);
      }
    }
    range = this.get('source_range');
    factors = range.get('factors');
    results = Array(xs.length);
    for (i = j = 0, ref = xs.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      x = xs[i];
      if (x.indexOf(':') >= 0) {
        ref1 = x.split(':'), factor = ref1[0], percent = ref1[1];
        percent = parseFloat(percent);
        results[i] = factors.indexOf(factor) + 0.5 + range.get('offset') + percent;
      } else {
        results[i] = factors.indexOf(x) + 1 + range.get('offset');
      }
    }
    if (return_synthetic) {
      return results;
    } else {
      return CategoricalMapper.__super__.v_map_to_target.call(this, results);
    }
  };

  CategoricalMapper.prototype.map_from_target = function(xprime, skip_cat) {
    var factors, range;
    if (skip_cat == null) {
      skip_cat = false;
    }
    xprime = CategoricalMapper.__super__.map_from_target.call(this, xprime);
    if (skip_cat) {
      return xprime;
    }
    range = this.get('source_range');
    factors = range.get('factors');
    return factors[Math.floor(xprime - 0.5 - range.get('offset'))];
  };

  CategoricalMapper.prototype.v_map_from_target = function(xprimes, skip_cat) {
    var factors, i, j, k, range, ref, ref1, result, x;
    if (skip_cat == null) {
      skip_cat = false;
    }
    x = CategoricalMapper.__super__.v_map_from_target.call(this, xprimes);
    for (i = j = 0, ref = x.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      x[i] = x[i];
    }
    if (skip_cat) {
      return x;
    }
    result = Array(x);
    range = this.get('source_range');
    factors = range.get('factors');
    for (i = k = 0, ref1 = xprimes.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
      result[i] = factors[Math.floor(x[i] - 0.5 - range.get('offset'))];
    }
    return result;
  };

  return CategoricalMapper;

})(LinearMapper.Model);

module.exports = {
  Model: CategoricalMapper
};

},{"./linear_mapper":"models/mappers/linear_mapper","underscore":"underscore"}],"models/mappers/color_mapper":[function(require,module,exports){
var ColorMapper, Model, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../../model");

ColorMapper = (function(superClass) {
  extend(ColorMapper, superClass);

  function ColorMapper() {
    return ColorMapper.__super__.constructor.apply(this, arguments);
  }

  ColorMapper.prototype.type = "ColorMapper";

  ColorMapper.prototype.initialize = function(attrs, options) {
    return ColorMapper.__super__.initialize.call(this, attrs, options);
  };

  ColorMapper.prototype.v_map_screen = function(data) {
    return null;
  };

  ColorMapper.prototype._is_little_endian = function() {
    var buf, buf32, buf8, little_endian;
    buf = new ArrayBuffer(4);
    buf8 = new Uint8ClampedArray(buf);
    buf32 = new Uint32Array(buf);
    buf32[1] = 0x0a0b0c0d;
    little_endian = true;
    if (buf8[4] === 0x0a && buf8[5] === 0x0b && buf8[6] === 0x0c && buf8[7] === 0x0d) {
      little_endian = false;
    }
    return little_endian;
  };

  ColorMapper.prototype._build_palette = function(palette) {
    var _convert, i, j, new_palette, ref;
    new_palette = new Uint32Array(palette.length + 1);
    _convert = function(value) {
      if (_.isNumber(value)) {
        return value;
      } else {
        return parseInt(value.slice(1), 16);
      }
    };
    for (i = j = 0, ref = palette.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      new_palette[i] = _convert(palette[i]);
    }
    new_palette[new_palette.length - 1] = _convert(palette[palette.length - 1]);
    return new_palette;
  };

  return ColorMapper;

})(Model);

module.exports = {
  Model: ColorMapper
};

},{"../../model":"model","underscore":"underscore"}],"models/mappers/grid_mapper":[function(require,module,exports){
var GridMapper, Model,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Model = require("../../model");

GridMapper = (function(superClass) {
  extend(GridMapper, superClass);

  function GridMapper() {
    return GridMapper.__super__.constructor.apply(this, arguments);
  }

  GridMapper.prototype.map_to_target = function(x, y) {
    var xprime, yprime;
    xprime = this.get('domain_mapper').map_to_target(x);
    yprime = this.get('codomain_mapper').map_to_target(y);
    return [xprime, yprime];
  };

  GridMapper.prototype.v_map_to_target = function(xs, ys) {
    var xprimes, yprimes;
    xprimes = this.get('domain_mapper').v_map_to_target(xs);
    yprimes = this.get('codomain_mapper').v_map_to_target(ys);
    return [xprimes, yprimes];
  };

  GridMapper.prototype.map_from_target = function(xprime, yprime) {
    var x, y;
    x = this.get('domain_mapper').map_from_target(xprime);
    y = this.get('codomain_mapper').map_from_target(yprime);
    return [x, y];
  };

  GridMapper.prototype.v_map_from_target = function(xprimes, yprimes) {
    var xs, ys;
    xs = this.get('domain_mapper').v_map_from_target(xprimes);
    ys = this.get('codomain_mapper').v_map_from_target(yprimes);
    return [xs, ys];
  };

  return GridMapper;

})(Model);

module.exports = {
  Model: GridMapper
};

},{"../../model":"model"}],"models/mappers/linear_color_mapper":[function(require,module,exports){
var ColorMapper, LinearColorMapper, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ColorMapper = require("./color_mapper");

p = require("../../core/properties");

LinearColorMapper = (function(superClass) {
  extend(LinearColorMapper, superClass);

  function LinearColorMapper() {
    return LinearColorMapper.__super__.constructor.apply(this, arguments);
  }

  LinearColorMapper.prototype.type = "LinearColorMapper";

  LinearColorMapper.define({
    high: [p.Number],
    low: [p.Number],
    palette: [p.Any],
    reserve_val: [p.Number],
    reserve_color: [p.Color, '#ffffff']
  });

  LinearColorMapper.prototype.initialize = function(attrs, options) {
    LinearColorMapper.__super__.initialize.call(this, attrs, options);
    this._little_endian = this._is_little_endian();
    this._palette = this._build_palette(this.get('palette'));
    if (this.get('reserve_color') != null) {
      this._reserve_color = parseInt(this.get('reserve_color').slice(1), 16);
      return this._reserve_val = this.get('reserve_val');
    }
  };

  LinearColorMapper.prototype.v_map_screen = function(data) {
    var N, buf, color, d, high, i, j, k, low, offset, ref, ref1, ref2, ref3, scale, value;
    buf = new ArrayBuffer(data.length * 4);
    color = new Uint32Array(buf);
    low = (ref = this.get('low')) != null ? ref : _.min(data);
    high = (ref1 = this.get('high')) != null ? ref1 : _.max(data);
    N = this._palette.length - 1;
    scale = N / (high - low);
    offset = -scale * low;
    if (this._little_endian) {
      for (i = j = 0, ref2 = data.length; 0 <= ref2 ? j < ref2 : j > ref2; i = 0 <= ref2 ? ++j : --j) {
        d = data[i];
        if (d === this._reserve_val) {
          value = this._reserve_color;
        } else {
          if (d > high) {
            d = high;
          }
          if (d < low) {
            d = low;
          }
          value = this._palette[Math.floor(d * scale + offset)];
        }
        color[i] = (0xff << 24) | ((value & 0xff0000) >> 16) | (value & 0xff00) | ((value & 0xff) << 16);
      }
    } else {
      for (i = k = 0, ref3 = data.length; 0 <= ref3 ? k < ref3 : k > ref3; i = 0 <= ref3 ? ++k : --k) {
        d = data[i];
        if (d === this._reserve_val) {
          value = this._reserve_color;
        } else {
          if (d > high) {
            d = high;
          }
          if (d < low) {
            d = low;
          }
          value = this._palette[Math.floor(d * scale + offset)];
        }
        color[i] = (value << 8) | 0xff;
      }
    }
    return buf;
  };

  return LinearColorMapper;

})(ColorMapper.Model);

module.exports = {
  Model: LinearColorMapper
};

},{"../../core/properties":"core/properties","./color_mapper":"models/mappers/color_mapper","underscore":"underscore"}],"models/mappers/linear_mapper":[function(require,module,exports){
var LinearMapper, Model, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Model = require("../../model");

p = require("../../core/properties");

LinearMapper = (function(superClass) {
  extend(LinearMapper, superClass);

  function LinearMapper() {
    return LinearMapper.__super__.constructor.apply(this, arguments);
  }

  LinearMapper.prototype.initialize = function(attrs, options) {
    LinearMapper.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('mapper_state', this._mapper_state, true);
    this.add_dependencies('mapper_state', this, ['source_range', 'target_range']);
    this.add_dependencies('mapper_state', this.get('source_range'), ['start', 'end']);
    return this.add_dependencies('mapper_state', this.get('target_range'), ['start', 'end']);
  };

  LinearMapper.prototype.map_to_target = function(x) {
    var offset, ref, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    return scale * x + offset;
  };

  LinearMapper.prototype.v_map_to_target = function(xs) {
    var i, idx, len, offset, ref, result, scale, x;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    result = new Float64Array(xs.length);
    for (idx = i = 0, len = xs.length; i < len; idx = ++i) {
      x = xs[idx];
      result[idx] = scale * x + offset;
    }
    return result;
  };

  LinearMapper.prototype.map_from_target = function(xprime) {
    var offset, ref, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    return (xprime - offset) / scale;
  };

  LinearMapper.prototype.v_map_from_target = function(xprimes) {
    var i, idx, len, offset, ref, result, scale, xprime;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1];
    result = new Float64Array(xprimes.length);
    for (idx = i = 0, len = xprimes.length; i < len; idx = ++i) {
      xprime = xprimes[idx];
      result[idx] = (xprime - offset) / scale;
    }
    return result;
  };

  LinearMapper.prototype._mapper_state = function() {
    var offset, scale, source_end, source_start, target_end, target_start;
    source_start = this.get('source_range').get('start');
    source_end = this.get('source_range').get('end');
    target_start = this.get('target_range').get('start');
    target_end = this.get('target_range').get('end');
    scale = (target_end - target_start) / (source_end - source_start);
    offset = -(scale * source_start) + target_start;
    return [scale, offset];
  };

  LinearMapper.internal({
    source_range: [p.Any],
    target_range: [p.Any]
  });

  return LinearMapper;

})(Model);

module.exports = {
  Model: LinearMapper
};

},{"../../core/properties":"core/properties","../../model":"model"}],"models/mappers/log_color_mapper":[function(require,module,exports){
var ColorMapper, LogColorMapper, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ColorMapper = require("./color_mapper");

p = require("../../core/properties");

LogColorMapper = (function(superClass) {
  extend(LogColorMapper, superClass);

  function LogColorMapper() {
    return LogColorMapper.__super__.constructor.apply(this, arguments);
  }

  LogColorMapper.prototype.type = "LogColorMapper";

  LogColorMapper.define({
    high: [p.Number],
    low: [p.Number],
    palette: [p.Any]
  });

  LogColorMapper.prototype.initialize = function(attrs, options) {
    LogColorMapper.__super__.initialize.call(this, attrs, options);
    this._little_endian = this._is_little_endian();
    return this._palette = this._build_palette(this.get('palette'));
  };

  LogColorMapper.prototype.v_map_screen = function(data) {
    var N, buf, color, d, high, i, j, k, log, low, ref, ref1, ref2, ref3, scale, value;
    buf = new ArrayBuffer(data.length * 4);
    color = new Uint32Array(buf);
    low = (ref = this.get('low')) != null ? ref : _.min(data);
    high = (ref1 = this.get('high')) != null ? ref1 : _.max(data);
    N = this._palette.length - 1;
    scale = N / (Math.log1p(high) - Math.log1p(low));
    if (this._little_endian) {
      for (i = j = 0, ref2 = data.length; 0 <= ref2 ? j < ref2 : j > ref2; i = 0 <= ref2 ? ++j : --j) {
        d = data[i];
        if (d > high) {
          d = high;
        } else if (d < low) {
          d = low;
        }
        log = Math.log1p(d) - Math.log1p(low);
        value = this._palette[Math.floor(log * scale)];
        color[i] = (0xff << 24) | ((value & 0xff0000) >> 16) | (value & 0xff00) | ((value & 0xff) << 16);
      }
    } else {
      for (i = k = 0, ref3 = data.length; 0 <= ref3 ? k < ref3 : k > ref3; i = 0 <= ref3 ? ++k : --k) {
        d = data[i];
        if (d > high) {
          d = high;
        } else if (d < low) {
          d = low;
        }
        log = Math.log1p(d) - Math.log1p(low);
        value = this._palette[Math.floor(log * scale)];
        color[i] = (value << 8) | 0xff;
      }
    }
    return buf;
  };

  return LogColorMapper;

})(ColorMapper.Model);

module.exports = {
  Model: LogColorMapper
};

},{"../../core/properties":"core/properties","./color_mapper":"models/mappers/color_mapper","underscore":"underscore"}],"models/mappers/log_mapper":[function(require,module,exports){
var LogMapper, Model, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Model = require("../../model");

p = require("../../core/properties");

LogMapper = (function(superClass) {
  extend(LogMapper, superClass);

  function LogMapper() {
    return LogMapper.__super__.constructor.apply(this, arguments);
  }

  LogMapper.prototype.initialize = function(attrs, options) {
    LogMapper.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('mapper_state', this._mapper_state, true);
    this.add_dependencies('mapper_state', this, ['source_range', 'target_range']);
    this.add_dependencies('mapper_state', this.get('source_range'), ['start', 'end']);
    return this.add_dependencies('mapper_state', this.get('target_range'), ['start', 'end']);
  };

  LogMapper.prototype.map_to_target = function(x) {
    var inter_offset, inter_scale, intermediate, offset, ref, result, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    result = 0;
    if (inter_scale === 0) {
      intermediate = 0;
    } else {
      intermediate = (Math.log(x) - inter_offset) / inter_scale;
      if (isNaN(intermediate) || !isFinite(intermediate)) {
        intermediate = 0;
      }
    }
    result = intermediate * scale + offset;
    return result;
  };

  LogMapper.prototype.v_map_to_target = function(xs) {
    var idx, inter_offset, inter_scale, intermediate, j, k, len, len1, offset, ref, result, scale, x;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    result = new Float64Array(xs.length);
    if (inter_scale === 0) {
      intermediate = xs.map(function(i) {
        return 0;
      });
    } else {
      intermediate = xs.map(function(i) {
        return (Math.log(i) - inter_offset) / inter_scale;
      });
      for (idx = j = 0, len = intermediate.length; j < len; idx = ++j) {
        x = intermediate[idx];
        if (isNaN(intermediate[idx]) || !isFinite(intermediate[idx])) {
          intermediate[idx] = 0;
        }
      }
    }
    for (idx = k = 0, len1 = xs.length; k < len1; idx = ++k) {
      x = xs[idx];
      result[idx] = intermediate[idx] * scale + offset;
    }
    return result;
  };

  LogMapper.prototype.map_from_target = function(xprime) {
    var inter_offset, inter_scale, intermediate, offset, ref, scale;
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    intermediate = (xprime - offset) / scale;
    intermediate = Math.exp(inter_scale * intermediate + inter_offset);
    return intermediate;
  };

  LogMapper.prototype.v_map_from_target = function(xprimes) {
    var idx, inter_offset, inter_scale, intermediate, j, len, offset, ref, result, scale, x;
    result = new Float64Array(xprimes.length);
    ref = this.get('mapper_state'), scale = ref[0], offset = ref[1], inter_scale = ref[2], inter_offset = ref[3];
    intermediate = xprimes.map(function(i) {
      return (i - offset) / scale;
    });
    for (idx = j = 0, len = xprimes.length; j < len; idx = ++j) {
      x = xprimes[idx];
      result[idx] = Math.exp(inter_scale * intermediate[idx] + inter_offset);
    }
    return result;
  };

  LogMapper.prototype._get_safe_scale = function(orig_start, orig_end) {
    var end, log_val, ref, start;
    if (orig_start < 0) {
      start = 0;
    } else {
      start = orig_start;
    }
    if (orig_end < 0) {
      end = 0;
    } else {
      end = orig_end;
    }
    if (start === end) {
      if (start === 0) {
        ref = [1, 10], start = ref[0], end = ref[1];
      } else {
        log_val = Math.log(start) / Math.log(10);
        start = Math.pow(10, Math.floor(log_val));
        if (Math.ceil(log_val) !== Math.floor(log_val)) {
          end = Math.pow(10, Math.ceil(log_val));
        } else {
          end = Math.pow(10, Math.ceil(log_val) + 1);
        }
      }
    }
    return [start, end];
  };

  LogMapper.prototype._mapper_state = function() {
    var end, inter_offset, inter_scale, offset, ref, scale, screen_range, source_end, source_start, start, target_end, target_start;
    source_start = this.get('source_range').get('start');
    source_end = this.get('source_range').get('end');
    target_start = this.get('target_range').get('start');
    target_end = this.get('target_range').get('end');
    screen_range = target_end - target_start;
    ref = this._get_safe_scale(source_start, source_end), start = ref[0], end = ref[1];
    if (start === 0) {
      inter_scale = Math.log(end);
      inter_offset = 0;
    } else {
      inter_scale = Math.log(end) - Math.log(start);
      inter_offset = Math.log(start);
    }
    scale = screen_range;
    offset = target_start;
    return [scale, offset, inter_scale, inter_offset];
  };

  LogMapper.internal({
    source_range: [p.Any],
    target_range: [p.Any]
  });

  return LogMapper;

})(Model);

module.exports = {
  Model: LogMapper
};

},{"../../core/properties":"core/properties","../../model":"model"}],"models/markers/asterisk":[function(require,module,exports){
var Asterisk, AsteriskView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

AsteriskView = (function(superClass) {
  extend(AsteriskView, superClass);

  function AsteriskView() {
    return AsteriskView.__super__.constructor.apply(this, arguments);
  }

  AsteriskView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, r2, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      r2 = r * 0.65;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(0, -r);
      ctx.moveTo(-r, 0);
      ctx.lineTo(r, 0);
      ctx.moveTo(-r2, r2);
      ctx.lineTo(r2, -r2);
      ctx.moveTo(-r2, -r2);
      ctx.lineTo(r2, r2);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return AsteriskView;

})(Marker.View);

Asterisk = (function(superClass) {
  extend(Asterisk, superClass);

  function Asterisk() {
    return Asterisk.__super__.constructor.apply(this, arguments);
  }

  Asterisk.prototype.default_view = AsteriskView;

  Asterisk.prototype.type = 'Asterisk';

  return Asterisk;

})(Marker.Model);

module.exports = {
  Model: Asterisk,
  View: AsteriskView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/circle_cross":[function(require,module,exports){
var CircleCross, CircleCrossView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

CircleCrossView = (function(superClass) {
  extend(CircleCrossView, superClass);

  function CircleCrossView() {
    return CircleCrossView.__super__.constructor.apply(this, arguments);
  }

  CircleCrossView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        if (_angle[i]) {
          ctx.rotate(_angle[i]);
        }
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
        if (_angle[i]) {
          ctx.rotate(-_angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return CircleCrossView;

})(Marker.View);

CircleCross = (function(superClass) {
  extend(CircleCross, superClass);

  function CircleCross() {
    return CircleCross.__super__.constructor.apply(this, arguments);
  }

  CircleCross.prototype.default_view = CircleCrossView;

  CircleCross.prototype.type = 'CircleCross';

  return CircleCross;

})(Marker.Model);

module.exports = {
  Model: CircleCross,
  View: CircleCrossView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/circle_x":[function(require,module,exports){
var CircleX, CircleXView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

CircleXView = (function(superClass) {
  extend(CircleXView, superClass);

  function CircleXView() {
    return CircleXView.__super__.constructor.apply(this, arguments);
  }

  CircleXView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        if (_angle[i]) {
          ctx.rotate(_angle[i]);
        }
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        if (_angle[i]) {
          ctx.rotate(-_angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return CircleXView;

})(Marker.View);

CircleX = (function(superClass) {
  extend(CircleX, superClass);

  function CircleX() {
    return CircleX.__super__.constructor.apply(this, arguments);
  }

  CircleX.prototype.default_view = CircleXView;

  CircleX.prototype.type = 'CircleX';

  return CircleX;

})(Marker.Model);

module.exports = {
  Model: CircleX,
  View: CircleXView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/cross":[function(require,module,exports){
var Cross, CrossView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

CrossView = (function(superClass) {
  extend(CrossView, superClass);

  function CrossView() {
    return CrossView.__super__.constructor.apply(this, arguments);
  }

  CrossView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(0, -r);
      ctx.moveTo(-r, 0);
      ctx.lineTo(r, 0);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        if (_angle[i]) {
          ctx.rotate(_angle[i]);
        }
        ctx.stroke();
        if (_angle[i]) {
          ctx.rotate(-_angle[i]);
        }
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return CrossView;

})(Marker.View);

Cross = (function(superClass) {
  extend(Cross, superClass);

  function Cross() {
    return Cross.__super__.constructor.apply(this, arguments);
  }

  Cross.prototype.default_view = CrossView;

  Cross.prototype.type = 'Cross';

  return Cross;

})(Marker.Model);

module.exports = {
  Model: Cross,
  View: CrossView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/diamond":[function(require,module,exports){
var Diamond, DiamondView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

DiamondView = (function(superClass) {
  extend(DiamondView, superClass);

  function DiamondView() {
    return DiamondView.__super__.constructor.apply(this, arguments);
  }

  DiamondView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(r / 1.5, 0);
      ctx.lineTo(0, -r);
      ctx.lineTo(-r / 1.5, 0);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      ctx.translate(-sx[i], -sy[i]);
      ctx.closePath();
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return DiamondView;

})(Marker.View);

Diamond = (function(superClass) {
  extend(Diamond, superClass);

  function Diamond() {
    return Diamond.__super__.constructor.apply(this, arguments);
  }

  Diamond.prototype.default_view = DiamondView;

  Diamond.prototype.type = 'Diamond';

  return Diamond;

})(Marker.Model);

module.exports = {
  Model: Diamond,
  View: DiamondView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/diamond_cross":[function(require,module,exports){
var DiamondCross, DiamondCrossView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

DiamondCrossView = (function(superClass) {
  extend(DiamondCrossView, superClass);

  function DiamondCrossView() {
    return DiamondCrossView.__super__.constructor.apply(this, arguments);
  }

  DiamondCrossView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(0, r);
      ctx.lineTo(r / 1.5, 0);
      ctx.lineTo(0, -r);
      ctx.lineTo(-r / 1.5, 0);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      ctx.closePath();
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        if (_angle[i]) {
          ctx.rotate(_angle[i]);
        }
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r / 1.5, 0);
        ctx.lineTo(r / 1.5, 0);
        if (_angle[i]) {
          ctx.rotate(-_angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return DiamondCrossView;

})(Marker.View);

DiamondCross = (function(superClass) {
  extend(DiamondCross, superClass);

  function DiamondCross() {
    return DiamondCross.__super__.constructor.apply(this, arguments);
  }

  DiamondCross.prototype.default_view = DiamondCrossView;

  DiamondCross.prototype.type = 'DiamondCross';

  return DiamondCross;

})(Marker.Model);

module.exports = {
  Model: DiamondCross,
  View: DiamondCrossView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/inverted_triangle":[function(require,module,exports){
var InvertedTriangle, InvertedTriangleView, Marker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

InvertedTriangleView = (function(superClass) {
  extend(InvertedTriangleView, superClass);

  function InvertedTriangleView() {
    return InvertedTriangleView.__super__.constructor.apply(this, arguments);
  }

  InvertedTriangleView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, a, h, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      a = _size[i] * Math.sqrt(3) / 6;
      r = _size[i] / 2;
      h = _size[i] * Math.sqrt(3) / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(-r, -a);
      ctx.lineTo(r, -a);
      ctx.lineTo(0, -a + h);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      ctx.translate(-sx[i], -sy[i]);
      ctx.closePath();
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return InvertedTriangleView;

})(Marker.View);

InvertedTriangle = (function(superClass) {
  extend(InvertedTriangle, superClass);

  function InvertedTriangle() {
    return InvertedTriangle.__super__.constructor.apply(this, arguments);
  }

  InvertedTriangle.prototype.default_view = InvertedTriangleView;

  InvertedTriangle.prototype.type = 'InvertedTriangle';

  return InvertedTriangle;

})(Marker.Model);

module.exports = {
  Model: InvertedTriangle,
  View: InvertedTriangleView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/marker":[function(require,module,exports){
var Glyph, Marker, MarkerView, _, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Glyph = require("../glyphs/glyph");

hittest = require("../../common/hittest");

p = require("../../core/properties");

MarkerView = (function(superClass) {
  extend(MarkerView, superClass);

  function MarkerView() {
    return MarkerView.__super__.constructor.apply(this, arguments);
  }

  MarkerView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    var angle, data, indices, ref, reference_point, size, sx, sy;
    reference_point = (ref = this.get_reference_point()) != null ? ref : 0;
    indices = [reference_point];
    sx = {};
    sx[reference_point] = (x0 + x1) / 2;
    sy = {};
    sy[reference_point] = (y0 + y1) / 2;
    size = {};
    size[reference_point] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
    angle = {};
    angle[reference_point] = 0;
    data = {
      sx: sx,
      sy: sy,
      _size: size,
      _angle: angle
    };
    return this._render(ctx, indices, data);
  };

  MarkerView.prototype._index_data = function() {
    return this._xy_index();
  };

  MarkerView.prototype._mask_data = function(all_indices) {
    var bbox, hr, ref, ref1, vr, vx0, vx1, vy0, vy1, x, x0, x1, y0, y1;
    hr = this.renderer.plot_view.frame.get('h_range');
    vx0 = hr.get('start') - this.max_size;
    vx1 = hr.get('end') + this.max_size;
    ref = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref[0], x1 = ref[1];
    vr = this.renderer.plot_view.frame.get('v_range');
    vy0 = vr.get('start') - this.max_size;
    vy1 = vr.get('end') + this.max_size;
    ref1 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref1[0], y1 = ref1[1];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    return (function() {
      var j, len, ref2, results;
      ref2 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
  };

  MarkerView.prototype._hit_point = function(geometry) {
    var bbox, candidates, dist, hits, i, j, len, ref, ref1, ref2, result, s2, sx, sy, vx, vx0, vx1, vy, vy0, vy1, x, x0, x1, y0, y1;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    sx = this.renderer.plot_view.canvas.vx_to_sx(vx);
    sy = this.renderer.plot_view.canvas.vy_to_sy(vy);
    vx0 = vx - this.max_size;
    vx1 = vx + this.max_size;
    ref1 = this.renderer.xmapper.v_map_from_target([vx0, vx1], true), x0 = ref1[0], x1 = ref1[1];
    vy0 = vy - this.max_size;
    vy1 = vy + this.max_size;
    ref2 = this.renderer.ymapper.v_map_from_target([vy0, vy1], true), y0 = ref2[0], y1 = ref2[1];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    candidates = (function() {
      var j, len, ref3, results;
      ref3 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref3.length; j < len; j++) {
        x = ref3[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
    hits = [];
    for (j = 0, len = candidates.length; j < len; j++) {
      i = candidates[j];
      s2 = this._size[i] / 2;
      dist = Math.abs(this.sx[i] - sx) + Math.abs(this.sy[i] - sy);
      if (Math.abs(this.sx[i] - sx) <= s2 && Math.abs(this.sy[i] - sy) <= s2) {
        hits.push([i, dist]);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = _.chain(hits).sortBy(function(elt) {
      return elt[1];
    }).map(function(elt) {
      return elt[0];
    }).value();
    return result;
  };

  MarkerView.prototype._hit_rect = function(geometry) {
    var bbox, ref, ref1, result, x, x0, x1, y0, y1;
    ref = this.renderer.xmapper.v_map_from_target([geometry.vx0, geometry.vx1], true), x0 = ref[0], x1 = ref[1];
    ref1 = this.renderer.ymapper.v_map_from_target([geometry.vy0, geometry.vy1], true), y0 = ref1[0], y1 = ref1[1];
    bbox = hittest.validate_bbox_coords([x0, x1], [y0, y1]);
    result = hittest.create_hit_test_result();
    result['1d'].indices = (function() {
      var j, len, ref2, results;
      ref2 = this.index.search(bbox);
      results = [];
      for (j = 0, len = ref2.length; j < len; j++) {
        x = ref2[j];
        results.push(x.i);
      }
      return results;
    }).call(this);
    return result;
  };

  MarkerView.prototype._hit_poly = function(geometry) {
    var candidates, hits, i, idx, j, k, ref, ref1, ref2, result, results, sx, sy, vx, vy;
    ref = [geometry.vx, geometry.vy], vx = ref[0], vy = ref[1];
    sx = this.renderer.plot_view.canvas.v_vx_to_sx(vx);
    sy = this.renderer.plot_view.canvas.v_vy_to_sy(vy);
    candidates = (function() {
      results = [];
      for (var j = 0, ref1 = this.sx.length; 0 <= ref1 ? j < ref1 : j > ref1; 0 <= ref1 ? j++ : j--){ results.push(j); }
      return results;
    }).apply(this);
    hits = [];
    for (i = k = 0, ref2 = candidates.length; 0 <= ref2 ? k < ref2 : k > ref2; i = 0 <= ref2 ? ++k : --k) {
      idx = candidates[i];
      if (hittest.point_in_poly(this.sx[i], this.sy[i], sx, sy)) {
        hits.push(idx);
      }
    }
    result = hittest.create_hit_test_result();
    result['1d'].indices = hits;
    return result;
  };

  return MarkerView;

})(Glyph.View);

Marker = (function(superClass) {
  extend(Marker, superClass);

  function Marker() {
    return Marker.__super__.constructor.apply(this, arguments);
  }

  Marker.coords([['x', 'y']]);

  Marker.mixins(['line', 'fill']);

  Marker.define({
    size: [
      p.DistanceSpec, {
        units: "screen",
        value: 4
      }
    ],
    angle: [p.AngleSpec, 0]
  });

  return Marker;

})(Glyph.Model);

module.exports = {
  Model: Marker,
  View: MarkerView
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","../glyphs/glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/markers/square":[function(require,module,exports){
var Marker, Square, SquareView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

SquareView = (function(superClass) {
  extend(SquareView, superClass);

  function SquareView() {
    return SquareView.__super__.constructor.apply(this, arguments);
  }

  SquareView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.rect(-_size[i] / 2, -_size[i] / 2, _size[i], _size[i]);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return SquareView;

})(Marker.View);

Square = (function(superClass) {
  extend(Square, superClass);

  function Square() {
    return Square.__super__.constructor.apply(this, arguments);
  }

  Square.prototype.default_view = SquareView;

  Square.prototype.type = 'Square';

  return Square;

})(Marker.Model);

module.exports = {
  Model: Square,
  View: SquareView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/square_cross":[function(require,module,exports){
var Marker, SquareCross, SquareCrossView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

SquareCrossView = (function(superClass) {
  extend(SquareCrossView, superClass);

  function SquareCrossView() {
    return SquareCrossView.__super__.constructor.apply(this, arguments);
  }

  SquareCrossView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.rect(-_size[i] / 2, -_size[i] / 2, _size[i], _size[i]);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        r = _size[i] / 2;
        if (_angle[i]) {
          ctx.rotate(_angle[i]);
        }
        ctx.moveTo(0, r);
        ctx.lineTo(0, -r);
        ctx.moveTo(-r, 0);
        ctx.lineTo(r, 0);
        if (_angle[i]) {
          ctx.rotate(-_angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return SquareCrossView;

})(Marker.View);

SquareCross = (function(superClass) {
  extend(SquareCross, superClass);

  function SquareCross() {
    return SquareCross.__super__.constructor.apply(this, arguments);
  }

  SquareCross.prototype.default_view = SquareCrossView;

  SquareCross.prototype.type = 'SquareCross';

  return SquareCross;

})(Marker.Model);

module.exports = {
  Model: SquareCross,
  View: SquareCrossView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/square_x":[function(require,module,exports){
var Marker, SquareX, SquareXView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

SquareXView = (function(superClass) {
  extend(SquareXView, superClass);

  function SquareXView() {
    return SquareXView.__super__.constructor.apply(this, arguments);
  }

  SquareXView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.rect(-_size[i] / 2, -_size[i] / 2, _size[i], _size[i]);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
        r = _size[i] / 2;
        if (_angle[i]) {
          ctx.rotate(_angle[i]);
        }
        ctx.moveTo(-r, r);
        ctx.lineTo(r, -r);
        ctx.moveTo(-r, -r);
        ctx.lineTo(r, r);
        if (_angle[i]) {
          ctx.rotate(-_angle[i]);
        }
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return SquareXView;

})(Marker.View);

SquareX = (function(superClass) {
  extend(SquareX, superClass);

  function SquareX() {
    return SquareX.__super__.constructor.apply(this, arguments);
  }

  SquareX.prototype.default_view = SquareXView;

  SquareX.prototype.type = 'SquareX';

  return SquareX;

})(Marker.Model);

module.exports = {
  Model: SquareX,
  View: SquareXView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/triangle":[function(require,module,exports){
var Marker, Triangle, TriangleView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

TriangleView = (function(superClass) {
  extend(TriangleView, superClass);

  function TriangleView() {
    return TriangleView.__super__.constructor.apply(this, arguments);
  }

  TriangleView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, a, h, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      a = _size[i] * Math.sqrt(3) / 6;
      r = _size[i] / 2;
      h = _size[i] * Math.sqrt(3) / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(-r, a);
      ctx.lineTo(r, a);
      ctx.lineTo(0, a - h);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      ctx.translate(-sx[i], -sy[i]);
      ctx.closePath();
      if (this.visuals.fill.doit) {
        this.visuals.fill.set_vectorize(ctx, i);
        ctx.fill();
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        results.push(ctx.stroke());
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return TriangleView;

})(Marker.View);

Triangle = (function(superClass) {
  extend(Triangle, superClass);

  function Triangle() {
    return Triangle.__super__.constructor.apply(this, arguments);
  }

  Triangle.prototype.default_view = TriangleView;

  Triangle.prototype.type = 'Triangle';

  return Triangle;

})(Marker.Model);

module.exports = {
  Model: Triangle,
  View: TriangleView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/markers/x":[function(require,module,exports){
var Marker, X, XView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Marker = require("./marker");

XView = (function(superClass) {
  extend(XView, superClass);

  function XView() {
    return XView.__super__.constructor.apply(this, arguments);
  }

  XView.prototype._render = function(ctx, indices, arg) {
    var _angle, _size, i, j, len, r, results, sx, sy;
    sx = arg.sx, sy = arg.sy, _size = arg._size, _angle = arg._angle;
    results = [];
    for (j = 0, len = indices.length; j < len; j++) {
      i = indices[j];
      if (isNaN(sx[i] + sy[i] + _size[i] + _angle[i])) {
        continue;
      }
      r = _size[i] / 2;
      ctx.beginPath();
      ctx.translate(sx[i], sy[i]);
      if (_angle[i]) {
        ctx.rotate(_angle[i]);
      }
      ctx.moveTo(-r, r);
      ctx.lineTo(r, -r);
      ctx.moveTo(-r, -r);
      ctx.lineTo(r, r);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      if (this.visuals.line.doit) {
        this.visuals.line.set_vectorize(ctx, i);
        ctx.stroke();
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  return XView;

})(Marker.View);

X = (function(superClass) {
  extend(X, superClass);

  function X() {
    return X.__super__.constructor.apply(this, arguments);
  }

  X.prototype.default_view = XView;

  X.prototype.type = 'X';

  return X;

})(Marker.Model);

module.exports = {
  Model: X,
  View: XView
};

},{"./marker":"models/markers/marker","underscore":"underscore"}],"models/plots/gmap_plot":[function(require,module,exports){
var GMapPlot, GMapPlotCanvas, GMapPlotView, Plot, _, logger, p, proj4, toProjection,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

proj4 = require("proj4");

toProjection = proj4.defs('GOOGLE');

logger = require("../../core/logging").logger;

GMapPlotCanvas = require("./gmap_plot_canvas");

Plot = require("./plot");

p = require("../../core/properties");

GMapPlotView = (function(superClass) {
  extend(GMapPlotView, superClass);

  function GMapPlotView() {
    return GMapPlotView.__super__.constructor.apply(this, arguments);
  }

  return GMapPlotView;

})(Plot.View);

GMapPlot = (function(superClass) {
  extend(GMapPlot, superClass);

  function GMapPlot() {
    return GMapPlot.__super__.constructor.apply(this, arguments);
  }

  GMapPlot.prototype.type = 'GMapPlot';

  GMapPlot.prototype.default_view = GMapPlotView;

  GMapPlot.prototype.initialize = function(options) {
    GMapPlot.__super__.initialize.call(this, options);
    if (!this.api_key) {
      logger.error("api_key is required. See https://developers.google.com/maps/documentation/javascript/get-api-key for more information on how to obtain your own.");
    }
    this._plot_canvas = new GMapPlotCanvas.Model({
      plot: this
    });
    return this.plot_canvas.toolbar = this.toolbar;
  };

  GMapPlot.define({
    map_options: [p.Any],
    api_key: [p.String]
  });

  return GMapPlot;

})(Plot.Model);

module.exports = {
  Model: GMapPlot,
  View: GMapPlotView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./gmap_plot_canvas":"models/plots/gmap_plot_canvas","./plot":"models/plots/plot","proj4":"proj4","underscore":"underscore"}],"models/plots/gmap_plot_canvas":[function(require,module,exports){
var GMapPlotCanvas, GMapPlotCanvasView, PlotCanvas, _, p, proj4, toProjection,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

proj4 = require("proj4");

toProjection = proj4.defs('GOOGLE');

PlotCanvas = require("./plot_canvas");

p = require("../../core/properties");

GMapPlotCanvasView = (function(superClass) {
  extend(GMapPlotCanvasView, superClass);

  function GMapPlotCanvasView() {
    this.setRanges = bind(this.setRanges, this);
    this.getProjectedBounds = bind(this.getProjectedBounds, this);
    this.getLatLngBounds = bind(this.getLatLngBounds, this);
    return GMapPlotCanvasView.__super__.constructor.apply(this, arguments);
  }

  GMapPlotCanvasView.prototype.initialize = function(options) {
    GMapPlotCanvasView.__super__.initialize.call(this, _.defaults(options, this.default_options));
    return this.zoom_count = 0;
  };

  GMapPlotCanvasView.prototype.getLatLngBounds = function() {
    var bottom_left, bounds, top_right, xend, xstart, yend, ystart;
    bounds = this.map.getBounds();
    top_right = bounds.getNorthEast();
    bottom_left = bounds.getSouthWest();
    xstart = bottom_left.lng();
    xend = top_right.lng();
    ystart = bottom_left.lat();
    yend = top_right.lat();
    return [xstart, xend, ystart, yend];
  };

  GMapPlotCanvasView.prototype.getProjectedBounds = function() {
    var proj_xend, proj_xstart, proj_yend, proj_ystart, ref, ref1, ref2, xend, xstart, yend, ystart;
    ref = this.getLatLngBounds(), xstart = ref[0], xend = ref[1], ystart = ref[2], yend = ref[3];
    ref1 = proj4(toProjection, [xstart, ystart]), proj_xstart = ref1[0], proj_ystart = ref1[1];
    ref2 = proj4(toProjection, [xend, yend]), proj_xend = ref2[0], proj_yend = ref2[1];
    return [proj_xstart, proj_xend, proj_ystart, proj_yend];
  };

  GMapPlotCanvasView.prototype.setRanges = function() {
    var proj_xend, proj_xstart, proj_yend, proj_ystart, ref;
    ref = this.getProjectedBounds(), proj_xstart = ref[0], proj_xend = ref[1], proj_ystart = ref[2], proj_yend = ref[3];
    this.x_range.set({
      start: proj_xstart,
      end: proj_xend
    });
    return this.y_range.set({
      start: proj_ystart,
      end: proj_yend
    });
  };

  GMapPlotCanvasView.prototype.update_range = function(range_info) {
    var new_map_zoom, original_map_zoom, proj_xend, proj_xstart, proj_yend, proj_ystart, ref, zoom_change;
    this.pause();
    if ((range_info.sdx != null) || (range_info.sdy != null)) {
      this.map.panBy(range_info.sdx, range_info.sdy);
      GMapPlotCanvasView.__super__.update_range.call(this, range_info);
    }
    if (range_info.factor != null) {
      if (this.zoom_count !== 10) {
        this.zoom_count += 1;
        return;
      }
      this.zoom_count = 0;
      GMapPlotCanvasView.__super__.update_range.call(this, range_info);
      if (range_info.factor < 0) {
        zoom_change = -1;
      } else {
        zoom_change = 1;
      }
      original_map_zoom = this.map.getZoom();
      new_map_zoom = original_map_zoom + zoom_change;
      if (new_map_zoom >= 2) {
        this.map.setZoom(new_map_zoom);
        ref = this.getProjectedBounds(), proj_xstart = ref[0], proj_xend = ref[1], proj_ystart = ref[2], proj_yend = ref[3];
        if ((proj_xend - proj_xstart) < 0) {
          this.map.setZoom(original_map_zoom);
        }
      }
      this.setRanges();
    }
    return this.unpause();
  };

  GMapPlotCanvasView.prototype.bind_bokeh_events = function() {
    var build_map, height, left, script, top, width;
    GMapPlotCanvasView.__super__.bind_bokeh_events.call(this);
    width = this.frame.get('width');
    height = this.frame.get('height');
    left = this.canvas.vx_to_sx(this.frame.get('left'));
    top = this.canvas.vy_to_sy(this.frame.get('top'));
    this.canvas_view.map_div.attr("style", "top: " + top + "px; left: " + left + "px; position: absolute");
    this.canvas_view.map_div.attr('style', "width:" + width + "px;");
    this.canvas_view.map_div.attr('style', "height:" + height + "px;");
    this.canvas_view.map_div.width(width + "px").height(height + "px");
    this.initial_zoom = this.model.plot.map_options.zoom;
    build_map = (function(_this) {
      return function() {
        var map_options, map_types, maps, mo;
        maps = window.google.maps;
        map_types = {
          "satellite": maps.MapTypeId.SATELLITE,
          "terrain": maps.MapTypeId.TERRAIN,
          "roadmap": maps.MapTypeId.ROADMAP,
          "hybrid": maps.MapTypeId.HYBRID
        };
        mo = _this.model.plot.map_options;
        map_options = {
          center: new maps.LatLng(mo.lat, mo.lng),
          zoom: mo.zoom,
          disableDefaultUI: true,
          mapTypeId: map_types[mo.map_type]
        };
        if (mo.styles != null) {
          map_options.styles = JSON.parse(mo.styles);
        }
        _this.map = new maps.Map(_this.canvas_view.map_div[0], map_options);
        return maps.event.addListenerOnce(_this.map, 'idle', _this.setRanges);
      };
    })(this);
    if (window._bokeh_gmap_loads == null) {
      window._bokeh_gmap_loads = [];
    }
    if ((window.google != null) && (window.google.maps != null)) {
      return _.defer(build_map);
    } else if (window._bokeh_gmap_callback != null) {
      return window._bokeh_gmap_loads.push(build_map);
    } else {
      window._bokeh_gmap_loads.push(build_map);
      window._bokeh_gmap_callback = function() {
        return _.each(window._bokeh_gmap_loads, _.defer);
      };
      script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = "https://maps.googleapis.com/maps/api/js?key=" + this.model.plot.api_key + "&callback=_bokeh_gmap_callback";
      return document.body.appendChild(script);
    }
  };

  GMapPlotCanvasView.prototype._map_hook = function(ctx, frame_box) {
    var height, left, top, width;
    left = frame_box[0], top = frame_box[1], width = frame_box[2], height = frame_box[3];
    this.canvas_view.map_div.attr("style", "top: " + top + "px; left: " + left + "px;");
    return this.canvas_view.map_div.width(width + "px").height(height + "px");
  };

  GMapPlotCanvasView.prototype._paint_empty = function(ctx, frame_box) {
    var ih, iw, left, oh, ow, top;
    ow = this.canvas.get('width');
    oh = this.canvas.get('height');
    left = frame_box[0], top = frame_box[1], iw = frame_box[2], ih = frame_box[3];
    ctx.clearRect(0, 0, ow, oh);
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(0, oh);
    ctx.lineTo(ow, oh);
    ctx.lineTo(ow, 0);
    ctx.lineTo(0, 0);
    ctx.moveTo(left, top);
    ctx.lineTo(left + iw, top);
    ctx.lineTo(left + iw, top + ih);
    ctx.lineTo(left, top + ih);
    ctx.lineTo(left, top);
    ctx.closePath();
    ctx.fillStyle = this.model.plot.border_fill_color;
    return ctx.fill();
  };

  return GMapPlotCanvasView;

})(PlotCanvas.View);

GMapPlotCanvas = (function(superClass) {
  extend(GMapPlotCanvas, superClass);

  function GMapPlotCanvas() {
    return GMapPlotCanvas.__super__.constructor.apply(this, arguments);
  }

  GMapPlotCanvas.prototype.type = 'GMapPlotCanvas';

  GMapPlotCanvas.prototype.default_view = GMapPlotCanvasView;

  GMapPlotCanvas.prototype.initialize = function(attrs, options) {
    this.use_map = true;
    return GMapPlotCanvas.__super__.initialize.call(this, attrs, options);
  };

  return GMapPlotCanvas;

})(PlotCanvas.Model);

module.exports = {
  Model: GMapPlotCanvas,
  View: GMapPlotCanvasView
};

},{"../../core/properties":"core/properties","./plot_canvas":"models/plots/plot_canvas","proj4":"proj4","underscore":"underscore"}],"models/plots/plot":[function(require,module,exports){
var ColumnDataSource, EQ, GE, GlyphRenderer, LayoutDOM, Plot, PlotCanvas, PlotView, Strength, Title, ToolEvents, Toolbar, Variable, WEAK_EQ, _, logger, p, ref,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  slice = [].slice;

_ = require("underscore");

ref = require("../../core/layout/solver"), WEAK_EQ = ref.WEAK_EQ, GE = ref.GE, EQ = ref.EQ, Strength = ref.Strength, Variable = ref.Variable;

logger = require("../../core/logging").logger;

p = require("../../core/properties");

LayoutDOM = require("../layouts/layout_dom");

Title = require("../annotations/title");

Toolbar = require("../tools/toolbar");

ToolEvents = require("../../common/tool_events");

PlotCanvas = require("./plot_canvas").Model;

ColumnDataSource = require("../sources/column_data_source");

GlyphRenderer = require("../renderers/glyph_renderer");

Title = require("../annotations/title");

PlotView = (function(superClass) {
  extend(PlotView, superClass);

  function PlotView() {
    return PlotView.__super__.constructor.apply(this, arguments);
  }

  PlotView.prototype.className = "bk-plot-layout";

  PlotView.prototype.bind_bokeh_events = function() {
    var title_msg;
    PlotView.__super__.bind_bokeh_events.call(this);
    title_msg = "Title object cannot be replaced. Try changing properties on title to update it after initialization.";
    return this.listenTo(this.model, 'change:title', (function(_this) {
      return function() {
        return logger.warn(title_msg);
      };
    })(this));
  };

  PlotView.prototype.render = function() {
    var height, ref1, s, width;
    PlotView.__super__.render.call(this);
    if (this.model.sizing_mode === 'scale_both') {
      ref1 = this.get_width_height(), width = ref1[0], height = ref1[1];
      s = this.model.document.solver();
      s.suggest_value(this.model._width, width);
      s.suggest_value(this.model._height, height);
      return this.$el.css({
        position: 'absolute',
        left: this.model._dom_left._value,
        top: this.model._dom_top._value,
        width: this.model._width.value(),
        height: this.model._height.value()
      });
    }
  };

  PlotView.prototype.get_width_height = function() {
    var ar, height, new_height_1, new_height_2, new_width_1, new_width_2, parent_height, parent_width, width;
    parent_height = this.el.parentNode.clientHeight;
    parent_width = this.el.parentNode.clientWidth;
    ar = this.model.get_aspect_ratio();
    new_width_1 = parent_width;
    new_height_1 = parent_width / ar;
    new_width_2 = parent_height * ar;
    new_height_2 = parent_height;
    if (new_width_1 < new_width_2) {
      width = new_width_1;
      height = new_height_1;
    } else {
      width = new_width_2;
      height = new_height_2;
    }
    return [width, height];
  };

  PlotView.prototype.get_height = function() {
    return this.model._width._value / this.model.get_aspect_ratio();
  };

  PlotView.prototype.get_width = function() {
    return this.model._height._value * this.model.get_aspect_ratio();
  };

  return PlotView;

})(LayoutDOM.View);

Plot = (function(superClass) {
  extend(Plot, superClass);

  function Plot() {
    return Plot.__super__.constructor.apply(this, arguments);
  }

  Plot.prototype.type = 'Plot';

  Plot.prototype.default_view = PlotView;

  Plot.prototype.initialize = function(options) {
    var i, j, len, len1, plots, ref1, ref2, ref3, title, xr, yr;
    Plot.__super__.initialize.call(this, options);
    ref1 = _.values(this.extra_x_ranges).concat(this.x_range);
    for (i = 0, len = ref1.length; i < len; i++) {
      xr = ref1[i];
      plots = xr.get('plots');
      if (_.isArray(plots)) {
        plots = plots.concat(this);
        xr.set('plots', plots);
      }
    }
    ref2 = _.values(this.extra_y_ranges).concat(this.y_range);
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      yr = ref2[j];
      plots = yr.get('plots');
      if (_.isArray(plots)) {
        plots = plots.concat(this);
        yr.set('plots', plots);
      }
    }
    this._horizontal = false;
    if ((ref3 = this.toolbar_location) === 'left' || ref3 === 'right') {
      this._horizontal = true;
    }
    if (this.min_border != null) {
      if (this.min_border_top == null) {
        this.min_border_top = this.min_border;
      }
      if (this.min_border_bottom == null) {
        this.min_border_bottom = this.min_border;
      }
      if (this.min_border_left == null) {
        this.min_border_left = this.min_border;
      }
      if (this.min_border_right == null) {
        this.min_border_right = this.min_border;
      }
    }
    if (this.title != null) {
      title = _.isString(this.title) ? new Title.Model({
        text: this.title
      }) : this.title;
      this.add_layout(title, this.title_location);
    }
    this._plot_canvas = new PlotCanvas({
      plot: this
    });
    this.toolbar.toolbar_location = this.toolbar_location;
    this.toolbar.toolbar_sticky = this.toolbar_sticky;
    this.plot_canvas.toolbar = this.toolbar;
    if (this.width == null) {
      this.width = this.plot_width;
    }
    if (this.height == null) {
      return this.height = this.plot_height;
    }
  };

  Object.defineProperty(Plot.prototype, "plot_canvas", {
    get: function() {
      return this._plot_canvas;
    }
  });

  Plot.prototype._doc_attached = function() {
    var i, j, layout_renderers, len, len1, r, ref1, side;
    ref1 = ['above', 'below', 'left', 'right'];
    for (i = 0, len = ref1.length; i < len; i++) {
      side = ref1[i];
      layout_renderers = this.get(side);
      for (j = 0, len1 = layout_renderers.length; j < len1; j++) {
        r = layout_renderers[j];
        this.plot_canvas.add_renderer_to_canvas_side(r, side);
      }
    }
    this.plot_canvas.attach_document(this.document);
    this._set_orientation_variables(this);
    this._set_orientation_variables(this.toolbar);
    return this._set_orientation_variables(this.plot_canvas);
  };

  Plot.prototype.add_renderers = function() {
    var new_renderers, renderers;
    new_renderers = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    renderers = this.get('renderers');
    renderers = renderers.concat(new_renderers);
    return this.set('renderers', renderers);
  };

  Plot.prototype.add_layout = function(renderer, side) {
    var side_renderers;
    if (side == null) {
      side = "center";
    }
    if (renderer.props.plot != null) {
      renderer.plot = this;
    }
    this.add_renderers(renderer);
    if (side !== 'center') {
      side_renderers = this.get(side);
      return side_renderers.push(renderer);
    }
  };

  Plot.prototype.add_glyph = function(glyph, source, attrs) {
    var renderer;
    if (attrs == null) {
      attrs = {};
    }
    if (source == null) {
      source = new ColumnDataSource.Model();
    }
    attrs = _.extend({}, attrs, {
      data_source: source,
      glyph: glyph
    });
    renderer = new GlyphRenderer.Model(attrs);
    this.add_renderers(renderer);
    return renderer;
  };

  Plot.prototype.add_tools = function() {
    var attrs, new_tools, tool, tools;
    tools = 1 <= arguments.length ? slice.call(arguments, 0) : [];
    new_tools = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = tools.length; i < len; i++) {
        tool = tools[i];
        if (tool.overlay != null) {
          this.add_renderers(tool.overlay);
        }
        if (tool.plot != null) {
          results.push(tool);
        } else {
          attrs = _.clone(tool.attributes);
          attrs.plot = this;
          results.push(new tool.constructor(attrs));
        }
      }
      return results;
    }).call(this);
    return this.toolbar.tools = this.toolbar.tools.concat(new_tools);
  };

  Plot.prototype.get_aspect_ratio = function() {
    return this.width / this.height;
  };

  Plot.prototype.get_layoutable_children = function() {
    var children;
    children = [this.plot_canvas];
    if (this.toolbar_location != null) {
      children = [this.toolbar, this.plot_canvas];
    }
    return children;
  };

  Plot.prototype.get_edit_variables = function() {
    var child, edit_variables, i, len, ref1;
    edit_variables = Plot.__super__.get_edit_variables.call(this);
    if (this.sizing_mode === 'scale_both') {
      edit_variables.push({
        edit_variable: this._width,
        strength: Strength.strong
      });
      edit_variables.push({
        edit_variable: this._height,
        strength: Strength.strong
      });
    }
    ref1 = this.get_layoutable_children();
    for (i = 0, len = ref1.length; i < len; i++) {
      child = ref1[i];
      edit_variables = edit_variables.concat(child.get_edit_variables());
    }
    return edit_variables;
  };

  Plot.prototype.get_constraints = function() {
    var child, constraints, i, len, ref1, ref2, ref3, sticky_edge;
    constraints = Plot.__super__.get_constraints.call(this);
    if (this.toolbar_location != null) {
      if (this.toolbar_sticky === true) {
        constraints.push(EQ(this._sizeable, [-1, this.plot_canvas._sizeable]));
      } else {
        constraints.push(EQ(this._sizeable, [-1, this.plot_canvas._sizeable], [-1, this.toolbar._sizeable]));
      }
      constraints.push(EQ(this._full, [-1, this.plot_canvas._full]));
      if (this.toolbar_location === 'above') {
        sticky_edge = this.toolbar_sticky === true ? this.plot_canvas._top : this.plot_canvas._dom_top;
        constraints.push(EQ(sticky_edge, [-1, this.toolbar._dom_top], [-1, this.toolbar._height]));
      }
      if (this.toolbar_location === 'below') {
        if (this.toolbar_sticky === false) {
          constraints.push(EQ(this.toolbar._dom_top, [-1, this.plot_canvas._height], this.toolbar._bottom, [-1, this.toolbar._height]));
        }
        if (this.toolbar_sticky === true) {
          constraints.push(GE(this.plot_canvas.below_panel._height, [-1, this.toolbar._height]));
          constraints.push(WEAK_EQ(this.toolbar._dom_top, [-1, this.plot_canvas._height], this.plot_canvas.below_panel._height));
        }
      }
      if (this.toolbar_location === 'left') {
        sticky_edge = this.toolbar_sticky === true ? this.plot_canvas._left : this.plot_canvas._dom_left;
        constraints.push(EQ(sticky_edge, [-1, this.toolbar._dom_left], [-1, this.toolbar._width]));
      }
      if (this.toolbar_location === 'right') {
        if (this.toolbar_sticky === false) {
          constraints.push(EQ(this.toolbar._dom_left, [-1, this.plot_canvas._width], this.toolbar._right, [-1, this.toolbar._width]));
        }
        if (this.toolbar_sticky === true) {
          constraints.push(GE(this.plot_canvas.right_panel._width, [-1, this.toolbar._width]));
          constraints.push(WEAK_EQ(this.toolbar._dom_left, [-1, this.plot_canvas._width], this.plot_canvas.right_panel._width));
        }
      }
      if ((ref1 = this.toolbar_location) === 'above' || ref1 === 'below') {
        constraints.push(EQ(this._width, [-1, this.toolbar._width], [-1, this.plot_canvas._width_minus_right]));
      }
      if ((ref2 = this.toolbar_location) === 'left' || ref2 === 'right') {
        constraints.push(EQ(this._height, [-1, this.toolbar._height], [-1, this.plot_canvas.above_panel._height]));
        constraints.push(EQ(this.toolbar._dom_top, [-1, this.plot_canvas.above_panel._height]));
      }
    }
    if (this.toolbar_location == null) {
      constraints.push(EQ(this._width, [-1, this.plot_canvas._width]));
      constraints.push(EQ(this._height, [-1, this.plot_canvas._height]));
    }
    ref3 = this.get_layoutable_children();
    for (i = 0, len = ref3.length; i < len; i++) {
      child = ref3[i];
      constraints = constraints.concat(child.get_constraints());
    }
    return constraints;
  };

  Plot.prototype.get_constrained_variables = function() {
    var constrained_variables;
    constrained_variables = Plot.__super__.get_constrained_variables.call(this);
    constrained_variables = _.extend(constrained_variables, {
      'on-edge-align-top': this.plot_canvas._top,
      'on-edge-align-bottom': this.plot_canvas._height_minus_bottom,
      'on-edge-align-left': this.plot_canvas._left,
      'on-edge-align-right': this.plot_canvas._width_minus_right,
      'box-cell-align-top': this.plot_canvas._top,
      'box-cell-align-bottom': this.plot_canvas._height_minus_bottom,
      'box-cell-align-left': this.plot_canvas._left,
      'box-cell-align-right': this.plot_canvas._width_minus_right,
      'box-equal-size-top': this.plot_canvas._top,
      'box-equal-size-bottom': this.plot_canvas._height_minus_bottom
    });
    if (this.sizing_mode !== 'fixed') {
      constrained_variables = _.extend(constrained_variables, {
        'box-equal-size-left': this.plot_canvas._left,
        'box-equal-size-right': this.plot_canvas._width_minus_right
      });
    }
    return constrained_variables;
  };

  Plot.prototype._set_orientation_variables = function(model) {
    if (this._horizontal === false) {
      model._sizeable = model._height;
      model._full = model._width;
    }
    if (this._horizontal === true) {
      model._sizeable = model._width;
      return model._full = model._height;
    }
  };

  Plot.mixins(['line:outline_', 'fill:background_', 'fill:border_']);

  Plot.define({
    toolbar: [
      p.Instance, function() {
        return new Toolbar.Model();
      }
    ],
    toolbar_location: [p.Location, 'right'],
    toolbar_sticky: [p.Bool, true],
    plot_width: [p.Number, 600],
    plot_height: [p.Number, 600],
    title: [
      p.Any, function() {
        return new Title.Model({
          text: ""
        });
      }
    ],
    title_location: [p.Location, 'above'],
    h_symmetry: [p.Bool, true],
    v_symmetry: [p.Bool, false],
    above: [p.Array, []],
    below: [p.Array, []],
    left: [p.Array, []],
    right: [p.Array, []],
    renderers: [p.Array, []],
    x_range: [p.Instance],
    extra_x_ranges: [p.Any, {}],
    y_range: [p.Instance],
    extra_y_ranges: [p.Any, {}],
    x_mapper_type: [p.String, 'auto'],
    y_mapper_type: [p.String, 'auto'],
    tool_events: [
      p.Instance, function() {
        return new ToolEvents.Model();
      }
    ],
    lod_factor: [p.Number, 10],
    lod_interval: [p.Number, 300],
    lod_threshold: [p.Number, 2000],
    lod_timeout: [p.Number, 500],
    webgl: [p.Bool, false],
    hidpi: [p.Bool, true],
    min_border: [p.Number, 5],
    min_border_top: [p.Number, null],
    min_border_left: [p.Number, null],
    min_border_bottom: [p.Number, null],
    min_border_right: [p.Number, null]
  });

  Plot.override({
    outline_line_color: '#e5e5e5',
    border_fill_color: "#ffffff",
    background_fill_color: "#ffffff"
  });

  return Plot;

})(LayoutDOM.Model);

module.exports = {
  View: PlotView,
  Model: Plot
};

},{"../../common/tool_events":"common/tool_events","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../annotations/title":"models/annotations/title","../layouts/layout_dom":"models/layouts/layout_dom","../renderers/glyph_renderer":"models/renderers/glyph_renderer","../sources/column_data_source":"models/sources/column_data_source","../tools/toolbar":"models/tools/toolbar","./plot_canvas":"models/plots/plot_canvas","underscore":"underscore"}],"models/plots/plot_canvas":[function(require,module,exports){
var $, Canvas, CartesianFrame, DataRange1d, EQ, GE, GlyphRenderer, LayoutCanvas, LayoutDOM, PlotCanvas, PlotCanvasView, Renderer, UIEvents, _, build_views, enums, global_gl_canvas, logger, p, ref, throttle, update_panel_constraints,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

_ = require("underscore");

$ = require("jquery");

Canvas = require("../canvas/canvas");

CartesianFrame = require("../canvas/cartesian_frame");

DataRange1d = require("../ranges/data_range1d");

GlyphRenderer = require("../renderers/glyph_renderer");

LayoutDOM = require("../layouts/layout_dom");

Renderer = require("../renderers/renderer");

build_views = require("../../common/build_views");

UIEvents = require("../../common/ui_events");

enums = require("../../core/enums");

LayoutCanvas = require("../../core/layout/layout_canvas");

ref = require("../../core/layout/solver"), EQ = ref.EQ, GE = ref.GE;

logger = require("../../core/logging").logger;

p = require("../../core/properties");

throttle = require("../../core/util/throttle").throttle;

update_panel_constraints = require("../../core/layout/side_panel").update_constraints;

global_gl_canvas = null;

PlotCanvasView = (function(superClass) {
  extend(PlotCanvasView, superClass);

  function PlotCanvasView() {
    this.remove = bind(this.remove, this);
    this.request_render = bind(this.request_render, this);
    return PlotCanvasView.__super__.constructor.apply(this, arguments);
  }

  PlotCanvasView.prototype.className = "bk-plot-wrapper";

  PlotCanvasView.prototype.state = {
    history: [],
    index: -1
  };

  PlotCanvasView.prototype.view_options = function() {
    return _.extend({
      plot_model: this.model,
      plot_view: this
    }, this.options);
  };

  PlotCanvasView.prototype.pause = function() {
    return this.is_paused = true;
  };

  PlotCanvasView.prototype.unpause = function() {
    this.is_paused = false;
    return this.request_render();
  };

  PlotCanvasView.prototype.request_render = function() {
    if (!this.is_paused) {
      this.throttled_render();
    }
  };

  PlotCanvasView.prototype.remove = function() {
    var id, ref1, results, tool_view;
    PlotCanvasView.__super__.remove.call(this);
    ref1 = this.tool_views;
    results = [];
    for (id in ref1) {
      tool_view = ref1[id];
      results.push(tool_view.remove());
    }
    return results;
  };

  PlotCanvasView.prototype.initialize = function(options) {
    var j, l, len, len1, level, name, prefix, ref1, ref2, ref3, spec;
    PlotCanvasView.__super__.initialize.call(this, options);
    this.pause();
    this.visuals = {};
    ref1 = this.model.plot.mixins;
    for (j = 0, len = ref1.length; j < len; j++) {
      spec = ref1[j];
      ref2 = spec.split(":"), name = ref2[0], prefix = ref2[1];
      if (prefix == null) {
        prefix = "";
      }
      this.visuals[prefix + name] = new Renderer.Visuals[name]({
        obj: this.model.plot,
        prefix: prefix
      });
    }
    this._initial_state_info = {
      range: null,
      selection: {},
      dimensions: {
        width: this.mget("canvas").get("width"),
        height: this.mget("canvas").get("height")
      }
    };
    this.frame = this.mget('frame');
    this.x_range = this.frame.get('x_ranges')['default'];
    this.y_range = this.frame.get('y_ranges')['default'];
    this.xmapper = this.frame.get('x_mappers')['default'];
    this.ymapper = this.frame.get('y_mappers')['default'];
    this.canvas = this.mget('canvas');
    this.canvas_view = new this.canvas.default_view({
      'model': this.canvas
    });
    this.$el.append(this.canvas_view.el);
    this.canvas_view.render(true);
    if (this.model.plot.webgl || window.location.search.indexOf('webgl=1') > 0) {
      if (window.location.search.indexOf('webgl=0') === -1) {
        this.init_webgl();
      }
    }
    this.throttled_render = throttle(this.render, 15);
    if (this.model.document._unrendered_plots == null) {
      this.model.document._unrendered_plots = {};
    }
    this.model.document._unrendered_plots[this.id] = true;
    this.ui_event_bus = new UIEvents({
      toolbar: this.mget('toolbar'),
      hit_area: this.canvas_view.$el
    });
    this.renderer_views = {};
    this.tool_views = {};
    this.levels = {};
    ref3 = enums.RenderLevel;
    for (l = 0, len1 = ref3.length; l < len1; l++) {
      level = ref3[l];
      this.levels[level] = {};
    }
    this.build_levels();
    this.bind_bokeh_events();
    this.update_dataranges();
    this.unpause();
    logger.debug("PlotView initialized");
    return this;
  };

  PlotCanvasView.prototype.get_canvas_element = function() {
    return this.canvas_view.ctx.canvas;
  };

  PlotCanvasView.prototype.init_webgl = function() {
    var ctx, glcanvas, opts;
    ctx = this.canvas_view.ctx;
    glcanvas = global_gl_canvas;
    if (glcanvas == null) {
      global_gl_canvas = glcanvas = document.createElement('canvas');
      opts = {
        'premultipliedAlpha': true
      };
      glcanvas.gl = glcanvas.getContext("webgl", opts) || glcanvas.getContext("experimental-webgl", opts);
    }
    if (glcanvas.gl != null) {
      return ctx.glcanvas = glcanvas;
    } else {
      return logger.warn('WebGL is not supported, falling back to 2D canvas.');
    }
  };

  PlotCanvasView.prototype.prepare_webgl = function(ratio, frame_box) {
    var canvas, ctx, flipped_top, gl;
    ctx = this.canvas_view.ctx;
    canvas = this.canvas_view.get_canvas_element();
    if (ctx.glcanvas) {
      ctx.glcanvas.width = canvas.width;
      ctx.glcanvas.height = canvas.height;
      gl = ctx.glcanvas.gl;
      gl.viewport(0, 0, ctx.glcanvas.width, ctx.glcanvas.height);
      gl.clearColor(0, 0, 0, 0);
      gl.clear(gl.COLOR_BUFFER_BIT || gl.DEPTH_BUFFER_BIT);
      gl.enable(gl.SCISSOR_TEST);
      flipped_top = ctx.glcanvas.height - ratio * (frame_box[1] + frame_box[3]);
      gl.scissor(ratio * frame_box[0], flipped_top, ratio * frame_box[2], ratio * frame_box[3]);
      gl.enable(gl.BLEND);
      return gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE_MINUS_DST_ALPHA, gl.ONE);
    }
  };

  PlotCanvasView.prototype.blit_webgl = function(ratio) {
    var ctx;
    ctx = this.canvas_view.ctx;
    if (ctx.glcanvas) {
      logger.debug('drawing with WebGL');
      ctx.restore();
      ctx.drawImage(ctx.glcanvas, 0, 0);
      ctx.save();
      ctx.scale(ratio, ratio);
      return ctx.translate(0.5, 0.5);
    }
  };

  PlotCanvasView.prototype.update_dataranges = function() {
    var bds, bounds, follow_enabled, frame, has_bounds, j, k, l, len, len1, len2, len3, m, n, ref1, ref2, ref3, ref4, ref5, ref6, v, xr, yr;
    frame = this.model.frame;
    bounds = {};
    ref1 = this.renderer_views;
    for (k in ref1) {
      v = ref1[k];
      bds = (ref2 = v.glyph) != null ? typeof ref2.bounds === "function" ? ref2.bounds() : void 0 : void 0;
      if (bds != null) {
        bounds[k] = bds;
      }
    }
    follow_enabled = false;
    has_bounds = false;
    ref3 = _.values(frame.get('x_ranges'));
    for (j = 0, len = ref3.length; j < len; j++) {
      xr = ref3[j];
      if (xr instanceof DataRange1d.Model) {
        xr.update(bounds, 0, this.model.id);
        if (xr.get('follow')) {
          follow_enabled = true;
        }
      }
      if (xr.get('bounds') != null) {
        has_bounds = true;
      }
    }
    ref4 = _.values(frame.get('y_ranges'));
    for (l = 0, len1 = ref4.length; l < len1; l++) {
      yr = ref4[l];
      if (yr instanceof DataRange1d.Model) {
        yr.update(bounds, 1, this.model.id);
        if (yr.get('follow')) {
          follow_enabled = true;
        }
      }
      if (yr.get('bounds') != null) {
        has_bounds = true;
      }
    }
    if (follow_enabled && has_bounds) {
      logger.warn('Follow enabled so bounds are unset.');
      ref5 = _.values(frame.get('x_ranges'));
      for (m = 0, len2 = ref5.length; m < len2; m++) {
        xr = ref5[m];
        xr.set('bounds', null);
      }
      ref6 = _.values(frame.get('y_ranges'));
      for (n = 0, len3 = ref6.length; n < len3; n++) {
        yr = ref6[n];
        yr.set('bounds', null);
      }
    }
    return this.range_update_timestamp = Date.now();
  };

  PlotCanvasView.prototype.map_to_screen = function(x, y, x_name, y_name) {
    if (x_name == null) {
      x_name = 'default';
    }
    if (y_name == null) {
      y_name = 'default';
    }
    return this.frame.map_to_screen(x, y, this.canvas, x_name, y_name);
  };

  PlotCanvasView.prototype.push_state = function(type, info) {
    var prev_info, ref1;
    prev_info = ((ref1 = this.state.history[this.state.index]) != null ? ref1.info : void 0) || {};
    info = _.extend({}, this._initial_state_info, prev_info, info);
    this.state.history.slice(0, this.state.index + 1);
    this.state.history.push({
      type: type,
      info: info
    });
    this.state.index = this.state.history.length - 1;
    return this.trigger("state_changed");
  };

  PlotCanvasView.prototype.clear_state = function() {
    this.state = {
      history: [],
      index: -1
    };
    return this.trigger("state_changed");
  };

  PlotCanvasView.prototype.can_undo = function() {
    return this.state.index >= 0;
  };

  PlotCanvasView.prototype.can_redo = function() {
    return this.state.index < this.state.history.length - 1;
  };

  PlotCanvasView.prototype.undo = function() {
    if (this.can_undo()) {
      this.state.index -= 1;
      this._do_state_change(this.state.index);
      return this.trigger("state_changed");
    }
  };

  PlotCanvasView.prototype.redo = function() {
    if (this.can_redo()) {
      this.state.index += 1;
      this._do_state_change(this.state.index);
      return this.trigger("state_changed");
    }
  };

  PlotCanvasView.prototype._do_state_change = function(index) {
    var info, ref1;
    info = ((ref1 = this.state.history[index]) != null ? ref1.info : void 0) || this._initial_state_info;
    if (info.range != null) {
      this.update_range(info.range);
    }
    if (info.selection != null) {
      this.update_selection(info.selection);
    }
    if (info.dimensions != null) {
      return this.canvas_view.set_dims([info.dimensions.width, info.dimensions.height]);
    }
  };

  PlotCanvasView.prototype.reset_dimensions = function() {
    return this.update_dimensions(this.canvas.initial_width, this.canvas.initial_height);
  };

  PlotCanvasView.prototype.update_dimensions = function(width, height) {
    this.pause();
    this.model.plot.width = width;
    this.model.plot.height = height;
    this.model.document.resize();
    return this.unpause();
  };

  PlotCanvasView.prototype.get_selection = function() {
    var j, len, ref1, renderer, selected, selection;
    selection = [];
    ref1 = this.model.plot.renderers;
    for (j = 0, len = ref1.length; j < len; j++) {
      renderer = ref1[j];
      if (renderer instanceof GlyphRenderer.Model) {
        selected = renderer.get('data_source').get("selected");
        selection[renderer.id] = selected;
      }
    }
    return selection;
  };

  PlotCanvasView.prototype.update_selection = function(selection) {
    var ds, j, len, ref1, ref2, renderer, results;
    ref1 = this.model.plot.renderers;
    results = [];
    for (j = 0, len = ref1.length; j < len; j++) {
      renderer = ref1[j];
      if (!(renderer instanceof GlyphRenderer.Model)) {
        continue;
      }
      ds = renderer.get('data_source');
      if (selection != null) {
        if (ref2 = renderer.id, indexOf.call(selection, ref2) >= 0) {
          results.push(ds.set("selected", selection[renderer.id]));
        } else {
          results.push(void 0);
        }
      } else {
        results.push(ds.get('selection_manager').clear());
      }
    }
    return results;
  };

  PlotCanvasView.prototype.reset_selection = function() {
    return this.update_selection(null);
  };

  PlotCanvasView.prototype._update_ranges_together = function(range_info_iter) {
    var j, l, len, len1, range_info, ref1, ref2, results, rng, weight;
    weight = 1.0;
    for (j = 0, len = range_info_iter.length; j < len; j++) {
      ref1 = range_info_iter[j], rng = ref1[0], range_info = ref1[1];
      weight = Math.min(weight, this._get_weight_to_constrain_interval(rng, range_info));
    }
    if (weight < 1) {
      results = [];
      for (l = 0, len1 = range_info_iter.length; l < len1; l++) {
        ref2 = range_info_iter[l], rng = ref2[0], range_info = ref2[1];
        range_info['start'] = weight * range_info['start'] + (1 - weight) * rng.get('start');
        results.push(range_info['end'] = weight * range_info['end'] + (1 - weight) * rng.get('end'));
      }
      return results;
    }
  };

  PlotCanvasView.prototype._update_ranges_individually = function(range_info_iter, is_panning, is_scrolling) {
    var hit_bound, j, l, len, len1, max, min, new_interval, range_info, ref1, ref2, ref3, results, reversed, rng, weight;
    hit_bound = false;
    for (j = 0, len = range_info_iter.length; j < len; j++) {
      ref1 = range_info_iter[j], rng = ref1[0], range_info = ref1[1];
      reversed = rng.get('start') > rng.get('end');
      if (!is_scrolling) {
        weight = this._get_weight_to_constrain_interval(rng, range_info);
        if (weight < 1) {
          range_info['start'] = weight * range_info['start'] + (1 - weight) * rng.get('start');
          range_info['end'] = weight * range_info['end'] + (1 - weight) * rng.get('end');
        }
      }
      if (rng.get('bounds') != null) {
        min = rng.get('bounds')[0];
        max = rng.get('bounds')[1];
        new_interval = Math.abs(range_info['end'] - range_info['start']);
        if (reversed) {
          if (min != null) {
            if (min >= range_info['end']) {
              hit_bound = true;
              range_info['end'] = min;
              if ((is_panning != null) || (is_scrolling != null)) {
                range_info['start'] = min + new_interval;
              }
            }
          }
          if (max != null) {
            if (max <= range_info['start']) {
              hit_bound = true;
              range_info['start'] = max;
              if ((is_panning != null) || (is_scrolling != null)) {
                range_info['end'] = max - new_interval;
              }
            }
          }
        } else {
          if (min != null) {
            if (min >= range_info['start']) {
              hit_bound = true;
              range_info['start'] = min;
              if ((is_panning != null) || (is_scrolling != null)) {
                range_info['end'] = min + new_interval;
              }
            }
          }
          if (max != null) {
            if (max <= range_info['end']) {
              hit_bound = true;
              range_info['end'] = max;
              if ((is_panning != null) || (is_scrolling != null)) {
                range_info['start'] = max - new_interval;
              }
            }
          }
        }
      }
    }
    if (is_scrolling && hit_bound) {
      return;
    }
    results = [];
    for (l = 0, len1 = range_info_iter.length; l < len1; l++) {
      ref2 = range_info_iter[l], rng = ref2[0], range_info = ref2[1];
      rng.have_updated_interactively = true;
      if (rng.get('start') !== range_info['start'] || rng.get('end') !== range_info['end']) {
        rng.set(range_info);
        results.push((ref3 = rng.get('callback')) != null ? ref3.execute(rng) : void 0);
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  PlotCanvasView.prototype._get_weight_to_constrain_interval = function(rng, range_info) {
    var max, max_interval, max_interval2, min, min_interval, new_interval, old_interval, ref1, weight;
    min_interval = rng.get('min_interval');
    max_interval = rng.get('max_interval');
    weight = 1.0;
    if (rng.get('bounds') != null) {
      ref1 = rng.get('bounds'), min = ref1[0], max = ref1[1];
      if ((min != null) && (max != null)) {
        max_interval2 = Math.abs(max - min);
        max_interval = max_interval != null ? Math.min(max_interval, max_interval2) : max_interval2;
      }
    }
    if ((min_interval != null) || (max_interval != null)) {
      old_interval = Math.abs(rng.get('end') - rng.get('start'));
      new_interval = Math.abs(range_info['end'] - range_info['start']);
      if (min_interval > 0 && new_interval < min_interval) {
        weight = (old_interval - min_interval) / (old_interval - new_interval);
      }
      if (max_interval > 0 && new_interval > max_interval) {
        weight = (max_interval - old_interval) / (new_interval - old_interval);
      }
      weight = Math.max(0.0, Math.min(1.0, weight));
    }
    return weight;
  };

  PlotCanvasView.prototype.update_range = function(range_info, is_panning, is_scrolling) {
    var name, range_info_iter, ref1, ref2, ref3, ref4, ref5, ref6, rng;
    this.pause;
    if (range_info == null) {
      ref1 = this.frame.get('x_ranges');
      for (name in ref1) {
        rng = ref1[name];
        rng.reset();
        if ((ref2 = rng.get('callback')) != null) {
          ref2.execute(rng);
        }
      }
      ref3 = this.frame.get('y_ranges');
      for (name in ref3) {
        rng = ref3[name];
        rng.reset();
        if ((ref4 = rng.get('callback')) != null) {
          ref4.execute(rng);
        }
      }
      this.update_dataranges();
    } else {
      range_info_iter = [];
      ref5 = this.frame.get('x_ranges');
      for (name in ref5) {
        rng = ref5[name];
        range_info_iter.push([rng, range_info.xrs[name]]);
      }
      ref6 = this.frame.get('y_ranges');
      for (name in ref6) {
        rng = ref6[name];
        range_info_iter.push([rng, range_info.yrs[name]]);
      }
      if (is_scrolling) {
        this._update_ranges_together(range_info_iter);
      }
      this._update_ranges_individually(range_info_iter, is_panning, is_scrolling);
    }
    return this.unpause();
  };

  PlotCanvasView.prototype.reset_range = function() {
    return this.update_range(null);
  };

  PlotCanvasView.prototype.build_levels = function() {
    var id_, j, l, len, len1, len2, len3, level, m, n, old_renderers, ref1, renderer_models, renderers_to_remove, synthetic, tool_model, tool_view, tool_views, v, views;
    renderer_models = this.model.plot.renderers;
    ref1 = this.model.plot.toolbar.tools;
    for (j = 0, len = ref1.length; j < len; j++) {
      tool_model = ref1[j];
      synthetic = tool_model.get("synthetic_renderers");
      renderer_models = renderer_models.concat(synthetic);
    }
    old_renderers = _.keys(this.renderer_views);
    views = build_views(this.renderer_views, renderer_models, this.view_options());
    renderers_to_remove = _.difference(old_renderers, _.pluck(renderer_models, 'id'));
    for (l = 0, len1 = renderers_to_remove.length; l < len1; l++) {
      id_ = renderers_to_remove[l];
      delete this.levels.glyph[id_];
    }
    tool_views = build_views(this.tool_views, this.model.plot.toolbar.tools, this.view_options());
    for (m = 0, len2 = views.length; m < len2; m++) {
      v = views[m];
      level = v.mget('level');
      this.levels[level][v.model.id] = v;
      v.bind_bokeh_events();
    }
    for (n = 0, len3 = tool_views.length; n < len3; n++) {
      tool_view = tool_views[n];
      level = tool_view.mget('level');
      this.levels[level][tool_view.model.id] = tool_view;
      tool_view.bind_bokeh_events();
      this.ui_event_bus.register_tool(tool_view);
    }
    return this;
  };

  PlotCanvasView.prototype.bind_bokeh_events = function() {
    var name, ref1, ref2, rng;
    ref1 = this.model.frame.get('x_ranges');
    for (name in ref1) {
      rng = ref1[name];
      this.listenTo(rng, 'change', this.request_render);
    }
    ref2 = this.model.frame.get('y_ranges');
    for (name in ref2) {
      rng = ref2[name];
      this.listenTo(rng, 'change', this.request_render);
    }
    this.listenTo(this.model.plot, 'change:renderers', this.build_levels);
    this.listenTo(this.model.plot.toolbar, 'change:tools', this.build_levels);
    this.listenTo(this.model.plot, 'change', this.request_render);
    this.listenTo(this.model.plot, 'destroy', (function(_this) {
      return function() {
        return _this.remove();
      };
    })(this));
    this.listenTo(this.model.plot.document.solver(), 'layout_update', (function(_this) {
      return function() {
        return _this.request_render();
      };
    })(this));
    this.listenTo(this.model.plot.document.solver(), 'resize', (function(_this) {
      return function() {
        return _this.resize();
      };
    })(this));
    return this.listenTo(this.canvas, 'change:pixel_ratio', (function(_this) {
      return function() {
        return _this.request_render();
      };
    })(this));
  };

  PlotCanvasView.prototype.set_initial_range = function() {
    var good_vals, name, ref1, ref2, rng, xrs, yrs;
    good_vals = true;
    xrs = {};
    ref1 = this.frame.get('x_ranges');
    for (name in ref1) {
      rng = ref1[name];
      if ((rng.get('start') == null) || (rng.get('end') == null) || _.isNaN(rng.get('start') + rng.get('end'))) {
        good_vals = false;
        break;
      }
      xrs[name] = {
        start: rng.get('start'),
        end: rng.get('end')
      };
    }
    if (good_vals) {
      yrs = {};
      ref2 = this.frame.get('y_ranges');
      for (name in ref2) {
        rng = ref2[name];
        if ((rng.get('start') == null) || (rng.get('end') == null) || _.isNaN(rng.get('start') + rng.get('end'))) {
          good_vals = false;
          break;
        }
        yrs[name] = {
          start: rng.get('start'),
          end: rng.get('end')
        };
      }
    }
    if (good_vals) {
      this._initial_state_info.range = this.initial_range_info = {
        xrs: xrs,
        yrs: yrs
      };
      return logger.debug("initial ranges set");
    } else {
      return logger.warn('could not set initial ranges');
    }
  };

  PlotCanvasView.prototype.render = function(force_canvas) {
    var ctx, frame_box, k, lod_timeout, ratio, ref1, v;
    if (force_canvas == null) {
      force_canvas = false;
    }
    logger.trace("PlotCanvas.render(force_canvas=" + force_canvas + ") for " + this.model.id);
    if (this.model.document == null) {
      return;
    }
    if (Date.now() - this.interactive_timestamp < this.model.plot.lod_interval) {
      this.interactive = true;
      lod_timeout = this.model.plot.lod_timeout;
      setTimeout((function(_this) {
        return function() {
          if (_this.interactive && (Date.now() - _this.interactive_timestamp) > lod_timeout) {
            _this.interactive = false;
          }
          return _this.request_render();
        };
      })(this), lod_timeout);
    } else {
      this.interactive = false;
    }
    ref1 = this.renderer_views;
    for (k in ref1) {
      v = ref1[k];
      if ((this.range_update_timestamp == null) || v.set_data_timestamp > this.range_update_timestamp) {
        this.update_dataranges();
        break;
      }
    }
    this.update_constraints();
    this.model.get('frame')._update_mappers();
    ctx = this.canvas_view.ctx;
    ctx.pixel_ratio = ratio = this.canvas_view.pixel_ratio;
    ctx.save();
    ctx.scale(ratio, ratio);
    ctx.translate(0.5, 0.5);
    frame_box = [this.canvas.vx_to_sx(this.frame.get('left')), this.canvas.vy_to_sy(this.frame.get('top')), this.frame.get('width'), this.frame.get('height')];
    this._map_hook(ctx, frame_box);
    this._paint_empty(ctx, frame_box);
    this.prepare_webgl(ratio, frame_box);
    if (this.visuals.outline_line.doit) {
      this.visuals.outline_line.set_value(ctx);
      ctx.strokeRect.apply(ctx, frame_box);
    }
    this._render_levels(ctx, ['image', 'underlay', 'glyph'], frame_box);
    this.blit_webgl(ratio);
    this._render_levels(ctx, ['annotation'], frame_box);
    this._render_levels(ctx, ['overlay', 'tool']);
    if (this.initial_range_info == null) {
      this.set_initial_range();
    }
    ctx.restore();
    if (this.model.document._unrendered_plots != null) {
      delete this.model.document._unrendered_plots[this.id];
      if (_.isEmpty(this.model.document._unrendered_plots)) {
        this.model.document._unrendered_plots = null;
        return _.delay($.proxy(this.model.document.resize, this.model.document), 1);
      }
    }
  };

  PlotCanvasView.prototype.resize = function() {
    var error, height, silent_error, width;
    width = this.model._width._value;
    height = this.model._height._value;
    this.canvas_view.set_dims([width, height], true);
    this.canvas_view.prepare_canvas();
    try {
      this.update_constraints();
    } catch (error) {
      silent_error = error;
    }
    return this.$el.css({
      position: 'absolute',
      left: this.model._dom_left._value,
      top: this.model._dom_top._value,
      width: this.model._width._value,
      height: this.model._height._value
    });
  };

  PlotCanvasView.prototype.update_constraints = function() {
    var model_id, ref1, s, view;
    s = this.model.document.solver();
    s.suggest_value(this.frame._width, this.canvas.get('width') - 1);
    s.suggest_value(this.frame._height, this.canvas.get('height') - 1);
    ref1 = this.renderer_views;
    for (model_id in ref1) {
      view = ref1[model_id];
      if (view.model.panel != null) {
        update_panel_constraints(view);
      }
    }
    return s.update_variables(false);
  };

  PlotCanvasView.prototype._render_levels = function(ctx, levels, clip_region) {
    var i, indices, j, l, len, len1, len2, level, m, ref1, renderer, renderer_view, renderer_views, sortKey;
    ctx.save();
    if (clip_region != null) {
      ctx.beginPath();
      ctx.rect.apply(ctx, clip_region);
      ctx.clip();
      ctx.beginPath();
    }
    indices = {};
    ref1 = this.model.plot.renderers;
    for (i = j = 0, len = ref1.length; j < len; i = ++j) {
      renderer = ref1[i];
      indices[renderer.id] = i;
    }
    sortKey = function(renderer_view) {
      return indices[renderer_view.model.id];
    };
    for (l = 0, len1 = levels.length; l < len1; l++) {
      level = levels[l];
      renderer_views = _.sortBy(_.values(this.levels[level]), sortKey);
      for (m = 0, len2 = renderer_views.length; m < len2; m++) {
        renderer_view = renderer_views[m];
        renderer_view.render();
      }
    }
    return ctx.restore();
  };

  PlotCanvasView.prototype._map_hook = function(ctx, frame_box) {};

  PlotCanvasView.prototype._paint_empty = function(ctx, frame_box) {
    this.visuals.border_fill.set_value(ctx);
    ctx.fillRect(0, 0, this.canvas_view.mget('width'), this.canvas_view.mget('height'));
    ctx.clearRect.apply(ctx, frame_box);
    this.visuals.background_fill.set_value(ctx);
    return ctx.fillRect.apply(ctx, frame_box);
  };

  return PlotCanvasView;

})(Renderer.View);

PlotCanvas = (function(superClass) {
  extend(PlotCanvas, superClass);

  function PlotCanvas() {
    return PlotCanvas.__super__.constructor.apply(this, arguments);
  }

  PlotCanvas.prototype.type = 'PlotCanvas';

  PlotCanvas.prototype.default_view = PlotCanvasView;

  PlotCanvas.prototype.initialize = function(attrs, options) {
    var ref1;
    PlotCanvas.__super__.initialize.call(this, attrs, options);
    this.canvas = new Canvas.Model({
      map: (ref1 = this.use_map) != null ? ref1 : false,
      initial_width: this.plot.plot_width,
      initial_height: this.plot.plot_height,
      use_hidpi: this.plot.hidpi
    });
    this.frame = new CartesianFrame.Model({
      x_range: this.plot.x_range,
      extra_x_ranges: this.plot.extra_x_ranges,
      x_mapper_type: this.plot.x_mapper_type,
      y_range: this.plot.y_range,
      extra_y_ranges: this.plot.extra_y_ranges,
      y_mapper_type: this.plot.y_mapper_type
    });
    this.above_panel = new LayoutCanvas.Model();
    this.below_panel = new LayoutCanvas.Model();
    this.left_panel = new LayoutCanvas.Model();
    this.right_panel = new LayoutCanvas.Model();
    return logger.debug("PlotCanvas initialized");
  };

  PlotCanvas.prototype.add_renderer_to_canvas_side = function(renderer, side) {
    if (side !== 'center') {
      return renderer.add_panel(side);
    }
  };

  PlotCanvas.prototype._doc_attached = function() {
    this.canvas.attach_document(this.document);
    this.frame.attach_document(this.document);
    this.above_panel.attach_document(this.document);
    this.below_panel.attach_document(this.document);
    this.left_panel.attach_document(this.document);
    this.right_panel.attach_document(this.document);
    return logger.debug("PlotCanvas attached to document");
  };

  PlotCanvas.override({
    sizing_mode: 'stretch_both'
  });

  PlotCanvas.internal({
    plot: [p.Instance],
    toolbar: [p.Instance],
    canvas: [p.Instance],
    frame: [p.Instance]
  });

  PlotCanvas.prototype.get_layoutable_children = function() {
    var children, j, l, layout_renderers, len, len1, r, ref1, side;
    children = [this.above_panel, this.below_panel, this.left_panel, this.right_panel, this.canvas, this.frame];
    ref1 = ['above', 'below', 'left', 'right'];
    for (j = 0, len = ref1.length; j < len; j++) {
      side = ref1[j];
      layout_renderers = this.plot.get(side);
      for (l = 0, len1 = layout_renderers.length; l < len1; l++) {
        r = layout_renderers[l];
        if (r.panel != null) {
          children.push(r.panel);
        }
      }
    }
    return children;
  };

  PlotCanvas.prototype.get_edit_variables = function() {
    var child, edit_variables, j, len, ref1;
    edit_variables = [];
    ref1 = this.get_layoutable_children();
    for (j = 0, len = ref1.length; j < len; j++) {
      child = ref1[j];
      edit_variables = edit_variables.concat(child.get_edit_variables());
    }
    return edit_variables;
  };

  PlotCanvas.prototype.get_constraints = function() {
    var child, constraints, j, len, ref1;
    constraints = PlotCanvas.__super__.get_constraints.call(this);
    constraints = constraints.concat(this._get_constant_constraints());
    constraints = constraints.concat(this._get_side_constraints());
    ref1 = this.get_layoutable_children();
    for (j = 0, len = ref1.length; j < len; j++) {
      child = ref1[j];
      constraints = constraints.concat(child.get_constraints());
    }
    return constraints;
  };

  PlotCanvas.prototype._get_constant_constraints = function() {
    var constraints, min_border_bottom, min_border_left, min_border_right, min_border_top;
    min_border_top = this.plot.min_border_top;
    min_border_bottom = this.plot.min_border_bottom;
    min_border_left = this.plot.min_border_left;
    min_border_right = this.plot.min_border_right;
    constraints = [];
    constraints.push(GE(this.above_panel._height, -min_border_top));
    constraints.push(GE(this.below_panel._height, -min_border_bottom));
    constraints.push(GE(this.left_panel._width, -min_border_left));
    constraints.push(GE(this.right_panel._width, -min_border_right));
    constraints.push(EQ(this.above_panel._top, [-1, this.canvas._top]));
    constraints.push(EQ(this.above_panel._bottom, [-1, this.frame._top]));
    constraints.push(EQ(this.below_panel._bottom, [-1, this.canvas._bottom]));
    constraints.push(EQ(this.below_panel._top, [-1, this.frame._bottom]));
    constraints.push(EQ(this.left_panel._left, [-1, this.canvas._left]));
    constraints.push(EQ(this.left_panel._right, [-1, this.frame._left]));
    constraints.push(EQ(this.right_panel._right, [-1, this.canvas._right]));
    constraints.push(EQ(this.right_panel._left, [-1, this.frame._right]));
    constraints.push(EQ(this.above_panel._height, [-1, this._top]));
    constraints.push(EQ(this.above_panel._height, [-1, this.canvas._top], this.frame._top));
    constraints.push(EQ(this.below_panel._height, [-1, this._height], this._bottom));
    constraints.push(EQ(this.below_panel._height, [-1, this.frame._bottom]));
    constraints.push(EQ(this.left_panel._width, [-1, this._left]));
    constraints.push(EQ(this.left_panel._width, [-1, this.frame._left]));
    constraints.push(EQ(this.right_panel._width, [-1, this._width], this._right));
    constraints.push(EQ(this.right_panel._width, [-1, this.canvas._right], this.frame._right));
    return constraints;
  };

  PlotCanvas.prototype._get_side_constraints = function() {
    var constraints, j, l, last, layout_renderers, len, len1, r, ref1, side;
    constraints = [];
    ref1 = ['above', 'below', 'left', 'right'];
    for (j = 0, len = ref1.length; j < len; j++) {
      side = ref1[j];
      layout_renderers = this.plot.get(side);
      last = this.frame;
      for (l = 0, len1 = layout_renderers.length; l < len1; l++) {
        r = layout_renderers[l];
        if (side === "above") {
          constraints.push(EQ(last.panel._top, [-1, r.panel._bottom]));
        }
        if (side === "below") {
          constraints.push(EQ(last.panel._bottom, [-1, r.panel._top]));
        }
        if (side === "left") {
          constraints.push(EQ(last.panel._left, [-1, r.panel._right]));
        }
        if (side === "right") {
          constraints.push(EQ(last.panel._right, [-1, r.panel._left]));
        }
        last = r;
      }
      if (layout_renderers.length !== 0) {
        if (side === "above") {
          constraints.push(EQ(last.panel._top, [-1, this.above_panel._top]));
        }
        if (side === "below") {
          constraints.push(EQ(last.panel._bottom, [-1, this.below_panel._bottom]));
        }
        if (side === "left") {
          constraints.push(EQ(last.panel._left, [-1, this.left_panel._left]));
        }
        if (side === "right") {
          constraints.push(EQ(last.panel._right, [-1, this.right_panel._right]));
        }
      }
    }
    return constraints;
  };

  PlotCanvas.prototype.plot_canvas = function() {
    return this;
  };

  return PlotCanvas;

})(LayoutDOM.Model);

module.exports = {
  Model: PlotCanvas,
  View: PlotCanvasView
};

},{"../../common/build_views":"common/build_views","../../common/ui_events":"common/ui_events","../../core/enums":"core/enums","../../core/layout/layout_canvas":"core/layout/layout_canvas","../../core/layout/side_panel":"core/layout/side_panel","../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/util/throttle":"core/util/throttle","../canvas/canvas":"models/canvas/canvas","../canvas/cartesian_frame":"models/canvas/cartesian_frame","../layouts/layout_dom":"models/layouts/layout_dom","../ranges/data_range1d":"models/ranges/data_range1d","../renderers/glyph_renderer":"models/renderers/glyph_renderer","../renderers/renderer":"models/renderers/renderer","jquery":"jquery","underscore":"underscore"}],"models/ranges/data_range":[function(require,module,exports){
var DataRange, Range, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Range = require("./range");

p = require("../../core/properties");

DataRange = (function(superClass) {
  extend(DataRange, superClass);

  function DataRange() {
    return DataRange.__super__.constructor.apply(this, arguments);
  }

  DataRange.prototype.type = 'DataRange';

  DataRange.define({
    names: [p.Array, []],
    renderers: [p.Array, []]
  });

  return DataRange;

})(Range.Model);

module.exports = {
  Model: DataRange
};

},{"../../core/properties":"core/properties","./range":"models/ranges/range","underscore":"underscore"}],"models/ranges/data_range1d":[function(require,module,exports){
var DataRange, DataRange1d, _, bbox, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

DataRange = require("./data_range");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

bbox = require("../../core/util/bbox");

DataRange1d = (function(superClass) {
  extend(DataRange1d, superClass);

  function DataRange1d() {
    return DataRange1d.__super__.constructor.apply(this, arguments);
  }

  DataRange1d.prototype.type = 'DataRange1d';

  DataRange1d.define({
    start: [p.Number],
    end: [p.Number],
    range_padding: [p.Number, 0.1],
    flipped: [p.Bool, false],
    follow: [p.String],
    follow_interval: [p.Number],
    default_span: [p.Number, 2],
    bounds: [p.Any],
    min_interval: [p.Any],
    max_interval: [p.Any]
  });

  DataRange1d.prototype.initialize = function(attrs, options) {
    DataRange1d.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('min', function() {
      return Math.min(this.get('start'), this.get('end'));
    }, true);
    this.add_dependencies('min', this, ['start', 'end']);
    this.define_computed_property('max', function() {
      return Math.max(this.get('start'), this.get('end'));
    }, true);
    this.add_dependencies('max', this, ['start', 'end']);
    this.plot_bounds = {};
    this.have_updated_interactively = false;
    this._initial_start = this.get('start');
    this._initial_end = this.get('end');
    this._initial_range_padding = this.get('range_padding');
    this._initial_follow = this.get('follow');
    this._initial_follow_interval = this.get('follow_interval');
    return this._initial_default_span = this.get('default_span');
  };

  DataRange1d.prototype.computed_renderers = function() {
    var all_renderers, i, j, len, len1, names, plot, r, ref, renderers, rs;
    names = this.get('names');
    renderers = this.get('renderers');
    if (renderers.length === 0) {
      ref = this.get('plots');
      for (i = 0, len = ref.length; i < len; i++) {
        plot = ref[i];
        all_renderers = plot.get('renderers');
        rs = (function() {
          var j, len1, results;
          results = [];
          for (j = 0, len1 = all_renderers.length; j < len1; j++) {
            r = all_renderers[j];
            if (r.type === "GlyphRenderer") {
              results.push(r);
            }
          }
          return results;
        })();
        renderers = renderers.concat(rs);
      }
    }
    if (names.length > 0) {
      renderers = (function() {
        var j, len1, results;
        results = [];
        for (j = 0, len1 = renderers.length; j < len1; j++) {
          r = renderers[j];
          if (names.indexOf(r.get('name')) >= 0) {
            results.push(r);
          }
        }
        return results;
      })();
    }
    logger.debug("computed " + renderers.length + " renderers for DataRange1d " + this.id);
    for (j = 0, len1 = renderers.length; j < len1; j++) {
      r = renderers[j];
      logger.trace(" - " + r.type + " " + r.id);
    }
    return renderers;
  };

  DataRange1d.prototype._compute_plot_bounds = function(renderers, bounds) {
    var i, len, r, result;
    result = bbox.empty();
    for (i = 0, len = renderers.length; i < len; i++) {
      r = renderers[i];
      if (bounds[r.id] != null) {
        result = bbox.union(result, bounds[r.id]);
      }
    }
    return result;
  };

  DataRange1d.prototype._compute_min_max = function(plot_bounds, dimension) {
    var k, max, min, overall, ref, ref1, v;
    overall = bbox.empty();
    for (k in plot_bounds) {
      v = plot_bounds[k];
      overall = bbox.union(overall, v);
    }
    if (dimension === 0) {
      ref = [overall.minX, overall.maxX], min = ref[0], max = ref[1];
    } else {
      ref1 = [overall.minY, overall.maxY], min = ref1[0], max = ref1[1];
    }
    return [min, max];
  };

  DataRange1d.prototype._compute_range = function(min, max) {
    var center, end, follow_interval, follow_sign, range_padding, ref, ref1, ref2, span, start;
    range_padding = this.get('range_padding');
    if ((range_padding != null) && range_padding > 0) {
      if (max === min) {
        span = this.get('default_span');
      } else {
        span = (max - min) * (1 + range_padding);
      }
      center = (max + min) / 2.0;
      ref = [center - span / 2.0, center + span / 2.0], start = ref[0], end = ref[1];
    } else {
      ref1 = [min, max], start = ref1[0], end = ref1[1];
    }
    follow_sign = +1;
    if (this.get('flipped')) {
      ref2 = [end, start], start = ref2[0], end = ref2[1];
      follow_sign = -1;
    }
    follow_interval = this.get('follow_interval');
    if ((follow_interval != null) && Math.abs(start - end) > follow_interval) {
      if (this.get('follow') === 'start') {
        end = start + follow_sign * follow_interval;
      } else if (this.get('follow') === 'end') {
        start = end - follow_sign * follow_interval;
      }
    }
    return [start, end];
  };

  DataRange1d.prototype.update = function(bounds, dimension, bounds_id) {
    var _end, _start, end, max, min, new_range, ref, ref1, ref2, renderers, start;
    if (this.have_updated_interactively) {
      return;
    }
    renderers = this.computed_renderers();
    this.plot_bounds[bounds_id] = this._compute_plot_bounds(renderers, bounds);
    ref = this._compute_min_max(this.plot_bounds, dimension), min = ref[0], max = ref[1];
    ref1 = this._compute_range(min, max), start = ref1[0], end = ref1[1];
    if (this._initial_start != null) {
      start = this._initial_start;
    }
    if (this._initial_end != null) {
      end = this._initial_end;
    }
    ref2 = [this.get('start'), this.get('end')], _start = ref2[0], _end = ref2[1];
    if (start !== _start || end !== _end) {
      new_range = {};
      if (start !== _start) {
        new_range.start = start;
      }
      if (end !== _end) {
        new_range.end = end;
      }
      this.set(new_range);
    }
    if (this.get('bounds') === 'auto') {
      return this.set('bounds', [start, end]);
    }
  };

  DataRange1d.prototype.reset = function() {
    this.have_updated_interactively = false;
    return this.set({
      range_padding: this._initial_range_padding,
      follow: this._initial_follow,
      follow_interval: this._initial_follow_interval,
      default_span: this._initial_default_span
    });
  };

  return DataRange1d;

})(DataRange.Model);

module.exports = {
  Model: DataRange1d
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/util/bbox":"core/util/bbox","./data_range":"models/ranges/data_range","underscore":"underscore"}],"models/ranges/factor_range":[function(require,module,exports){
var FactorRange, Range, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Range = require("./range");

p = require("../../core/properties");

FactorRange = (function(superClass) {
  extend(FactorRange, superClass);

  function FactorRange() {
    return FactorRange.__super__.constructor.apply(this, arguments);
  }

  FactorRange.prototype.type = 'FactorRange';

  FactorRange.define({
    offset: [p.Number, 0],
    factors: [p.Array, []],
    bounds: [p.Any],
    min_interval: [p.Any],
    max_interval: [p.Any]
  });

  FactorRange.internal({
    _bounds_as_factors: [p.Any],
    start: [p.Number],
    end: [p.Number]
  });

  FactorRange.prototype.initialize = function(attrs, options) {
    FactorRange.__super__.initialize.call(this, attrs, options);
    if ((this.get('bounds') != null) && this.get('bounds') !== 'auto') {
      this.set('_bounds_as_factors', this.get('bounds'));
    } else {
      this.set('_bounds_as_factors', this.get('factors'));
    }
    this._init();
    this.define_computed_property('min', function() {
      return this.get('start');
    }, false);
    this.add_dependencies('min', this, ['factors', 'offset']);
    this.define_computed_property('max', function() {
      return this.get('end');
    }, false);
    this.add_dependencies('max', this, ['factors', 'offset']);
    this.listenTo(this, 'change:factors', this._update_factors);
    return this.listenTo(this, 'change:offset', this._init);
  };

  FactorRange.prototype.reset = function() {
    return this._init();
  };

  FactorRange.prototype._update_factors = function() {
    this.set('_bounds_as_factors', this.get('factors'));
    return this._init();
  };

  FactorRange.prototype._init = function() {
    var end, factors, start;
    factors = this.get('factors');
    if ((this.get('bounds') != null) && this.get('bounds') !== 'auto') {
      factors = this.get('_bounds_as_factors');
      this.set('factors', factors);
    }
    start = 0.5 + this.get('offset');
    end = factors.length + start;
    this.set('start', start);
    this.set('end', end);
    if (this.get('bounds') != null) {
      return this.set('bounds', [start, end]);
    }
  };

  return FactorRange;

})(Range.Model);

module.exports = {
  Model: FactorRange
};

},{"../../core/properties":"core/properties","./range":"models/ranges/range","underscore":"underscore"}],"models/ranges/range":[function(require,module,exports){
var Model, Range, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../../model");

p = require("../../core/properties");

Range = (function(superClass) {
  extend(Range, superClass);

  function Range() {
    return Range.__super__.constructor.apply(this, arguments);
  }

  Range.prototype.type = 'Range';

  Range.define({
    callback: [p.Instance]
  });

  Range.internal({
    plots: [p.Array, []]
  });

  Range.prototype.reset = function() {};

  return Range;

})(Model);

module.exports = {
  Model: Range
};

},{"../../core/properties":"core/properties","../../model":"model","underscore":"underscore"}],"models/ranges/range1d":[function(require,module,exports){
var Range, Range1d, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Range = require("./range");

p = require("../../core/properties");

Range1d = (function(superClass) {
  extend(Range1d, superClass);

  Range1d.prototype.type = 'Range1d';

  Range1d.define({
    start: [p.Number, 0],
    end: [p.Number, 1],
    bounds: [p.Any],
    min_interval: [p.Any],
    max_interval: [p.Any]
  });

  Range1d.prototype._set_auto_bounds = function() {
    var max, min;
    if (this.get('bounds') === 'auto') {
      min = Math.min(this._initial_start, this._initial_end);
      max = Math.max(this._initial_start, this._initial_end);
      return this.set('bounds', [min, max]);
    }
  };

  function Range1d() {
    var end, start;
    if (this instanceof Range1d) {
      return Range1d.__super__.constructor.apply(this, arguments);
    } else {
      start = arguments[0], end = arguments[1];
      return new Range1d({
        start: start,
        end: end
      });
    }
  }

  Range1d.prototype.initialize = function(attrs, options) {
    Range1d.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('min', function() {
      return Math.min(this.get('start'), this.get('end'));
    }, true);
    this.add_dependencies('min', this, ['start', 'end']);
    this.define_computed_property('max', function() {
      return Math.max(this.get('start'), this.get('end'));
    }, true);
    this.add_dependencies('max', this, ['start', 'end']);
    this._initial_start = this.get('start');
    this._initial_end = this.get('end');
    return this._set_auto_bounds();
  };

  Range1d.prototype.reset = function() {
    this.set({
      start: this._initial_start,
      end: this._initial_end
    });
    return this._set_auto_bounds();
  };

  return Range1d;

})(Range.Model);

module.exports = {
  Model: Range1d
};

},{"../../core/properties":"core/properties","./range":"models/ranges/range","underscore":"underscore"}],"models/renderers/glyph_renderer":[function(require,module,exports){
var GlyphRenderer, GlyphRendererView, RemoteDataSource, Renderer, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Renderer = require("./renderer");

RemoteDataSource = require("../sources/remote_data_source");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

GlyphRendererView = (function(superClass) {
  extend(GlyphRendererView, superClass);

  function GlyphRendererView() {
    return GlyphRendererView.__super__.constructor.apply(this, arguments);
  }

  GlyphRendererView.prototype.initialize = function(options) {
    var base_glyph, decimated_glyph, glyph_attrs, has_fill, has_line, hover_glyph, mk_glyph, nonselection_glyph, selection_glyph;
    GlyphRendererView.__super__.initialize.call(this, options);
    base_glyph = this.mget("glyph");
    has_fill = _.contains(base_glyph.mixins, "fill");
    has_line = _.contains(base_glyph.mixins, "line");
    glyph_attrs = _.omit(_.clone(base_glyph.attributes), 'id');
    mk_glyph = function(defaults) {
      var attrs;
      attrs = _.clone(glyph_attrs);
      if (has_fill) {
        _.extend(attrs, defaults.fill);
      }
      if (has_line) {
        _.extend(attrs, defaults.line);
      }
      return new base_glyph.constructor(attrs);
    };
    this.glyph = this.build_glyph_view(base_glyph);
    selection_glyph = this.mget("selection_glyph");
    if (selection_glyph == null) {
      selection_glyph = mk_glyph(this.model.selection_defaults);
    }
    this.selection_glyph = this.build_glyph_view(selection_glyph);
    nonselection_glyph = this.mget("nonselection_glyph");
    if (nonselection_glyph == null) {
      nonselection_glyph = mk_glyph(this.model.nonselection_defaults);
    }
    this.nonselection_glyph = this.build_glyph_view(nonselection_glyph);
    hover_glyph = this.mget("hover_glyph");
    if (hover_glyph != null) {
      this.hover_glyph = this.build_glyph_view(hover_glyph);
    }
    decimated_glyph = mk_glyph(this.model.decimated_defaults);
    this.decimated_glyph = this.build_glyph_view(decimated_glyph);
    this.xmapper = this.plot_view.frame.get('x_mappers')[this.mget("x_range_name")];
    this.ymapper = this.plot_view.frame.get('y_mappers')[this.mget("y_range_name")];
    this.set_data(false);
    if (this.mget('data_source') instanceof RemoteDataSource.Model) {
      return this.mget('data_source').setup(this.plot_view, this.glyph);
    }
  };

  GlyphRendererView.prototype.build_glyph_view = function(model) {
    return new model.default_view({
      model: model,
      renderer: this,
      plot_view: this.plot_view,
      plot_model: this.plot_model
    });
  };

  GlyphRendererView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change', this.request_render);
    this.listenTo(this.mget('data_source'), 'change', this.set_data);
    this.listenTo(this.mget('data_source'), 'patch', this.set_data);
    this.listenTo(this.mget('data_source'), 'stream', this.set_data);
    this.listenTo(this.mget('data_source'), 'select', this.request_render);
    if (this.hover_glyph != null) {
      this.listenTo(this.mget('data_source'), 'inspect', this.request_render);
    }
    return this.listenTo(this.mget('glyph'), 'propchange', function() {
      this.glyph.set_visuals(this.mget('data_source'));
      return this.request_render();
    });
  };

  GlyphRendererView.prototype.have_selection_glyphs = function() {
    return (this.selection_glyph != null) && (this.nonselection_glyph != null);
  };

  GlyphRendererView.prototype.set_data = function(request_render, arg) {
    var dt, i, j, k, length, lod_factor, ref, results, source, t0;
    if (request_render == null) {
      request_render = true;
    }
    t0 = Date.now();
    source = this.mget('data_source');
    this.glyph.model.set({
      x_range_name: this.mget('x_range_name'),
      y_range_name: this.mget('y_range_name')
    }, {
      silent: true
    });
    this.glyph.set_data(source, arg);
    this.glyph.set_visuals(source);
    this.decimated_glyph.set_visuals(source);
    if (this.have_selection_glyphs()) {
      this.selection_glyph.set_visuals(source);
      this.nonselection_glyph.set_visuals(source);
    }
    if (this.hover_glyph != null) {
      this.hover_glyph.set_visuals(source);
    }
    length = source.get_length();
    if (length == null) {
      length = 1;
    }
    this.all_indices = (function() {
      results = [];
      for (var j = 0; 0 <= length ? j < length : j > length; 0 <= length ? j++ : j--){ results.push(j); }
      return results;
    }).apply(this);
    lod_factor = this.plot_model.plot.lod_factor;
    this.decimated = [];
    for (i = k = 0, ref = Math.floor(this.all_indices.length / lod_factor); 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      this.decimated.push(this.all_indices[i * lod_factor]);
    }
    dt = Date.now() - t0;
    logger.debug(this.glyph.model.type + " GlyphRenderer (" + this.model.id + "): set_data finished in " + dt + "ms");
    this.set_data_timestamp = Date.now();
    if (request_render) {
      return this.request_render();
    }
  };

  GlyphRendererView.prototype.render = function() {
    var ctx, dtmap, dtmask, dtrender, dtselect, dttot, glsupport, glyph, i, indices, inspected, j, k, len, len1, lod_threshold, nonselected, nonselection_glyph, selected, selected_mask, selection_glyph, t0, tmap, tmask, trender, tselect;
    if (this.model.visible === false) {
      return;
    }
    t0 = Date.now();
    glsupport = this.glyph.glglyph;
    tmap = Date.now();
    this.glyph.map_data();
    dtmap = Date.now() - t0;
    tmask = Date.now();
    if (glsupport) {
      indices = this.all_indices;
    } else {
      indices = this.glyph._mask_data(this.all_indices);
    }
    dtmask = Date.now() - tmask;
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    selected = this.mget('data_source').get('selected');
    if (!selected || selected.length === 0) {
      selected = [];
    } else {
      if (selected['0d'].glyph) {
        selected = indices;
      } else if (selected['1d'].indices.length > 0) {
        selected = selected['1d'].indices;
      } else if (selected['2d'].indices.length > 0) {
        selected = selected['2d'].indices;
      } else {
        selected = [];
      }
    }
    inspected = this.mget('data_source').get('inspected');
    if (!inspected || inspected.length === 0) {
      inspected = [];
    } else {
      if (inspected['0d'].glyph) {
        inspected = indices;
      } else if (inspected['1d'].indices.length > 0) {
        inspected = inspected['1d'].indices;
      } else if (inspected['2d'].indices.length > 0) {
        inspected = inspected['2d'].indices;
      } else {
        inspected = [];
      }
    }
    lod_threshold = this.plot_model.plot.lod_threshold;
    if (this.plot_view.interactive && !glsupport && (lod_threshold != null) && this.all_indices.length > lod_threshold) {
      indices = this.decimated;
      glyph = this.decimated_glyph;
      nonselection_glyph = this.decimated_glyph;
      selection_glyph = this.selection_glyph;
    } else {
      glyph = this.glyph;
      nonselection_glyph = this.nonselection_glyph;
      selection_glyph = this.selection_glyph;
    }
    if ((this.hover_glyph != null) && inspected.length) {
      indices = _.without.bind(null, indices).apply(null, inspected);
    }
    if (!(selected.length && this.have_selection_glyphs())) {
      trender = Date.now();
      glyph.render(ctx, indices, this.glyph);
      if (this.hover_glyph && inspected.length) {
        this.hover_glyph.render(ctx, inspected, this.glyph);
      }
      dtrender = Date.now() - trender;
    } else {
      tselect = Date.now();
      selected_mask = {};
      for (j = 0, len = selected.length; j < len; j++) {
        i = selected[j];
        selected_mask[i] = true;
      }
      selected = new Array();
      nonselected = new Array();
      for (k = 0, len1 = indices.length; k < len1; k++) {
        i = indices[k];
        if (selected_mask[i] != null) {
          selected.push(i);
        } else {
          nonselected.push(i);
        }
      }
      dtselect = Date.now() - tselect;
      trender = Date.now();
      nonselection_glyph.render(ctx, nonselected, this.glyph);
      selection_glyph.render(ctx, selected, this.glyph);
      if (this.hover_glyph != null) {
        this.hover_glyph.render(ctx, inspected, this.glyph);
      }
      dtrender = Date.now() - trender;
    }
    this.last_dtrender = dtrender;
    dttot = Date.now() - t0;
    logger.debug(this.glyph.model.type + " GlyphRenderer (" + this.model.id + "): render finished in " + dttot + "ms");
    logger.trace(" - map_data finished in       : " + dtmap + "ms");
    if (dtmask != null) {
      logger.trace(" - mask_data finished in      : " + dtmask + "ms");
    }
    if (dtselect != null) {
      logger.trace(" - selection mask finished in : " + dtselect + "ms");
    }
    logger.trace(" - glyph renders finished in  : " + dtrender + "ms");
    return ctx.restore();
  };

  GlyphRendererView.prototype.map_to_screen = function(x, y) {
    return this.plot_view.map_to_screen(x, y, this.mget("x_range_name"), this.mget("y_range_name"));
  };

  GlyphRendererView.prototype.draw_legend = function(ctx, x0, x1, y0, y1) {
    return this.glyph.draw_legend(ctx, x0, x1, y0, y1);
  };

  GlyphRendererView.prototype.hit_test = function(geometry) {
    return this.glyph.hit_test(geometry);
  };

  return GlyphRendererView;

})(Renderer.View);

GlyphRenderer = (function(superClass) {
  extend(GlyphRenderer, superClass);

  function GlyphRenderer() {
    return GlyphRenderer.__super__.constructor.apply(this, arguments);
  }

  GlyphRenderer.prototype.default_view = GlyphRendererView;

  GlyphRenderer.prototype.type = 'GlyphRenderer';

  GlyphRenderer.define({
    x_range_name: [p.String, 'default'],
    y_range_name: [p.String, 'default'],
    data_source: [p.Instance],
    glyph: [p.Instance],
    hover_glyph: [p.Instance],
    nonselection_glyph: [p.Instance],
    selection_glyph: [p.Instance]
  });

  GlyphRenderer.override({
    level: 'glyph'
  });

  GlyphRenderer.prototype.selection_defaults = {
    fill: {},
    line: {}
  };

  GlyphRenderer.prototype.decimated_defaults = {
    fill: {
      fill_alpha: 0.3,
      fill_color: "grey"
    },
    line: {
      line_alpha: 0.3,
      line_color: "grey"
    }
  };

  GlyphRenderer.prototype.nonselection_defaults = {
    fill: {
      fill_alpha: 0.2,
      line_alpha: 0.2
    },
    line: {}
  };

  return GlyphRenderer;

})(Renderer.Model);

module.exports = {
  Model: GlyphRenderer,
  View: GlyphRendererView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../sources/remote_data_source":"models/sources/remote_data_source","./renderer":"models/renderers/renderer","underscore":"underscore"}],"models/renderers/guide_renderer":[function(require,module,exports){
var GuideRenderer, Renderer, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Renderer = require("./renderer");

p = require("../../core/properties");

GuideRenderer = (function(superClass) {
  extend(GuideRenderer, superClass);

  function GuideRenderer() {
    return GuideRenderer.__super__.constructor.apply(this, arguments);
  }

  GuideRenderer.prototype.type = 'GuideRenderer';

  GuideRenderer.define({
    plot: [p.Instance]
  });

  GuideRenderer.override({
    level: 'overlay'
  });

  return GuideRenderer;

})(Renderer.Model);

module.exports = {
  Model: GuideRenderer
};

},{"../../core/properties":"core/properties","./renderer":"models/renderers/renderer","underscore":"underscore"}],"models/renderers/renderer":[function(require,module,exports){
var Backbone, BokehView, Model, Renderer, RendererView, VISUALS, _, _ContextProperties, _Fill, _Line, _Text, array_max, color2rgba, logger, mixins, p, proj4, toProjection,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

proj4 = require("proj4");

toProjection = proj4.defs('GOOGLE');

Backbone = require("backbone");

BokehView = require("../../core/bokeh_view");

color2rgba = require("../../core/util/color").color2rgba;

logger = require("../../core/logging").logger;

p = require("../../core/properties");

mixins = require("../../core/property_mixins");

array_max = require("../../core/util/math").array_max;

Model = require("../../model");

_ContextProperties = (function(superClass) {
  extend(_ContextProperties, superClass);

  function _ContextProperties(attrs, options) {
    var attr, do_spec, j, len, obj, prefix, ref;
    if (attrs.prefix == null) {
      attrs.prefix = "";
    }
    _ContextProperties.__super__.constructor.call(this, attrs, options);
    this.cache = {};
    obj = this.get('obj');
    prefix = this.get('prefix');
    do_spec = obj.properties[prefix + this.do_attr].spec;
    this.doit = !_.isNull(do_spec.value);
    ref = this.attrs;
    for (j = 0, len = ref.length; j < len; j++) {
      attr = ref[j];
      this[attr] = obj.properties[prefix + attr];
    }
  }

  _ContextProperties.prototype.warm_cache = function(source) {
    var attr, j, len, obj, prefix, prop, ref, results;
    ref = this.attrs;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      attr = ref[j];
      obj = this.get('obj');
      prefix = this.get('prefix');
      prop = obj.properties[prefix + attr];
      if (!_.isUndefined(prop.spec.value)) {
        results.push(this.cache[attr] = prop.spec.value);
      } else {
        results.push(this.cache[attr + "_array"] = prop.array(source));
      }
    }
    return results;
  };

  _ContextProperties.prototype.cache_select = function(attr, i) {
    var obj, prefix, prop;
    obj = this.get('obj');
    prefix = this.get('prefix');
    prop = obj.properties[prefix + attr];
    if (!_.isUndefined(prop.spec.value)) {
      return this.cache[attr] = prop.spec.value;
    } else {
      return this.cache[attr] = this.cache[attr + "_array"][i];
    }
  };

  return _ContextProperties;

})(Backbone.Model);

_Line = (function(superClass) {
  extend(_Line, superClass);

  function _Line() {
    return _Line.__super__.constructor.apply(this, arguments);
  }

  _Line.prototype.attrs = _.keys(mixins.line());

  _Line.prototype.do_attr = "line_color";

  _Line.prototype.set_value = function(ctx) {
    ctx.strokeStyle = this.line_color.value();
    ctx.globalAlpha = this.line_alpha.value();
    ctx.lineWidth = this.line_width.value();
    ctx.lineJoin = this.line_join.value();
    ctx.lineCap = this.line_cap.value();
    ctx.setLineDash(this.line_dash.value());
    return ctx.setLineDashOffset(this.line_dash_offset.value());
  };

  _Line.prototype.set_vectorize = function(ctx, i) {
    this.cache_select("line_color", i);
    if (ctx.strokeStyle !== this.cache.line_color) {
      ctx.strokeStyle = this.cache.line_color;
    }
    this.cache_select("line_alpha", i);
    if (ctx.globalAlpha !== this.cache.line_alpha) {
      ctx.globalAlpha = this.cache.line_alpha;
    }
    this.cache_select("line_width", i);
    if (ctx.lineWidth !== this.cache.line_width) {
      ctx.lineWidth = this.cache.line_width;
    }
    this.cache_select("line_join", i);
    if (ctx.lineJoin !== this.cache.line_join) {
      ctx.lineJoin = this.cache.line_join;
    }
    this.cache_select("line_cap", i);
    if (ctx.lineCap !== this.cache.line_cap) {
      ctx.lineCap = this.cache.line_cap;
    }
    this.cache_select("line_dash", i);
    if (ctx.getLineDash() !== this.cache.line_dash) {
      ctx.setLineDash(this.cache.line_dash);
    }
    this.cache_select("line_dash_offset", i);
    if (ctx.getLineDashOffset() !== this.cache.line_dash_offset) {
      return ctx.setLineDashOffset(this.cache.line_dash_offset);
    }
  };

  _Line.prototype.color_value = function() {
    var color;
    color = color2rgba(this.line_color.value(), this.line_alpha.value());
    return "rgba(" + (color[0] * 255) + "," + (color[1] * 255) + "," + (color[2] * 255) + "," + color[3] + ")";
  };

  return _Line;

})(_ContextProperties);

_Fill = (function(superClass) {
  extend(_Fill, superClass);

  function _Fill() {
    return _Fill.__super__.constructor.apply(this, arguments);
  }

  _Fill.prototype.attrs = _.keys(mixins.fill());

  _Fill.prototype.do_attr = "fill_color";

  _Fill.prototype.set_value = function(ctx) {
    ctx.fillStyle = this.fill_color.value();
    return ctx.globalAlpha = this.fill_alpha.value();
  };

  _Fill.prototype.set_vectorize = function(ctx, i) {
    this.cache_select("fill_color", i);
    if (ctx.fillStyle !== this.cache.fill_color) {
      ctx.fillStyle = this.cache.fill_color;
    }
    this.cache_select("fill_alpha", i);
    if (ctx.globalAlpha !== this.cache.fill_alpha) {
      return ctx.globalAlpha = this.cache.fill_alpha;
    }
  };

  _Fill.prototype.color_value = function() {
    var color;
    color = color2rgba(this.fill_color.value(), this.fill_alpha.value());
    return "rgba(" + (color[0] * 255) + "," + (color[1] * 255) + "," + (color[2] * 255) + "," + color[3] + ")";
  };

  return _Fill;

})(_ContextProperties);

_Text = (function(superClass) {
  extend(_Text, superClass);

  function _Text() {
    return _Text.__super__.constructor.apply(this, arguments);
  }

  _Text.prototype.attrs = _.keys(mixins.text());

  _Text.prototype.do_attr = "text_color";

  _Text.prototype.cache_select = function(name, i) {
    var val;
    if (name === "font") {
      val = _Text.__super__.cache_select.call(this, "text_font_style", i) + " " + _Text.__super__.cache_select.call(this, "text_font_size", i) + " " + _Text.__super__.cache_select.call(this, "text_font", i);
      return this.cache.font = val;
    } else {
      return _Text.__super__.cache_select.call(this, name, i);
    }
  };

  _Text.prototype.font_value = function() {
    var font, font_size, font_style;
    font = this.text_font.value();
    font_size = this.text_font_size.value();
    font_style = this.text_font_style.value();
    return font_style + " " + font_size + " " + font;
  };

  _Text.prototype.color_value = function() {
    var color;
    color = color2rgba(this.text_color.value(), this.text_alpha.value());
    return "rgba(" + (color[0] * 255) + "," + (color[1] * 255) + "," + (color[2] * 255) + "," + color[3] + ")";
  };

  _Text.prototype.set_value = function(ctx) {
    ctx.font = this.font_value();
    ctx.fillStyle = this.text_color.value();
    ctx.globalAlpha = this.text_alpha.value();
    ctx.textAlign = this.text_align.value();
    return ctx.textBaseline = this.text_baseline.value();
  };

  _Text.prototype.set_vectorize = function(ctx, i) {
    this.cache_select("font", i);
    if (ctx.font !== this.cache.font) {
      ctx.font = this.cache.font;
    }
    this.cache_select("text_color", i);
    if (ctx.fillStyle !== this.cache.text_color) {
      ctx.fillStyle = this.cache.text_color;
    }
    this.cache_select("text_alpha", i);
    if (ctx.globalAlpha !== this.cache.text_alpha) {
      ctx.globalAlpha = this.cache.text_alpha;
    }
    this.cache_select("text_align", i);
    if (ctx.textAlign !== this.cache.text_align) {
      ctx.textAlign = this.cache.text_align;
    }
    this.cache_select("text_baseline", i);
    if (ctx.textBaseline !== this.cache.text_baseline) {
      return ctx.textBaseline = this.cache.text_baseline;
    }
  };

  return _Text;

})(_ContextProperties);

VISUALS = {
  line: _Line,
  fill: _Fill,
  text: _Text
};

RendererView = (function(superClass) {
  extend(RendererView, superClass);

  function RendererView() {
    return RendererView.__super__.constructor.apply(this, arguments);
  }

  RendererView.prototype.initialize = function(options) {
    var j, len, name, prefix, ref, ref1, results, spec;
    RendererView.__super__.initialize.call(this, options);
    this.plot_model = options.plot_model;
    this.plot_view = options.plot_view;
    this.nohit_warned = {};
    this.visuals = {};
    ref = this.model.mixins;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      spec = ref[j];
      ref1 = spec.split(":"), name = ref1[0], prefix = ref1[1];
      if (prefix == null) {
        prefix = "";
      }
      results.push(this.visuals[prefix + name] = new VISUALS[name]({
        obj: this.model,
        prefix: prefix
      }));
    }
    return results;
  };

  RendererView.prototype.bind_bokeh_events = function() {};

  RendererView.prototype.request_render = function() {
    return this.plot_view.request_render();
  };

  RendererView.prototype.map_data = function() {
    var i, j, k, len, ref, ref1, ref2, ref3, ref4, ref5, ref6, sx, sxname, sy, syname, xname, yname;
    ref = this.model._coords;
    for (j = 0, len = ref.length; j < len; j++) {
      ref1 = ref[j], xname = ref1[0], yname = ref1[1];
      sxname = "s" + xname;
      syname = "s" + yname;
      xname = "_" + xname;
      yname = "_" + yname;
      if (_.isArray((ref2 = this[xname]) != null ? ref2[0] : void 0)) {
        ref3 = [[], []], this[sxname] = ref3[0], this[syname] = ref3[1];
        for (i = k = 0, ref4 = this[xname].length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
          ref5 = this.map_to_screen(this[xname][i], this[yname][i]), sx = ref5[0], sy = ref5[1];
          this[sxname].push(sx);
          this[syname].push(sy);
        }
      } else {
        ref6 = this.map_to_screen(this[xname], this[yname]), this[sxname] = ref6[0], this[syname] = ref6[1];
      }
    }
    return this._map_data();
  };

  RendererView.prototype.project_xy = function(x, y) {
    var i, j, merc_x, merc_x_s, merc_y, merc_y_s, ref, ref1;
    merc_x_s = [];
    merc_y_s = [];
    for (i = j = 0, ref = x.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ref1 = proj4(toProjection, [x[i], y[i]]), merc_x = ref1[0], merc_y = ref1[1];
      merc_x_s[i] = merc_x;
      merc_y_s[i] = merc_y;
    }
    return [merc_x_s, merc_y_s];
  };

  RendererView.prototype.project_xsys = function(xs, ys) {
    var i, j, merc_x_s, merc_xs_s, merc_y_s, merc_ys_s, ref, ref1;
    merc_xs_s = [];
    merc_ys_s = [];
    for (i = j = 0, ref = xs.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ref1 = this.project_xy(xs[i], ys[i]), merc_x_s = ref1[0], merc_y_s = ref1[1];
      merc_xs_s[i] = merc_x_s;
      merc_ys_s[i] = merc_y_s;
    }
    return [merc_xs_s, merc_ys_s];
  };

  RendererView.prototype.set_data = function(source) {
    var name, prop, ref, ref1, ref2;
    ref = this.model.properties;
    for (name in ref) {
      prop = ref[name];
      if (!prop.dataspec) {
        continue;
      }
      if ((prop.optional || false) && prop.spec.value === null && (!(name in this.model._set_after_defaults))) {
        continue;
      }
      this["_" + name] = prop.array(source);
      if (prop instanceof p.Distance) {
        this["max_" + name] = array_max(this["_" + name]);
      }
    }
    if (this.plot_model.use_map) {
      if (this._x != null) {
        ref1 = this.project_xy(this._x, this._y), this._x = ref1[0], this._y = ref1[1];
      }
      if (this._xs != null) {
        ref2 = this.project_xsys(this._xs, this._ys), this._xs = ref2[0], this._ys = ref2[1];
      }
    }
    if (this.glglyph != null) {
      this.glglyph.set_data_changed(this._x.length);
    }
    this._set_data();
    return this.index = this._index_data();
  };

  RendererView.prototype.set_visuals = function(source) {
    var name, prop, ref;
    ref = this.visuals;
    for (name in ref) {
      prop = ref[name];
      prop.warm_cache(source);
    }
    if (this.glglyph != null) {
      return this.glglyph.set_visuals_changed();
    }
  };

  RendererView.prototype._set_data = function() {
    return null;
  };

  RendererView.prototype._map_data = function() {
    return null;
  };

  RendererView.prototype._index_data = function() {
    return null;
  };

  RendererView.prototype._mask_data = function(inds) {
    return inds;
  };

  RendererView.prototype._bounds = function(bds) {
    return bds;
  };

  RendererView.prototype.hit_test = function(geometry) {
    var func, result;
    result = null;
    func = "_hit_" + geometry.type;
    if (this[func] != null) {
      result = this[func](geometry);
    } else if (this.nohit_warned[geometry.type] == null) {
      logger.debug("'" + geometry.type + "' selection not available for " + this.model.type);
      this.nohit_warned[geometry.type] = true;
    }
    return result;
  };

  RendererView.prototype.map_to_screen = function(x, y) {
    return this.plot_view.map_to_screen(x, y, this.mget("x_range_name"), this.mget("y_range_name"));
  };

  return RendererView;

})(BokehView);

Renderer = (function(superClass) {
  extend(Renderer, superClass);

  function Renderer() {
    return Renderer.__super__.constructor.apply(this, arguments);
  }

  Renderer.prototype.type = "Renderer";

  Renderer.define({
    level: [p.RenderLevel, null],
    visible: [p.Bool, true]
  });

  return Renderer;

})(Model);

module.exports = {
  Model: Renderer,
  View: RendererView,
  Visuals: VISUALS
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/property_mixins":"core/property_mixins","../../core/util/color":"core/util/color","../../core/util/math":"core/util/math","../../model":"model","backbone":"backbone","proj4":"proj4","underscore":"underscore"}],"models/sources/ajax_data_source":[function(require,module,exports){
var $, AjaxDataSource, RemoteDataSource, _, logger, p,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

$ = require("jquery");

_ = require("underscore");

RemoteDataSource = require("./remote_data_source");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

AjaxDataSource = (function(superClass) {
  extend(AjaxDataSource, superClass);

  function AjaxDataSource() {
    this.get_data = bind(this.get_data, this);
    this.setup = bind(this.setup, this);
    this.destroy = bind(this.destroy, this);
    return AjaxDataSource.__super__.constructor.apply(this, arguments);
  }

  AjaxDataSource.prototype.type = 'AjaxDataSource';

  AjaxDataSource.define({
    mode: [p.String, 'replace'],
    content_type: [p.String, 'application/json'],
    http_headers: [p.Any, {}],
    max_size: [p.Number],
    method: [p.String, 'POST'],
    if_modified: [p.Bool, false]
  });

  AjaxDataSource.prototype.destroy = function() {
    if (this.interval != null) {
      return clearInterval(this.interval);
    }
  };

  AjaxDataSource.prototype.setup = function(plot_view, glyph) {
    this.pv = plot_view;
    this.get_data(this.get('mode'));
    if (this.get('polling_interval')) {
      return this.interval = setInterval(this.get_data, this.get('polling_interval'), this.get('mode'), this.get('max_size'), this.get('if_modified'));
    }
  };

  AjaxDataSource.prototype.get_data = function(mode, max_size, if_modified) {
    if (max_size == null) {
      max_size = 0;
    }
    if (if_modified == null) {
      if_modified = false;
    }
    $.ajax({
      dataType: 'json',
      ifModified: if_modified,
      url: this.get('data_url'),
      xhrField: {
        withCredentials: true
      },
      method: this.get('method'),
      contentType: this.get('content_type'),
      headers: this.get('http_headers')
    }).done((function(_this) {
      return function(data) {
        var column, i, len, original_data, ref;
        if (mode === 'replace') {
          _this.set('data', data);
        } else if (mode === 'append') {
          original_data = _this.get('data');
          ref = _this.columns();
          for (i = 0, len = ref.length; i < len; i++) {
            column = ref[i];
            data[column] = original_data[column].concat(data[column]).slice(-max_size);
          }
          _this.set('data', data);
        } else {
          logger.error("unsupported mode: " + mode);
        }
        logger.trace(data);
        return null;
      };
    })(this)).error(function() {
      return logger.error(arguments);
    });
    return null;
  };

  return AjaxDataSource;

})(RemoteDataSource.Model);

module.exports = {
  Model: AjaxDataSource
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./remote_data_source":"models/sources/remote_data_source","jquery":"jquery","underscore":"underscore"}],"models/sources/column_data_source":[function(require,module,exports){
var ColumnDataSource, DataSource, SelectionManager, _, hittest, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

DataSource = require('./data_source');

hittest = require("../../common/hittest");

SelectionManager = require("../../common/selection_manager");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

ColumnDataSource = (function(superClass) {
  extend(ColumnDataSource, superClass);

  function ColumnDataSource() {
    return ColumnDataSource.__super__.constructor.apply(this, arguments);
  }

  ColumnDataSource.prototype.type = 'ColumnDataSource';

  ColumnDataSource.define({
    data: [p.Any, {}],
    column_names: [p.Array, []]
  });

  ColumnDataSource.internal({
    selection_manager: [
      p.Instance, function(self) {
        return new SelectionManager({
          source: self
        });
      }
    ],
    inspected: [p.Any]
  });

  ColumnDataSource.prototype.get_column = function(colname) {
    var ref;
    return (ref = this.get('data')[colname]) != null ? ref : null;
  };

  ColumnDataSource.prototype.get_length = function() {
    var data, key, lengths, val;
    data = this.get('data');
    if (_.keys(data).length === 0) {
      return null;
    } else {
      lengths = _.uniq((function() {
        var results;
        results = [];
        for (key in data) {
          val = data[key];
          results.push(val.length);
        }
        return results;
      })());
      if (lengths.length > 1) {
        logger.debug("data source has columns of inconsistent lengths");
      }
      return lengths[0];
    }
  };

  ColumnDataSource.prototype.columns = function() {
    return _.keys(this.get('data'));
  };

  ColumnDataSource.prototype.stream = function(new_data, rollover) {
    var data, k, v;
    data = this.get('data');
    for (k in new_data) {
      v = new_data[k];
      data[k] = data[k].concat(new_data[k]);
      if (data[k].length > rollover) {
        data[k] = data[k].slice(-rollover);
      }
    }
    this.set('data', data, {
      silent: true
    });
    return this.trigger('stream');
  };

  ColumnDataSource.prototype.patch = function(patches) {
    var data, i, ind, j, k, patch, ref, ref1, value;
    data = this.get('data');
    for (k in patches) {
      patch = patches[k];
      for (i = j = 0, ref = patch.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        ref1 = patch[i], ind = ref1[0], value = ref1[1];
        data[k][ind] = value;
      }
    }
    this.set('data', data, {
      silent: true
    });
    return this.trigger('patch');
  };

  return ColumnDataSource;

})(DataSource.Model);

module.exports = {
  Model: ColumnDataSource
};

},{"../../common/hittest":"common/hittest","../../common/selection_manager":"common/selection_manager","../../core/logging":"core/logging","../../core/properties":"core/properties","./data_source":"models/sources/data_source","underscore":"underscore"}],"models/sources/data_source":[function(require,module,exports){
var DataSource, Model, _, hittest, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../../model");

hittest = require("../../common/hittest");

p = require("../../core/properties");

DataSource = (function(superClass) {
  extend(DataSource, superClass);

  function DataSource() {
    return DataSource.__super__.constructor.apply(this, arguments);
  }

  DataSource.prototype.type = 'DataSource';

  DataSource.define({
    selected: [p.Any, hittest.create_hit_test_result()],
    callback: [p.Any]
  });

  DataSource.prototype.initialize = function(options) {
    DataSource.__super__.initialize.call(this, options);
    return this.listenTo(this, 'change:selected', (function(_this) {
      return function() {
        var callback;
        callback = _this.get('callback');
        if (callback != null) {
          if (_.isFunction(callback)) {
            return callback(_this);
          } else {
            return callback.execute(_this);
          }
        }
      };
    })(this));
  };

  return DataSource;

})(Model);

module.exports = {
  Model: DataSource
};

},{"../../common/hittest":"common/hittest","../../core/properties":"core/properties","../../model":"model","underscore":"underscore"}],"models/sources/geojson_data_source":[function(require,module,exports){
var ColumnDataSource, GeoJSONDataSource, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ColumnDataSource = require("./column_data_source");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

GeoJSONDataSource = (function(superClass) {
  extend(GeoJSONDataSource, superClass);

  function GeoJSONDataSource() {
    return GeoJSONDataSource.__super__.constructor.apply(this, arguments);
  }

  GeoJSONDataSource.prototype.type = 'GeoJSONDataSource';

  GeoJSONDataSource.define({
    geojson: [p.Any]
  });

  GeoJSONDataSource.prototype.initialize = function(options) {
    GeoJSONDataSource.__super__.initialize.call(this, options);
    this.geojson_to_column_data();
    this.define_computed_property('data', this.geojson_to_column_data, true);
    return this.add_dependencies('data', this, ['geojson']);
  };

  GeoJSONDataSource.prototype._get_new_list_array = function(length) {
    var array, list_array;
    array = new Array(length);
    list_array = _.map(array, function(x) {
      return [];
    });
    return list_array;
  };

  GeoJSONDataSource.prototype._get_new_nan_array = function(length) {
    var array, nan_array;
    array = new Array(length);
    nan_array = _.map(array, function(x) {
      return NaN;
    });
    return nan_array;
  };

  GeoJSONDataSource.prototype._flatten_function = function(accumulator, currentItem) {
    return accumulator.concat([[NaN, NaN, NaN]]).concat(currentItem);
  };

  GeoJSONDataSource.prototype._add_properties = function(item, data, i, item_count) {
    var property, results;
    results = [];
    for (property in item.properties) {
      if (!data.hasOwnProperty(property)) {
        data[property] = this._get_new_nan_array(item_count);
      }
      results.push(data[property][i] = item.properties[property]);
    }
    return results;
  };

  GeoJSONDataSource.prototype._add_geometry = function(geometry, data, i) {
    var coord_list, coords, exterior_ring, exterior_rings, flattened_coord_list, j, k, l, len, len1, len2, len3, len4, m, n, o, polygon, ref, ref1, ref2, ref3, ref4, ref5, results, results1, results2, results3;
    switch (geometry.type) {
      case "Point":
        coords = geometry.coordinates;
        data.x[i] = coords[0];
        data.y[i] = coords[1];
        return data.z[i] = (ref = coords[2]) != null ? ref : NaN;
      case "LineString":
        coord_list = geometry.coordinates;
        results = [];
        for (j = k = 0, len = coord_list.length; k < len; j = ++k) {
          coords = coord_list[j];
          data.xs[i][j] = coords[0];
          data.ys[i][j] = coords[1];
          results.push(data.zs[i][j] = (ref1 = coords[2]) != null ? ref1 : NaN);
        }
        return results;
        break;
      case "Polygon":
        if (geometry.coordinates.length > 1) {
          logger.warn('Bokeh does not support Polygons with holes in, only exterior ring used.');
        }
        exterior_ring = geometry.coordinates[0];
        results1 = [];
        for (j = l = 0, len1 = exterior_ring.length; l < len1; j = ++l) {
          coords = exterior_ring[j];
          data.xs[i][j] = coords[0];
          data.ys[i][j] = coords[1];
          results1.push(data.zs[i][j] = (ref2 = coords[2]) != null ? ref2 : NaN);
        }
        return results1;
        break;
      case "MultiPoint":
        return logger.warn('MultiPoint not supported in Bokeh');
      case "MultiLineString":
        flattened_coord_list = _.reduce(geometry.coordinates, this._flatten_function);
        results2 = [];
        for (j = m = 0, len2 = flattened_coord_list.length; m < len2; j = ++m) {
          coords = flattened_coord_list[j];
          data.xs[i][j] = coords[0];
          data.ys[i][j] = coords[1];
          results2.push(data.zs[i][j] = (ref3 = coords[2]) != null ? ref3 : NaN);
        }
        return results2;
        break;
      case "MultiPolygon":
        exterior_rings = [];
        ref4 = geometry.coordinates;
        for (n = 0, len3 = ref4.length; n < len3; n++) {
          polygon = ref4[n];
          if (polygon.length > 1) {
            logger.warn('Bokeh does not support Polygons with holes in, only exterior ring used.');
          }
          exterior_rings.push(polygon[0]);
        }
        flattened_coord_list = _.reduce(exterior_rings, this._flatten_function);
        results3 = [];
        for (j = o = 0, len4 = flattened_coord_list.length; o < len4; j = ++o) {
          coords = flattened_coord_list[j];
          data.xs[i][j] = coords[0];
          data.ys[i][j] = coords[1];
          results3.push(data.zs[i][j] = (ref5 = coords[2]) != null ? ref5 : NaN);
        }
        return results3;
        break;
      default:
        throw new Error('Invalid type ' + geometry.type);
    }
  };

  GeoJSONDataSource.prototype._get_items_length = function(items) {
    var count, g, geometry, i, item, j, k, l, len, len1, ref;
    count = 0;
    for (i = k = 0, len = items.length; k < len; i = ++k) {
      item = items[i];
      geometry = item.type === 'Feature' ? item.geometry : item;
      if (geometry.type === 'GeometryCollection') {
        ref = geometry.geometries;
        for (j = l = 0, len1 = ref.length; l < len1; j = ++l) {
          g = ref[j];
          count += 1;
        }
      } else {
        count += 1;
      }
    }
    return count;
  };

  GeoJSONDataSource.prototype.geojson_to_column_data = function() {
    var arr_index, data, g, geojson, geometry, i, item, item_count, items, j, k, l, len, len1, ref, ref1;
    geojson = JSON.parse(this.get('geojson'));
    if ((ref = geojson.type) !== 'GeometryCollection' && ref !== 'FeatureCollection') {
      throw new Error('Bokeh only supports type GeometryCollection and FeatureCollection at top level');
    }
    if (geojson.type === 'GeometryCollection') {
      if (geojson.geometries == null) {
        throw new Error('No geometries found in GeometryCollection');
      }
      if (geojson.geometries.length === 0) {
        throw new Error('geojson.geometries must have one or more items');
      }
      items = geojson.geometries;
    }
    if (geojson.type === 'FeatureCollection') {
      if (geojson.features == null) {
        throw new Error('No features found in FeaturesCollection');
      }
      if (geojson.features.length === 0) {
        throw new Error('geojson.features must have one or more items');
      }
      items = geojson.features;
    }
    item_count = this._get_items_length(items);
    data = {
      'x': this._get_new_nan_array(item_count),
      'y': this._get_new_nan_array(item_count),
      'z': this._get_new_nan_array(item_count),
      'xs': this._get_new_list_array(item_count),
      'ys': this._get_new_list_array(item_count),
      'zs': this._get_new_list_array(item_count)
    };
    arr_index = 0;
    for (i = k = 0, len = items.length; k < len; i = ++k) {
      item = items[i];
      geometry = item.type === 'Feature' ? item.geometry : item;
      if (geometry.type === 'GeometryCollection') {
        ref1 = geometry.geometries;
        for (j = l = 0, len1 = ref1.length; l < len1; j = ++l) {
          g = ref1[j];
          this._add_geometry(g, data, arr_index);
          if (item.type === 'Feature') {
            this._add_properties(item, data, arr_index, item_count);
          }
          arr_index += 1;
        }
      } else {
        this._add_geometry(geometry, data, arr_index);
        if (item.type === 'Feature') {
          this._add_properties(item, data, arr_index, item_count);
        }
        arr_index += 1;
      }
    }
    return data;
  };

  return GeoJSONDataSource;

})(ColumnDataSource.Model);

module.exports = {
  Model: GeoJSONDataSource
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./column_data_source":"models/sources/column_data_source","underscore":"underscore"}],"models/sources/remote_data_source":[function(require,module,exports){
var ColumnDataSource, RemoteDataSource, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ColumnDataSource = require("./column_data_source");

p = require("../../core/properties");

RemoteDataSource = (function(superClass) {
  extend(RemoteDataSource, superClass);

  function RemoteDataSource() {
    return RemoteDataSource.__super__.constructor.apply(this, arguments);
  }

  RemoteDataSource.prototype.type = 'RemoteDataSource';

  RemoteDataSource.define({
    data_url: [p.String],
    polling_interval: [p.Number]
  });

  return RemoteDataSource;

})(ColumnDataSource.Model);

module.exports = {
  Model: RemoteDataSource
};

},{"../../core/properties":"core/properties","./column_data_source":"models/sources/column_data_source","underscore":"underscore"}],"models/tickers/adaptive_ticker":[function(require,module,exports){
var AdaptiveTicker, ContinuousTicker, _, argmin, clamp, log, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

argmin = require("./util").argmin;

ContinuousTicker = require("./continuous_ticker");

p = require("../../core/properties");

clamp = function(x, min_val, max_val) {
  return Math.max(min_val, Math.min(max_val, x));
};

log = function(x, base) {
  if (base == null) {
    base = Math.E;
  }
  return Math.log(x) / Math.log(base);
};

AdaptiveTicker = (function(superClass) {
  extend(AdaptiveTicker, superClass);

  function AdaptiveTicker() {
    return AdaptiveTicker.__super__.constructor.apply(this, arguments);
  }

  AdaptiveTicker.prototype.type = 'AdaptiveTicker';

  AdaptiveTicker.define({
    base: [p.Number, 10.0],
    mantissas: [p.Array, [1, 2, 5]],
    min_interval: [p.Number, 0.0],
    max_interval: [p.Number]
  });

  AdaptiveTicker.prototype.initialize = function(attrs, options) {
    var prefix_mantissa, suffix_mantissa;
    AdaptiveTicker.__super__.initialize.call(this, attrs, options);
    prefix_mantissa = _.last(this.get('mantissas')) / this.get('base');
    suffix_mantissa = _.first(this.get('mantissas')) * this.get('base');
    this.extended_mantissas = _.flatten([prefix_mantissa, this.get('mantissas'), suffix_mantissa]);
    return this.base_factor = this.get_min_interval() === 0.0 ? 1.0 : this.get_min_interval();
  };

  AdaptiveTicker.prototype.get_interval = function(data_low, data_high, desired_n_ticks) {
    var best_mantissa, candidate_mantissas, data_range, errors, ideal_interval, ideal_magnitude, ideal_mantissa, interval, interval_exponent;
    data_range = data_high - data_low;
    ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
    interval_exponent = Math.floor(log(ideal_interval / this.base_factor, this.get('base')));
    ideal_magnitude = Math.pow(this.get('base'), interval_exponent) * this.base_factor;
    ideal_mantissa = ideal_interval / ideal_magnitude;
    candidate_mantissas = this.extended_mantissas;
    errors = candidate_mantissas.map(function(mantissa) {
      return Math.abs(desired_n_ticks - (data_range / (mantissa * ideal_magnitude)));
    });
    best_mantissa = candidate_mantissas[argmin(errors)];
    interval = best_mantissa * ideal_magnitude;
    return clamp(interval, this.get_min_interval(), this.get_max_interval());
  };

  return AdaptiveTicker;

})(ContinuousTicker.Model);

module.exports = {
  Model: AdaptiveTicker
};

},{"../../core/properties":"core/properties","./continuous_ticker":"models/tickers/continuous_ticker","./util":"models/tickers/util","underscore":"underscore"}],"models/tickers/basic_ticker":[function(require,module,exports){
var AdaptiveTicker, BasicTicker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

AdaptiveTicker = require("./adaptive_ticker");

BasicTicker = (function(superClass) {
  extend(BasicTicker, superClass);

  function BasicTicker() {
    return BasicTicker.__super__.constructor.apply(this, arguments);
  }

  BasicTicker.prototype.type = 'BasicTicker';

  return BasicTicker;

})(AdaptiveTicker.Model);

module.exports = {
  Model: BasicTicker
};

},{"./adaptive_ticker":"models/tickers/adaptive_ticker","underscore":"underscore"}],"models/tickers/categorical_ticker":[function(require,module,exports){
var CategoricalTicker, Ticker,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

Ticker = require("./ticker");

CategoricalTicker = (function(superClass) {
  extend(CategoricalTicker, superClass);

  function CategoricalTicker() {
    return CategoricalTicker.__super__.constructor.apply(this, arguments);
  }

  CategoricalTicker.prototype.type = 'CategoricalTicker';

  CategoricalTicker.prototype.get_ticks = function(start, end, range, arg) {
    var desired_n_ticks, factors, i, ii, j, majors, ref;
    desired_n_ticks = arg.desired_n_ticks;
    majors = [];
    factors = range.get("factors");
    for (i = j = 0, ref = factors.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ii = i + range.get('offset');
      if ((ii + 1) > start && (ii + 1) < end) {
        majors.push(factors[i]);
      }
    }
    return {
      "major": majors,
      "minor": []
    };
  };

  return CategoricalTicker;

})(Ticker.Model);

module.exports = {
  Model: CategoricalTicker
};

},{"./ticker":"models/tickers/ticker"}],"models/tickers/composite_ticker":[function(require,module,exports){
var CompositeTicker, ContinuousTicker, _, argmin, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ContinuousTicker = require("./continuous_ticker");

argmin = require("./util").argmin;

p = require("../../core/properties");

CompositeTicker = (function(superClass) {
  extend(CompositeTicker, superClass);

  function CompositeTicker() {
    return CompositeTicker.__super__.constructor.apply(this, arguments);
  }

  CompositeTicker.prototype.type = 'CompositeTicker';

  CompositeTicker.define({
    tickers: [p.Array, []]
  });

  CompositeTicker.prototype.initialize = function(attrs, options) {
    var tickers;
    CompositeTicker.__super__.initialize.call(this, attrs, options);
    tickers = this.get('tickers');
    this.define_computed_property('min_intervals', function() {
      return _.invoke(tickers, 'get_min_interval');
    }, true);
    this.add_dependencies('min_intervals', this, ['tickers']);
    this.define_computed_property('max_intervals', function() {
      return _.invoke(tickers, 'get_max_interval');
    }, true);
    this.add_dependencies('max_intervals', this, ['tickers']);
    this.define_computed_property('min_interval', function() {
      return _.first(this.get('min_intervals'));
    }, true);
    this.add_dependencies('min_interval', this, ['min_intervals']);
    this.define_computed_property('max_interval', function() {
      return _.first(this.get('max_intervals'));
    }, true);
    return this.add_dependencies('max_interval', this, ['max_interval']);
  };

  CompositeTicker.prototype.get_best_ticker = function(data_low, data_high, desired_n_ticks) {
    var best_index, best_ticker, best_ticker_ndx, data_range, errors, ideal_interval, intervals, ticker_ndxs;
    data_range = data_high - data_low;
    ideal_interval = this.get_ideal_interval(data_low, data_high, desired_n_ticks);
    ticker_ndxs = [_.sortedIndex(this.get('min_intervals'), ideal_interval) - 1, _.sortedIndex(this.get('max_intervals'), ideal_interval)];
    intervals = [this.get('min_intervals')[ticker_ndxs[0]], this.get('max_intervals')[ticker_ndxs[1]]];
    errors = intervals.map(function(interval) {
      return Math.abs(desired_n_ticks - (data_range / interval));
    });
    best_index = argmin(errors);
    if (best_index === Infinity) {
      return this.get('tickers')[0];
    }
    best_ticker_ndx = ticker_ndxs[best_index];
    best_ticker = this.get('tickers')[best_ticker_ndx];
    return best_ticker;
  };

  CompositeTicker.prototype.get_interval = function(data_low, data_high, desired_n_ticks) {
    var best_ticker;
    best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
    return best_ticker.get_interval(data_low, data_high, desired_n_ticks);
  };

  CompositeTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var best_ticker, ticks;
    best_ticker = this.get_best_ticker(data_low, data_high, desired_n_ticks);
    ticks = best_ticker.get_ticks_no_defaults(data_low, data_high, desired_n_ticks);
    return ticks;
  };

  return CompositeTicker;

})(ContinuousTicker.Model);

module.exports = {
  Model: CompositeTicker
};

},{"../../core/properties":"core/properties","./continuous_ticker":"models/tickers/continuous_ticker","./util":"models/tickers/util","underscore":"underscore"}],"models/tickers/continuous_ticker":[function(require,module,exports){
var ContinuousTicker, Ticker, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Ticker = require("./ticker");

p = require("../../core/properties");

ContinuousTicker = (function(superClass) {
  extend(ContinuousTicker, superClass);

  function ContinuousTicker() {
    return ContinuousTicker.__super__.constructor.apply(this, arguments);
  }

  ContinuousTicker.prototype.type = 'ContinuousTicker';

  ContinuousTicker.define({
    num_minor_ticks: [p.Number, 5],
    desired_num_ticks: [p.Number, 6]
  });

  ContinuousTicker.prototype.get_interval = void 0;

  ContinuousTicker.prototype.get_min_interval = function() {
    return this.get('min_interval');
  };

  ContinuousTicker.prototype.get_max_interval = function() {
    var ref;
    return (ref = this.get('max_interval')) != null ? ref : Infinity;
  };

  ContinuousTicker.prototype.get_ideal_interval = function(data_low, data_high, desired_n_ticks) {
    var data_range;
    data_range = data_high - data_low;
    return data_range / desired_n_ticks;
  };

  return ContinuousTicker;

})(Ticker.Model);

module.exports = {
  Model: ContinuousTicker
};

},{"../../core/properties":"core/properties","./ticker":"models/tickers/ticker","underscore":"underscore"}],"models/tickers/datetime_ticker":[function(require,module,exports){
var AdaptiveTicker, CompositeTicker, DatetimeTicker, DaysTicker, MonthsTicker, ONE_HOUR, ONE_MILLI, ONE_MINUTE, ONE_MONTH, ONE_SECOND, YearsTicker, _, util,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

AdaptiveTicker = require("./adaptive_ticker");

CompositeTicker = require("./composite_ticker");

DaysTicker = require("./days_ticker");

MonthsTicker = require("./months_ticker");

YearsTicker = require("./years_ticker");

util = require("./util");

ONE_MILLI = util.ONE_MILLI;

ONE_SECOND = util.ONE_SECOND;

ONE_MINUTE = util.ONE_MINUTE;

ONE_HOUR = util.ONE_HOUR;

ONE_MONTH = util.ONE_MONTH;

DatetimeTicker = (function(superClass) {
  extend(DatetimeTicker, superClass);

  function DatetimeTicker() {
    return DatetimeTicker.__super__.constructor.apply(this, arguments);
  }

  DatetimeTicker.prototype.type = 'DatetimeTicker';

  DatetimeTicker.override({
    num_minor_ticks: 0,
    tickers: function() {
      return [
        new AdaptiveTicker.Model({
          mantissas: [1, 2, 5],
          base: 10,
          min_interval: 0,
          max_interval: 500 * ONE_MILLI,
          num_minor_ticks: 0
        }), new AdaptiveTicker.Model({
          mantissas: [1, 2, 5, 10, 15, 20, 30],
          base: 60,
          min_interval: ONE_SECOND,
          max_interval: 30 * ONE_MINUTE,
          num_minor_ticks: 0
        }), new AdaptiveTicker.Model({
          mantissas: [1, 2, 4, 6, 8, 12],
          base: 24.0,
          min_interval: ONE_HOUR,
          max_interval: 12 * ONE_HOUR,
          num_minor_ticks: 0
        }), new DaysTicker.Model({
          days: _.range(1, 32)
        }), new DaysTicker.Model({
          days: _.range(1, 31, 3)
        }), new DaysTicker.Model({
          days: [1, 8, 15, 22]
        }), new DaysTicker.Model({
          days: [1, 15]
        }), new MonthsTicker.Model({
          months: _.range(0, 12, 1)
        }), new MonthsTicker.Model({
          months: _.range(0, 12, 2)
        }), new MonthsTicker.Model({
          months: _.range(0, 12, 4)
        }), new MonthsTicker.Model({
          months: _.range(0, 12, 6)
        }), new YearsTicker.Model({})
      ];
    }
  });

  return DatetimeTicker;

})(CompositeTicker.Model);

module.exports = {
  Model: DatetimeTicker
};

},{"./adaptive_ticker":"models/tickers/adaptive_ticker","./composite_ticker":"models/tickers/composite_ticker","./days_ticker":"models/tickers/days_ticker","./months_ticker":"models/tickers/months_ticker","./util":"models/tickers/util","./years_ticker":"models/tickers/years_ticker","underscore":"underscore"}],"models/tickers/days_ticker":[function(require,module,exports){
var DaysTicker, ONE_DAY, SingleIntervalTicker, _, copy_date, date_range_by_month, last_month_no_later_than, p, util,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SingleIntervalTicker = require("./single_interval_ticker");

util = require("./util");

p = require("../../core/properties");

copy_date = util.copy_date;

last_month_no_later_than = util.last_month_no_later_than;

ONE_DAY = util.ONE_DAY;

date_range_by_month = function(start_time, end_time) {
  var date, dates, end_date, prev_end_date, start_date;
  start_date = last_month_no_later_than(new Date(start_time));
  end_date = last_month_no_later_than(new Date(end_time));
  prev_end_date = copy_date(end_date);
  end_date.setUTCMonth(end_date.getUTCMonth() + 1);
  dates = [];
  date = start_date;
  while (true) {
    dates.push(copy_date(date));
    date.setUTCMonth(date.getUTCMonth() + 1);
    if (date > end_date) {
      break;
    }
  }
  return dates;
};

DaysTicker = (function(superClass) {
  extend(DaysTicker, superClass);

  function DaysTicker() {
    return DaysTicker.__super__.constructor.apply(this, arguments);
  }

  DaysTicker.prototype.type = 'DaysTicker';

  DaysTicker.define({
    days: [p.Array, []]
  });

  DaysTicker.prototype.initialize = function(attrs, options) {
    var days, interval;
    attrs.num_minor_ticks = 0;
    DaysTicker.__super__.initialize.call(this, attrs, options);
    days = this.get('days');
    interval = days.length > 1 ? (days[1] - days[0]) * ONE_DAY : 31 * ONE_DAY;
    return this.set('interval', interval);
  };

  DaysTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var all_ticks, date, day_dates, days, days_of_month, interval, month_dates, ticks_in_range;
    month_dates = date_range_by_month(data_low, data_high);
    days = this.get('days');
    days_of_month = (function(_this) {
      return function(month_date, interval) {
        var dates, day, day_date, future_date, i, len;
        dates = [];
        for (i = 0, len = days.length; i < len; i++) {
          day = days[i];
          day_date = copy_date(month_date);
          day_date.setUTCDate(day);
          future_date = new Date(day_date.getTime() + (interval / 2));
          if (future_date.getUTCMonth() === month_date.getUTCMonth()) {
            dates.push(day_date);
          }
        }
        return dates;
      };
    })(this);
    interval = this.get('interval');
    day_dates = _.flatten((function() {
      var i, len, results;
      results = [];
      for (i = 0, len = month_dates.length; i < len; i++) {
        date = month_dates[i];
        results.push(days_of_month(date, interval));
      }
      return results;
    })());
    all_ticks = _.invoke(day_dates, 'getTime');
    ticks_in_range = _.filter(all_ticks, (function(tick) {
      return (data_low <= tick && tick <= data_high);
    }));
    return {
      "major": ticks_in_range,
      "minor": []
    };
  };

  return DaysTicker;

})(SingleIntervalTicker.Model);

module.exports = {
  Model: DaysTicker
};

},{"../../core/properties":"core/properties","./single_interval_ticker":"models/tickers/single_interval_ticker","./util":"models/tickers/util","underscore":"underscore"}],"models/tickers/fixed_ticker":[function(require,module,exports){
var ContinuousTicker, FixedTicker, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ContinuousTicker = require("./continuous_ticker");

p = require("../../core/properties");

FixedTicker = (function(superClass) {
  extend(FixedTicker, superClass);

  function FixedTicker() {
    return FixedTicker.__super__.constructor.apply(this, arguments);
  }

  FixedTicker.prototype.type = 'FixedTicker';

  FixedTicker.define({
    ticks: [p.Array, []]
  });

  FixedTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    return {
      major: this.get('ticks'),
      minor: []
    };
  };

  return FixedTicker;

})(ContinuousTicker.Model);

module.exports = {
  Model: FixedTicker
};

},{"../../core/properties":"core/properties","./continuous_ticker":"models/tickers/continuous_ticker","underscore":"underscore"}],"models/tickers/log_ticker":[function(require,module,exports){
var AdaptiveTicker, LogTicker, _, range,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

AdaptiveTicker = require("./adaptive_ticker");

range = function(start, stop, step) {
  var i, result;
  if (_.isUndefined(stop)) {
    stop = start;
    start = 0;
  }
  if (_.isUndefined(step)) {
    step = 1;
  }
  if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
    return [];
  }
  result = [];
  i = start;
  while ((step > 0 ? i < stop : i > stop)) {
    result.push(i);
    i += step;
  }
  return result;
};

LogTicker = (function(superClass) {
  extend(LogTicker, superClass);

  function LogTicker() {
    return LogTicker.__super__.constructor.apply(this, arguments);
  }

  LogTicker.prototype.type = 'LogTicker';

  LogTicker.override({
    mantissas: [1, 5]
  });

  LogTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var base, end_factor, endlog, factor, factors, i, interval, j, k, l, len, len1, len2, len3, len4, len5, log_high, log_interval, log_low, m, minor_interval, minor_offsets, minor_ticks, n, num_minor_ticks, o, ref, start_factor, startlog, tick, ticks, x;
    num_minor_ticks = this.get('num_minor_ticks');
    minor_ticks = [];
    if (data_low <= 0) {
      data_low = 1;
    }
    if (data_low > data_high) {
      ref = [data_high, data_low], data_low = ref[0], data_high = ref[1];
    }
    base = this.get('base');
    log_low = Math.log(data_low) / Math.log(base);
    log_high = Math.log(data_high) / Math.log(base);
    log_interval = log_high - log_low;
    if (log_interval < 2) {
      interval = this.get_interval(data_low, data_high, desired_n_ticks);
      start_factor = Math.floor(data_low / interval);
      end_factor = Math.ceil(data_high / interval);
      if (_.isNaN(start_factor) || _.isNaN(end_factor)) {
        factors = [];
      } else {
        factors = _.range(start_factor, end_factor + 1);
      }
      ticks = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = factors.length; j < len; j++) {
          factor = factors[j];
          if (factor !== 0) {
            results.push(factor * interval);
          }
        }
        return results;
      })();
      if (num_minor_ticks > 1) {
        minor_interval = interval / num_minor_ticks;
        minor_offsets = (function() {
          var j, ref1, results;
          results = [];
          for (i = j = 1, ref1 = num_minor_ticks; 1 <= ref1 ? j <= ref1 : j >= ref1; i = 1 <= ref1 ? ++j : --j) {
            results.push(i * minor_interval);
          }
          return results;
        })();
        for (j = 0, len = minor_offsets.length; j < len; j++) {
          x = minor_offsets[j];
          minor_ticks.push(ticks[0] - x);
        }
        for (k = 0, len1 = ticks.length; k < len1; k++) {
          tick = ticks[k];
          for (l = 0, len2 = minor_offsets.length; l < len2; l++) {
            x = minor_offsets[l];
            minor_ticks.push(tick + x);
          }
        }
      }
    } else {
      startlog = Math.ceil(log_low);
      endlog = Math.floor(log_high);
      interval = Math.ceil((endlog - startlog) / 9.0);
      ticks = range(startlog, endlog, interval);
      if ((endlog - startlog) % interval === 0) {
        ticks = ticks.concat([endlog]);
      }
      ticks = ticks.map(function(i) {
        return Math.pow(base, i);
      });
      if (num_minor_ticks > 1) {
        minor_interval = Math.pow(base, interval) / num_minor_ticks;
        minor_offsets = (function() {
          var m, ref1, results;
          results = [];
          for (i = m = 1, ref1 = num_minor_ticks; 1 <= ref1 ? m <= ref1 : m >= ref1; i = 1 <= ref1 ? ++m : --m) {
            results.push(i * minor_interval);
          }
          return results;
        })();
        for (m = 0, len3 = minor_offsets.length; m < len3; m++) {
          x = minor_offsets[m];
          minor_ticks.push(ticks[0] / x);
        }
        for (n = 0, len4 = ticks.length; n < len4; n++) {
          tick = ticks[n];
          for (o = 0, len5 = minor_offsets.length; o < len5; o++) {
            x = minor_offsets[o];
            minor_ticks.push(tick * x);
          }
        }
      }
    }
    return {
      "major": ticks,
      "minor": minor_ticks
    };
  };

  return LogTicker;

})(AdaptiveTicker.Model);

module.exports = {
  Model: LogTicker
};

},{"./adaptive_ticker":"models/tickers/adaptive_ticker","underscore":"underscore"}],"models/tickers/months_ticker":[function(require,module,exports){
var MonthsTicker, ONE_MONTH, SingleIntervalTicker, _, copy_date, date_range_by_year, last_year_no_later_than, p, util,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SingleIntervalTicker = require("./single_interval_ticker");

util = require("./util");

p = require("../../core/properties");

copy_date = util.copy_date;

last_year_no_later_than = util.last_year_no_later_than;

ONE_MONTH = util.ONE_MONTH;

date_range_by_year = function(start_time, end_time) {
  var date, dates, end_date, start_date;
  start_date = last_year_no_later_than(new Date(start_time));
  end_date = last_year_no_later_than(new Date(end_time));
  end_date.setUTCFullYear(end_date.getUTCFullYear() + 1);
  dates = [];
  date = start_date;
  while (true) {
    dates.push(copy_date(date));
    date.setUTCFullYear(date.getUTCFullYear() + 1);
    if (date > end_date) {
      break;
    }
  }
  return dates;
};

MonthsTicker = (function(superClass) {
  extend(MonthsTicker, superClass);

  function MonthsTicker() {
    return MonthsTicker.__super__.constructor.apply(this, arguments);
  }

  MonthsTicker.prototype.type = 'MonthsTicker';

  MonthsTicker.define({
    months: [p.Array, []]
  });

  MonthsTicker.prototype.initialize = function(attrs, options) {
    var interval, months;
    MonthsTicker.__super__.initialize.call(this, attrs, options);
    months = this.get('months');
    interval = months.length > 1 ? (months[1] - months[0]) * ONE_MONTH : 12 * ONE_MONTH;
    return this.set('interval', interval);
  };

  MonthsTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var all_ticks, date, month_dates, months, months_of_year, ticks_in_range, year_dates;
    year_dates = date_range_by_year(data_low, data_high);
    months = this.get('months');
    months_of_year = function(year_date) {
      return months.map(function(month) {
        var month_date;
        month_date = copy_date(year_date);
        month_date.setUTCMonth(month);
        return month_date;
      });
    };
    month_dates = _.flatten((function() {
      var i, len, results;
      results = [];
      for (i = 0, len = year_dates.length; i < len; i++) {
        date = year_dates[i];
        results.push(months_of_year(date));
      }
      return results;
    })());
    all_ticks = _.invoke(month_dates, 'getTime');
    ticks_in_range = _.filter(all_ticks, (function(tick) {
      return (data_low <= tick && tick <= data_high);
    }));
    return {
      "major": ticks_in_range,
      "minor": []
    };
  };

  return MonthsTicker;

})(SingleIntervalTicker.Model);

module.exports = {
  Model: MonthsTicker
};

},{"../../core/properties":"core/properties","./single_interval_ticker":"models/tickers/single_interval_ticker","./util":"models/tickers/util","underscore":"underscore"}],"models/tickers/single_interval_ticker":[function(require,module,exports){
var ContinuousTicker, SingleIntervalTicker, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ContinuousTicker = require("./continuous_ticker");

p = require("../../core/properties");

SingleIntervalTicker = (function(superClass) {
  extend(SingleIntervalTicker, superClass);

  function SingleIntervalTicker() {
    return SingleIntervalTicker.__super__.constructor.apply(this, arguments);
  }

  SingleIntervalTicker.prototype.type = 'SingleIntervalTicker';

  SingleIntervalTicker.define({
    interval: [p.Number]
  });

  SingleIntervalTicker.prototype.initialize = function(attrs, options) {
    SingleIntervalTicker.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('min_interval', function() {
      return this.get('interval');
    }, true);
    this.add_dependencies('min_interval', this, ['interval']);
    this.define_computed_property('max_interval', function() {
      return this.get('interval');
    }, true);
    return this.add_dependencies('max_interval', this, ['interval']);
  };

  SingleIntervalTicker.prototype.get_interval = function(data_low, data_high, n_desired_ticks) {
    return this.get('interval');
  };

  return SingleIntervalTicker;

})(ContinuousTicker.Model);

module.exports = {
  Model: SingleIntervalTicker
};

},{"../../core/properties":"core/properties","./continuous_ticker":"models/tickers/continuous_ticker","underscore":"underscore"}],"models/tickers/ticker":[function(require,module,exports){
var Model, Ticker, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../../model");

Ticker = (function(superClass) {
  extend(Ticker, superClass);

  function Ticker() {
    return Ticker.__super__.constructor.apply(this, arguments);
  }

  Ticker.prototype.type = 'Ticker';

  Ticker.prototype.get_ticks = function(data_low, data_high, range, arg) {
    var desired_n_ticks;
    desired_n_ticks = arg.desired_n_ticks;
    return this.get_ticks_no_defaults(data_low, data_high, this.get('desired_num_ticks'));
  };

  Ticker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var end_factor, factor, factors, i, interval, j, k, l, len, len1, len2, minor_interval, minor_offsets, minor_ticks, num_minor_ticks, start_factor, tick, ticks, x;
    interval = this.get_interval(data_low, data_high, desired_n_ticks);
    start_factor = Math.floor(data_low / interval);
    end_factor = Math.ceil(data_high / interval);
    if (_.isNaN(start_factor) || _.isNaN(end_factor)) {
      factors = [];
    } else {
      factors = _.range(start_factor, end_factor + 1);
    }
    ticks = (function() {
      var j, len, results;
      results = [];
      for (j = 0, len = factors.length; j < len; j++) {
        factor = factors[j];
        results.push(factor * interval);
      }
      return results;
    })();
    num_minor_ticks = this.get("num_minor_ticks");
    minor_ticks = [];
    if (num_minor_ticks > 1) {
      minor_interval = interval / num_minor_ticks;
      minor_offsets = (function() {
        var j, ref, results;
        results = [];
        for (i = j = 1, ref = num_minor_ticks; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) {
          results.push(i * minor_interval);
        }
        return results;
      })();
      for (j = 0, len = minor_offsets.length; j < len; j++) {
        x = minor_offsets[j];
        minor_ticks.push(ticks[0] - x);
      }
      for (k = 0, len1 = ticks.length; k < len1; k++) {
        tick = ticks[k];
        for (l = 0, len2 = minor_offsets.length; l < len2; l++) {
          x = minor_offsets[l];
          minor_ticks.push(tick + x);
        }
      }
    }
    return {
      "major": ticks,
      "minor": minor_ticks
    };
  };

  return Ticker;

})(Model);

module.exports = {
  Model: Ticker
};

},{"../../model":"model","underscore":"underscore"}],"models/tickers/util":[function(require,module,exports){
var ONE_DAY, ONE_HOUR, ONE_MILLI, ONE_MINUTE, ONE_MONTH, ONE_SECOND, ONE_YEAR, _, argmin, copy_date, last_month_no_later_than, last_year_no_later_than;

_ = require("underscore");

ONE_MILLI = 1.0;

ONE_SECOND = 1000.0;

ONE_MINUTE = 60.0 * ONE_SECOND;

ONE_HOUR = 60 * ONE_MINUTE;

ONE_DAY = 24 * ONE_HOUR;

ONE_MONTH = 30 * ONE_DAY;

ONE_YEAR = 365 * ONE_DAY;

argmin = function(arr) {
  var ret;
  ret = _.min(_.range(arr.length), (function(i) {
    return arr[i];
  }));
  return ret;
};

copy_date = function(date) {
  return new Date(date.getTime());
};

last_month_no_later_than = function(date) {
  date = copy_date(date);
  date.setUTCDate(1);
  date.setUTCHours(0);
  date.setUTCMinutes(0);
  date.setUTCSeconds(0);
  date.setUTCMilliseconds(0);
  return date;
};

last_year_no_later_than = function(date) {
  date = last_month_no_later_than(date);
  date.setUTCMonth(0);
  return date;
};

module.exports = {
  argmin: argmin,
  copy_date: copy_date,
  last_month_no_later_than: last_month_no_later_than,
  last_year_no_later_than: last_year_no_later_than,
  ONE_MILLI: ONE_MILLI,
  ONE_SECOND: ONE_SECOND,
  ONE_MINUTE: ONE_MINUTE,
  ONE_HOUR: ONE_HOUR,
  ONE_DAY: ONE_DAY,
  ONE_MONTH: ONE_MONTH,
  ONE_YEAR: ONE_YEAR
};

},{"underscore":"underscore"}],"models/tickers/years_ticker":[function(require,module,exports){
var BasicTicker, ONE_YEAR, SingleIntervalTicker, YearsTicker, _, last_year_no_later_than, util,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

BasicTicker = require("./basic_ticker");

SingleIntervalTicker = require("./single_interval_ticker");

util = require("./util");

last_year_no_later_than = util.last_year_no_later_than;

ONE_YEAR = util.ONE_YEAR;

YearsTicker = (function(superClass) {
  extend(YearsTicker, superClass);

  function YearsTicker() {
    return YearsTicker.__super__.constructor.apply(this, arguments);
  }

  YearsTicker.prototype.type = 'YearsTicker';

  YearsTicker.prototype.initialize = function(attrs, options) {
    YearsTicker.__super__.initialize.call(this, attrs, options);
    this.set('interval', ONE_YEAR);
    return this.basic_ticker = new BasicTicker.Model({
      num_minor_ticks: 0
    });
  };

  YearsTicker.prototype.get_ticks_no_defaults = function(data_low, data_high, desired_n_ticks) {
    var all_ticks, end_year, start_year, ticks_in_range, year, years;
    start_year = last_year_no_later_than(new Date(data_low)).getUTCFullYear();
    end_year = last_year_no_later_than(new Date(data_high)).getUTCFullYear();
    years = this.basic_ticker.get_ticks_no_defaults(start_year, end_year, desired_n_ticks).major;
    all_ticks = (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = years.length; i < len; i++) {
        year = years[i];
        results.push(Date.UTC(year, 0, 1));
      }
      return results;
    })();
    ticks_in_range = _.filter(all_ticks, (function(tick) {
      return (data_low <= tick && tick <= data_high);
    }));
    return {
      major: ticks_in_range,
      minor: []
    };
  };

  return YearsTicker;

})(SingleIntervalTicker.Model);

module.exports = {
  Model: YearsTicker
};

},{"./basic_ticker":"models/tickers/basic_ticker","./single_interval_ticker":"models/tickers/single_interval_ticker","./util":"models/tickers/util","underscore":"underscore"}],"models/tiles/bbox_tile_source":[function(require,module,exports){
var BBoxTileSource, MercatorTileSource, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

MercatorTileSource = require('./mercator_tile_source');

p = require("../../core/properties");

BBoxTileSource = (function(superClass) {
  extend(BBoxTileSource, superClass);

  function BBoxTileSource() {
    return BBoxTileSource.__super__.constructor.apply(this, arguments);
  }

  BBoxTileSource.prototype.type = 'BBoxTileSource';

  BBoxTileSource.define({
    use_latlon: [p.Bool, false]
  });

  BBoxTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url, ref, ref1, xmax, xmin, ymax, ymin;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    if (this.get('use_latlon')) {
      ref = this.get_tile_geographic_bounds(x, y, z), xmin = ref[0], ymin = ref[1], xmax = ref[2], ymax = ref[3];
    } else {
      ref1 = this.get_tile_meter_bounds(x, y, z), xmin = ref1[0], ymin = ref1[1], xmax = ref1[2], ymax = ref1[3];
    }
    return image_url.replace("{XMIN}", xmin).replace("{YMIN}", ymin).replace("{XMAX}", xmax).replace("{YMAX}", ymax);
  };

  return BBoxTileSource;

})(MercatorTileSource);

module.exports = {
  Model: BBoxTileSource
};

},{"../../core/properties":"core/properties","./mercator_tile_source":"models/tiles/mercator_tile_source","underscore":"underscore"}],"models/tiles/dynamic_image_renderer":[function(require,module,exports){
var DynamicImageRenderer, DynamicImageView, ImagePool, Renderer, _, logger, p,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ImagePool = require("./image_pool");

Renderer = require("../renderers/renderer");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

DynamicImageView = (function(superClass) {
  extend(DynamicImageView, superClass);

  function DynamicImageView() {
    this._on_image_error = bind(this._on_image_error, this);
    this._on_image_load = bind(this._on_image_load, this);
    return DynamicImageView.__super__.constructor.apply(this, arguments);
  }

  DynamicImageView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change', this.request_render);
  };

  DynamicImageView.prototype.get_extent = function() {
    return [this.x_range.get('start'), this.y_range.get('start'), this.x_range.get('end'), this.y_range.get('end')];
  };

  DynamicImageView.prototype._set_data = function() {
    this.map_plot = this.plot_view.model.plot;
    this.map_canvas = this.plot_view.canvas_view.ctx;
    this.map_frame = this.plot_view.frame;
    this.x_range = this.map_plot.get('x_range');
    this.x_mapper = this.map_frame.get('x_mappers')['default'];
    this.y_range = this.map_plot.get('y_range');
    this.y_mapper = this.map_frame.get('y_mappers')['default'];
    this.lastImage = void 0;
    return this.extent = this.get_extent();
  };

  DynamicImageView.prototype._map_data = function() {
    return this.initial_extent = this.get_extent();
  };

  DynamicImageView.prototype._on_image_load = function(e) {
    var image_data;
    image_data = e.target.image_data;
    image_data.img = e.target;
    image_data.loaded = true;
    this.lastImage = image_data;
    if (this.get_extent().join(':') === image_data.cache_key) {
      return this.request_render();
    }
  };

  DynamicImageView.prototype._on_image_error = function(e) {
    var image_data;
    logger.error('Error loading image: #{e.target.src}');
    image_data = e.target.image_data;
    return this.mget('image_source').remove_image(image_data);
  };

  DynamicImageView.prototype._create_image = function(bounds) {
    var image;
    image = new Image();
    image.onload = this._on_image_load;
    image.onerror = this._on_image_error;
    image.alt = '';
    image.image_data = {
      bounds: bounds,
      loaded: false,
      cache_key: bounds.join(':')
    };
    this.mget('image_source').add_image(image.image_data);
    image.src = this.mget('image_source').get_image_url(bounds[0], bounds[1], bounds[2], bounds[3], Math.ceil(this.map_frame.get('height')), Math.ceil(this.map_frame.get('width')));
    return image;
  };

  DynamicImageView.prototype.render = function(ctx, indices, args) {
    var extent, image_obj;
    if (this.map_initialized == null) {
      this._set_data();
      this._map_data();
      this.map_initialized = true;
    }
    extent = this.get_extent();
    if (this.render_timer) {
      clearTimeout(this.render_timer);
    }
    image_obj = this.mget('image_source').images[extent.join(':')];
    if ((image_obj != null) && image_obj.loaded) {
      this._draw_image(extent.join(':'));
      return;
    }
    if (this.lastImage != null) {
      this._draw_image(this.lastImage.cache_key);
    }
    if (image_obj == null) {
      return this.render_timer = setTimeout(((function(_this) {
        return function() {
          return _this._create_image(extent);
        };
      })(this)), 125);
    }
  };

  DynamicImageView.prototype._draw_image = function(image_key) {
    var image_obj, ref, ref1, sh, sw, sx, sxmax, sxmin, sy, symax, symin;
    image_obj = this.mget('image_source').images[image_key];
    if (image_obj != null) {
      this.map_canvas.save();
      this._set_rect();
      this.map_canvas.globalAlpha = this.mget('alpha');
      ref = this.plot_view.frame.map_to_screen([image_obj.bounds[0]], [image_obj.bounds[3]], this.plot_view.canvas), sxmin = ref[0], symin = ref[1];
      ref1 = this.plot_view.frame.map_to_screen([image_obj.bounds[2]], [image_obj.bounds[1]], this.plot_view.canvas), sxmax = ref1[0], symax = ref1[1];
      sxmin = sxmin[0];
      symin = symin[0];
      sxmax = sxmax[0];
      symax = symax[0];
      sw = sxmax - sxmin;
      sh = symax - symin;
      sx = sxmin;
      sy = symin;
      this.map_canvas.drawImage(image_obj.img, sx, sy, sw, sh);
      return this.map_canvas.restore();
    }
  };

  DynamicImageView.prototype._set_rect = function() {
    var h, l, outline_width, t, w;
    outline_width = this.plot_model.plot.properties.outline_line_width.value();
    l = this.plot_view.canvas.vx_to_sx(this.map_frame.get('left')) + (outline_width / 2);
    t = this.plot_view.canvas.vy_to_sy(this.map_frame.get('top')) + (outline_width / 2);
    w = this.map_frame.get('width') - outline_width;
    h = this.map_frame.get('height') - outline_width;
    this.map_canvas.rect(l, t, w, h);
    return this.map_canvas.clip();
  };

  return DynamicImageView;

})(Renderer.View);

DynamicImageRenderer = (function(superClass) {
  extend(DynamicImageRenderer, superClass);

  function DynamicImageRenderer() {
    return DynamicImageRenderer.__super__.constructor.apply(this, arguments);
  }

  DynamicImageRenderer.prototype.default_view = DynamicImageView;

  DynamicImageRenderer.prototype.type = 'DynamicImageRenderer';

  DynamicImageRenderer.define({
    alpha: [p.Number, 1.0],
    image_source: [p.Instance],
    render_parents: [p.Bool, true]
  });

  DynamicImageRenderer.override({
    level: 'underlay'
  });

  return DynamicImageRenderer;

})(Renderer.Model);

module.exports = {
  Model: DynamicImageRenderer,
  View: DynamicImageView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../renderers/renderer":"models/renderers/renderer","./image_pool":"models/tiles/image_pool","underscore":"underscore"}],"models/tiles/image_pool":[function(require,module,exports){
var ImagePool;

ImagePool = (function() {
  function ImagePool() {
    this.images = [];
  }

  ImagePool.prototype.pop = function() {
    var img;
    img = this.images.pop();
    if (img != null) {
      return img;
    } else {
      return new Image();
    }
  };

  ImagePool.prototype.push = function(img) {
    if (this.images.length > 50) {
      return;
    }
    if (img.constructor === Array) {
      return Array.prototype.push.apply(this.images, img);
    } else {
      return this.images.push(img);
    }
  };

  return ImagePool;

})();

module.exports = ImagePool;

},{}],"models/tiles/image_source":[function(require,module,exports){
var ImageSource, Model, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

Model = require("../../model");

ImageSource = (function(superClass) {
  extend(ImageSource, superClass);

  ImageSource.prototype.type = 'ImageSource';

  ImageSource.define({
    url: [p.String, ''],
    extra_url_vars: [p.Any, {}]
  });

  function ImageSource(options) {
    if (options == null) {
      options = {};
    }
    ImageSource.__super__.constructor.apply(this, arguments);
    this.images = {};
    this.normalize_case();
  }

  ImageSource.prototype.normalize_case = function() {
    'Note: should probably be refactored into subclasses.';
    var url;
    url = this.get('url');
    url = url.replace('{xmin}', '{XMIN}');
    url = url.replace('{ymin}', '{YMIN}');
    url = url.replace('{xmax}', '{XMAX}');
    url = url.replace('{ymax}', '{YMAX}');
    url = url.replace('{height}', '{HEIGHT}');
    url = url.replace('{width}', '{WIDTH}');
    return this.set('url', url);
  };

  ImageSource.prototype.string_lookup_replace = function(str, lookup) {
    var key, result_str, value;
    result_str = str;
    for (key in lookup) {
      value = lookup[key];
      result_str = result_str.replace('{' + key + '}', value.toString());
    }
    return result_str;
  };

  ImageSource.prototype.add_image = function(image_obj) {
    return this.images[image_obj.cache_key] = image_obj;
  };

  ImageSource.prototype.remove_image = function(image_obj) {
    return delete this.images[image_obj.cache_key];
  };

  ImageSource.prototype.get_image_url = function(xmin, ymin, xmax, ymax, height, width) {
    var image_url;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    return image_url.replace("{XMIN}", xmin).replace("{YMIN}", ymin).replace("{XMAX}", xmax).replace("{YMAX}", ymax).replace("{WIDTH}", width).replace("{HEIGHT}", height);
  };

  return ImageSource;

})(Model);

module.exports = {
  Model: ImageSource
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../../model":"model","underscore":"underscore"}],"models/tiles/mercator_tile_source":[function(require,module,exports){
var MercatorTileSource, TileSource, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

TileSource = require("./tile_source");

p = require("../../core/properties");

MercatorTileSource = (function(superClass) {
  extend(MercatorTileSource, superClass);

  function MercatorTileSource() {
    return MercatorTileSource.__super__.constructor.apply(this, arguments);
  }

  MercatorTileSource.prototype.type = 'MercatorTileSource';

  MercatorTileSource.define({
    wrap_around: [p.Bool, true]
  });

  MercatorTileSource.override({
    x_origin_offset: 20037508.34,
    y_origin_offset: 20037508.34,
    initial_resolution: 156543.03392804097
  });

  MercatorTileSource.prototype.initialize = function(options) {
    var z;
    MercatorTileSource.__super__.initialize.call(this, options);
    return this._resolutions = (function() {
      var j, results;
      results = [];
      for (z = j = 0; j <= 30; z = ++j) {
        results.push(this.get_resolution(z));
      }
      return results;
    }).call(this);
  };

  MercatorTileSource.prototype._computed_initial_resolution = function() {
    if (this.get('initial_resolution') != null) {
      return this.get('initial_resolution');
    } else {
      return 2 * Math.PI * 6378137 / this.get('tile_size');
    }
  };

  MercatorTileSource.prototype.is_valid_tile = function(x, y, z) {
    if (!this.get('wrap_around')) {
      if (x < 0 || x >= Math.pow(2, z)) {
        return false;
      }
    }
    if (y < 0 || y >= Math.pow(2, z)) {
      return false;
    }
    return true;
  };

  MercatorTileSource.prototype.retain_children = function(reference_tile) {
    var key, max_zoom, min_zoom, quadkey, ref, results, tile;
    quadkey = reference_tile.quadkey;
    min_zoom = quadkey.length;
    max_zoom = min_zoom + 3;
    ref = this.tiles;
    results = [];
    for (key in ref) {
      tile = ref[key];
      if (tile.quadkey.indexOf(quadkey) === 0 && tile.quadkey.length > min_zoom && tile.quadkey.length <= max_zoom) {
        results.push(tile.retain = true);
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  MercatorTileSource.prototype.retain_neighbors = function(reference_tile) {
    var key, neighbor_radius, neighbor_x, neighbor_y, ref, ref1, results, tile, tx, ty, tz, x, y;
    neighbor_radius = 4;
    ref = reference_tile.tile_coords, tx = ref[0], ty = ref[1], tz = ref[2];
    neighbor_x = (function() {
      var j, ref1, ref2, results;
      results = [];
      for (x = j = ref1 = tx - neighbor_radius, ref2 = tx + neighbor_radius; ref1 <= ref2 ? j <= ref2 : j >= ref2; x = ref1 <= ref2 ? ++j : --j) {
        results.push(x);
      }
      return results;
    })();
    neighbor_y = (function() {
      var j, ref1, ref2, results;
      results = [];
      for (y = j = ref1 = ty - neighbor_radius, ref2 = ty + neighbor_radius; ref1 <= ref2 ? j <= ref2 : j >= ref2; y = ref1 <= ref2 ? ++j : --j) {
        results.push(y);
      }
      return results;
    })();
    ref1 = this.tiles;
    results = [];
    for (key in ref1) {
      tile = ref1[key];
      if (tile.tile_coords[2] === tz && _.contains(neighbor_x, tile.tile_coords[0]) && _.contains(neighbor_y, tile.tile_coords[1])) {
        results.push(tile.retain = true);
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  MercatorTileSource.prototype.retain_parents = function(reference_tile) {
    var key, quadkey, ref, results, tile;
    quadkey = reference_tile.quadkey;
    ref = this.tiles;
    results = [];
    for (key in ref) {
      tile = ref[key];
      results.push(tile.retain = quadkey.indexOf(tile.quadkey) === 0);
    }
    return results;
  };

  MercatorTileSource.prototype.children_by_tile_xyz = function(x, y, z) {
    var b, child_tile_xyz, i, j, quad_key, ref, ref1, ref2, world_x;
    world_x = this.calculate_world_x_by_tile_xyz(x, y, z);
    if (world_x !== 0) {
      ref = this.normalize_xyz(x, y, z), x = ref[0], y = ref[1], z = ref[2];
    }
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    child_tile_xyz = [];
    for (i = j = 0; j <= 3; i = j += 1) {
      ref1 = this.quadkey_to_tile_xyz(quad_key + i.toString()), x = ref1[0], y = ref1[1], z = ref1[2];
      if (world_x !== 0) {
        ref2 = this.denormalize_xyz(x, y, z, world_x), x = ref2[0], y = ref2[1], z = ref2[2];
      }
      b = this.get_tile_meter_bounds(x, y, z);
      if (b != null) {
        child_tile_xyz.push([x, y, z, b]);
      }
    }
    return child_tile_xyz;
  };

  MercatorTileSource.prototype.parent_by_tile_xyz = function(x, y, z) {
    var parent_quad_key, quad_key;
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    parent_quad_key = quad_key.substring(0, quad_key.length - 1);
    return this.quadkey_to_tile_xyz(parent_quad_key);
  };

  MercatorTileSource.prototype.get_resolution = function(level) {
    return this._computed_initial_resolution() / Math.pow(2, level);
  };

  MercatorTileSource.prototype.get_resolution_by_extent = function(extent, height, width) {
    var x_rs, y_rs;
    x_rs = (extent[2] - extent[0]) / width;
    y_rs = (extent[3] - extent[1]) / height;
    return [x_rs, y_rs];
  };

  MercatorTileSource.prototype.get_level_by_extent = function(extent, height, width) {
    var i, j, len, r, ref, resolution, x_rs, y_rs;
    x_rs = (extent[2] - extent[0]) / width;
    y_rs = (extent[3] - extent[1]) / height;
    resolution = Math.max(x_rs, y_rs);
    i = 0;
    ref = this._resolutions;
    for (j = 0, len = ref.length; j < len; j++) {
      r = ref[j];
      if (resolution > r) {
        if (i === 0) {
          return 0;
        }
        if (i > 0) {
          return i - 1;
        }
      }
      i += 1;
    }
  };

  MercatorTileSource.prototype.get_closest_level_by_extent = function(extent, height, width) {
    var closest, resolution, ress, x_rs, y_rs;
    x_rs = (extent[2] - extent[0]) / width;
    y_rs = (extent[3] - extent[1]) / height;
    resolution = Math.max(x_rs, y_rs);
    ress = this._resolutions;
    closest = this._resolutions.reduce(function(previous, current) {
      if (Math.abs(current - resolution) < Math.abs(previous - resolution)) {
        return current;
      }
      return previous;
    });
    return this._resolutions.indexOf(closest);
  };

  MercatorTileSource.prototype.snap_to_zoom = function(extent, height, width, level) {
    var desired_res, desired_x_delta, desired_y_delta, x_adjust, xmax, xmin, y_adjust, ymax, ymin;
    desired_res = this._resolutions[level];
    desired_x_delta = width * desired_res;
    desired_y_delta = height * desired_res;
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    x_adjust = (desired_x_delta - (xmax - xmin)) / 2;
    y_adjust = (desired_y_delta - (ymax - ymin)) / 2;
    return [xmin - x_adjust, ymin - y_adjust, xmax + x_adjust, ymax + y_adjust];
  };

  MercatorTileSource.prototype.tms_to_wmts = function(x, y, z) {
    'Note this works both ways';
    return [x, Math.pow(2, z) - 1 - y, z];
  };

  MercatorTileSource.prototype.wmts_to_tms = function(x, y, z) {
    'Note this works both ways';
    return [x, Math.pow(2, z) - 1 - y, z];
  };

  MercatorTileSource.prototype.pixels_to_meters = function(px, py, level) {
    var mx, my, res;
    res = this.get_resolution(level);
    mx = px * res - this.get('x_origin_offset');
    my = py * res - this.get('y_origin_offset');
    return [mx, my];
  };

  MercatorTileSource.prototype.meters_to_pixels = function(mx, my, level) {
    var px, py, res;
    res = this.get_resolution(level);
    px = (mx + this.get('x_origin_offset')) / res;
    py = (my + this.get('y_origin_offset')) / res;
    return [px, py];
  };

  MercatorTileSource.prototype.pixels_to_tile = function(px, py) {
    var tx, ty;
    tx = Math.ceil(px / parseFloat(this.get('tile_size')));
    tx = tx === 0 ? tx : tx - 1;
    ty = Math.max(Math.ceil(py / parseFloat(this.get('tile_size'))) - 1, 0);
    return [tx, ty];
  };

  MercatorTileSource.prototype.pixels_to_raster = function(px, py, level) {
    var mapSize;
    mapSize = this.get('tile_size') << level;
    return [px, mapSize - py];
  };

  MercatorTileSource.prototype.meters_to_tile = function(mx, my, level) {
    var px, py, ref;
    ref = this.meters_to_pixels(mx, my, level), px = ref[0], py = ref[1];
    return this.pixels_to_tile(px, py);
  };

  MercatorTileSource.prototype.get_tile_meter_bounds = function(tx, ty, level) {
    var ref, ref1, xmax, xmin, ymax, ymin;
    ref = this.pixels_to_meters(tx * this.get('tile_size'), ty * this.get('tile_size'), level), xmin = ref[0], ymin = ref[1];
    ref1 = this.pixels_to_meters((tx + 1) * this.get('tile_size'), (ty + 1) * this.get('tile_size'), level), xmax = ref1[0], ymax = ref1[1];
    if ((xmin != null) && (ymin != null) && (xmax != null) && (ymax != null)) {
      return [xmin, ymin, xmax, ymax];
    } else {
      return void 0;
    }
  };

  MercatorTileSource.prototype.get_tile_geographic_bounds = function(tx, ty, level) {
    var bounds, maxLat, maxLon, minLat, minLon, ref;
    bounds = this.get_tile_meter_bounds(tx, ty, level);
    ref = this.utils.meters_extent_to_geographic(bounds), minLon = ref[0], minLat = ref[1], maxLon = ref[2], maxLat = ref[3];
    return [minLon, minLat, maxLon, maxLat];
  };

  MercatorTileSource.prototype.get_tiles_by_extent = function(extent, level, tile_border) {
    var j, k, ref, ref1, ref2, ref3, ref4, ref5, tiles, tx, txmax, txmin, ty, tymax, tymin, xmax, xmin, ymax, ymin;
    if (tile_border == null) {
      tile_border = 1;
    }
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    ref = this.meters_to_tile(xmin, ymin, level), txmin = ref[0], tymin = ref[1];
    ref1 = this.meters_to_tile(xmax, ymax, level), txmax = ref1[0], tymax = ref1[1];
    txmin -= tile_border;
    tymin -= tile_border;
    txmax += tile_border;
    tymax += tile_border;
    tiles = [];
    for (ty = j = ref2 = tymax, ref3 = tymin; j >= ref3; ty = j += -1) {
      for (tx = k = ref4 = txmin, ref5 = txmax; k <= ref5; tx = k += 1) {
        if (this.is_valid_tile(tx, ty, level)) {
          tiles.push([tx, ty, level, this.get_tile_meter_bounds(tx, ty, level)]);
        }
      }
    }
    tiles = this.sort_tiles_from_center(tiles, [txmin, tymin, txmax, tymax]);
    return tiles;
  };

  MercatorTileSource.prototype.quadkey_to_tile_xyz = function(quadKey) {
    'Computes tile x, y and z values based on quadKey.';
    var i, j, mask, ref, tileX, tileY, tileZ, value;
    tileX = 0;
    tileY = 0;
    tileZ = quadKey.length;
    for (i = j = ref = tileZ; j > 0; i = j += -1) {
      value = quadKey.charAt(tileZ - i);
      mask = 1 << (i - 1);
      if (value === '0') {
        continue;
      } else if (value === '1') {
        tileX |= mask;
      } else if (value === '2') {
        tileY |= mask;
      } else if (value === '3') {
        tileX |= mask;
        tileY |= mask;
      } else {
        throw new TypeError("Invalid Quadkey: " + quadKey);
      }
    }
    return [tileX, tileY, tileZ];
  };

  MercatorTileSource.prototype.tile_xyz_to_quadkey = function(x, y, z) {
    'Computes quadkey value based on tile x, y and z values.';
    var digit, i, j, mask, quadKey, ref;
    quadKey = '';
    for (i = j = ref = z; j > 0; i = j += -1) {
      digit = 0;
      mask = 1 << (i - 1);
      if ((x & mask) !== 0) {
        digit += 1;
      }
      if ((y & mask) !== 0) {
        digit += 2;
      }
      quadKey += digit.toString();
    }
    return quadKey;
  };

  MercatorTileSource.prototype.children_by_tile_xyz = function(x, y, z) {
    var b, child_tile_xyz, i, j, quad_key, ref;
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    child_tile_xyz = [];
    for (i = j = 0; j <= 3; i = j += 1) {
      ref = this.quadkey_to_tile_xyz(quad_key + i.toString()), x = ref[0], y = ref[1], z = ref[2];
      b = this.get_tile_meter_bounds(x, y, z);
      if (b != null) {
        child_tile_xyz.push([x, y, z, b]);
      }
    }
    return child_tile_xyz;
  };

  MercatorTileSource.prototype.parent_by_tile_xyz = function(x, y, z) {
    var parent_quad_key, quad_key;
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    parent_quad_key = quad_key.substring(0, quad_key.length - 1);
    return this.quadkey_to_tile_xyz(parent_quad_key);
  };

  MercatorTileSource.prototype.get_closest_parent_by_tile_xyz = function(x, y, z) {
    var quad_key, ref, ref1, ref2, world_x;
    world_x = this.calculate_world_x_by_tile_xyz(x, y, z);
    ref = this.normalize_xyz(x, y, z), x = ref[0], y = ref[1], z = ref[2];
    quad_key = this.tile_xyz_to_quadkey(x, y, z);
    while (quad_key.length > 0) {
      quad_key = quad_key.substring(0, quad_key.length - 1);
      ref1 = this.quadkey_to_tile_xyz(quad_key), x = ref1[0], y = ref1[1], z = ref1[2];
      ref2 = this.denormalize_xyz(x, y, z, world_x), x = ref2[0], y = ref2[1], z = ref2[2];
      if (this.tile_xyz_to_key(x, y, z) in this.tiles) {
        return [x, y, z];
      }
    }
    return [0, 0, 0];
  };

  MercatorTileSource.prototype.normalize_xyz = function(x, y, z) {
    var tile_count;
    if (this.get('wrap_around')) {
      tile_count = Math.pow(2, z);
      return [((x % tile_count) + tile_count) % tile_count, y, z];
    } else {
      return [x, y, z];
    }
  };

  MercatorTileSource.prototype.denormalize_xyz = function(x, y, z, world_x) {
    return [x + world_x * Math.pow(2, z), y, z];
  };

  MercatorTileSource.prototype.denormalize_meters = function(meters_x, meters_y, level, world_x) {
    return [meters_x + world_x * 2 * Math.PI * 6378137, meters_y];
  };

  MercatorTileSource.prototype.calculate_world_x_by_tile_xyz = function(x, y, z) {
    return Math.floor(x / Math.pow(2, z));
  };

  return MercatorTileSource;

})(TileSource);

module.exports = MercatorTileSource;

},{"../../core/properties":"core/properties","./tile_source":"models/tiles/tile_source","underscore":"underscore"}],"models/tiles/quadkey_tile_source":[function(require,module,exports){
var MercatorTileSource, QUADKEYTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MercatorTileSource = require('./mercator_tile_source');

QUADKEYTileSource = (function(superClass) {
  extend(QUADKEYTileSource, superClass);

  function QUADKEYTileSource() {
    return QUADKEYTileSource.__super__.constructor.apply(this, arguments);
  }

  QUADKEYTileSource.prototype.type = 'QUADKEYTileSource';

  QUADKEYTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url, quadKey, ref;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    ref = this.tms_to_wmts(x, y, z), x = ref[0], y = ref[1], z = ref[2];
    quadKey = this.tile_xyz_to_quadkey(x, y, z);
    return image_url.replace("{Q}", quadKey);
  };

  return QUADKEYTileSource;

})(MercatorTileSource);

module.exports = {
  Model: QUADKEYTileSource
};

},{"./mercator_tile_source":"models/tiles/mercator_tile_source"}],"models/tiles/tile_renderer":[function(require,module,exports){
var $, ImagePool, Renderer, TileRenderer, TileRendererView, _, logger, p, wmts,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

_ = require("underscore");

$ = require("jquery");

ImagePool = require("./image_pool");

wmts = require("./wmts_tile_source");

Renderer = require("../renderers/renderer");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

TileRendererView = (function(superClass) {
  extend(TileRendererView, superClass);

  function TileRendererView() {
    this._update = bind(this._update, this);
    this._prefetch_tiles = bind(this._prefetch_tiles, this);
    this._on_tile_error = bind(this._on_tile_error, this);
    this._on_tile_cache_load = bind(this._on_tile_cache_load, this);
    this._on_tile_load = bind(this._on_tile_load, this);
    this._add_attribution = bind(this._add_attribution, this);
    return TileRendererView.__super__.constructor.apply(this, arguments);
  }

  TileRendererView.prototype.initialize = function(options) {
    this.attributionEl = null;
    return TileRendererView.__super__.initialize.apply(this, arguments);
  };

  TileRendererView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change', this.request_render);
  };

  TileRendererView.prototype.get_extent = function() {
    return [this.x_range.get('start'), this.y_range.get('start'), this.x_range.get('end'), this.y_range.get('end')];
  };

  TileRendererView.prototype._set_data = function() {
    this.pool = new ImagePool();
    this.map_plot = this.plot_model.plot;
    this.map_canvas = this.plot_view.canvas_view.ctx;
    this.map_frame = this.plot_model.frame;
    this.x_range = this.map_plot.get('x_range');
    this.x_mapper = this.map_frame.get('x_mappers')['default'];
    this.y_range = this.map_plot.get('y_range');
    this.y_mapper = this.map_frame.get('y_mappers')['default'];
    this.extent = this.get_extent();
    this._last_height = void 0;
    return this._last_width = void 0;
  };

  TileRendererView.prototype._add_attribution = function() {
    var attribution, border_width, bottom_offset, max_width, overlays, right_offset;
    attribution = this.mget('tile_source').get('attribution');
    if (_.isString(attribution) && attribution.length > 0) {
      if (this.attributionEl != null) {
        return this.attributionEl.html(attribution);
      } else {
        border_width = this.map_plot.get('outline_line_width');
        bottom_offset = this.map_plot.get('min_border_bottom') + border_width;
        right_offset = this.map_frame.get('right') - this.map_frame.get('width');
        max_width = this.map_frame.get('width') - border_width;
        this.attributionEl = $('<div>').html(attribution).addClass('bk-tile-attribution').css({
          'position': 'absolute',
          'bottom': bottom_offset + "px",
          'right': right_offset + "px",
          'max-width': max_width + "px",
          'background-color': 'rgba(255,255,255,0.8)',
          'font-size': '9pt',
          'font-family': 'sans-serif'
        });
        overlays = this.plot_view.$el.find('div.bk-canvas-events');
        return this.attributionEl.appendTo(overlays);
      }
    }
  };

  TileRendererView.prototype._map_data = function() {
    var new_extent, zoom_level;
    this.initial_extent = this.get_extent();
    zoom_level = this.mget('tile_source').get_level_by_extent(this.initial_extent, this.map_frame.get('height'), this.map_frame.get('width'));
    new_extent = this.mget('tile_source').snap_to_zoom(this.initial_extent, this.map_frame.get('height'), this.map_frame.get('width'), zoom_level);
    this.x_range.set('start', new_extent[0]);
    this.y_range.set('start', new_extent[1]);
    this.x_range.set('end', new_extent[2]);
    this.y_range.set('end', new_extent[3]);
    return this._add_attribution();
  };

  TileRendererView.prototype._on_tile_load = function(e) {
    var tile_data;
    tile_data = e.target.tile_data;
    tile_data.img = e.target;
    tile_data.current = true;
    tile_data.loaded = true;
    return this.request_render();
  };

  TileRendererView.prototype._on_tile_cache_load = function(e) {
    var tile_data;
    tile_data = e.target.tile_data;
    tile_data.img = e.target;
    return tile_data.loaded = true;
  };

  TileRendererView.prototype._on_tile_error = function(e) {
    return '';
  };

  TileRendererView.prototype._create_tile = function(x, y, z, bounds, cache_only) {
    var normalized_coords, ref, tile;
    if (cache_only == null) {
      cache_only = false;
    }
    normalized_coords = this.mget('tile_source').normalize_xyz(x, y, z);
    tile = this.pool.pop();
    if (cache_only) {
      tile.onload = this._on_tile_cache_load;
    } else {
      tile.onload = this._on_tile_load;
    }
    tile.onerror = this._on_tile_error;
    tile.alt = '';
    tile.tile_data = {
      tile_coords: [x, y, z],
      normalized_coords: normalized_coords,
      quadkey: this.mget('tile_source').tile_xyz_to_quadkey(x, y, z),
      cache_key: this.mget('tile_source').tile_xyz_to_key(x, y, z),
      bounds: bounds,
      loaded: false,
      x_coord: bounds[0],
      y_coord: bounds[3]
    };
    this.mget('tile_source').tiles[tile.tile_data.cache_key] = tile.tile_data;
    tile.src = (ref = this.mget('tile_source')).get_image_url.apply(ref, normalized_coords);
    return tile;
  };

  TileRendererView.prototype._enforce_aspect_ratio = function() {
    var extent, new_extent, zoom_level;
    if (this._last_height !== this.map_frame.get('height') || this._last_width !== this.map_frame.get('width')) {
      extent = this.get_extent();
      zoom_level = this.mget('tile_source').get_level_by_extent(extent, this.map_frame.get('height'), this.map_frame.get('width'));
      new_extent = this.mget('tile_source').snap_to_zoom(extent, this.map_frame.get('height'), this.map_frame.get('width'), zoom_level);
      this.x_range.set({
        start: new_extent[0],
        end: new_extent[2]
      });
      this.y_range.set({
        start: new_extent[1],
        end: new_extent[3]
      });
      this.extent = new_extent;
      this._last_height = this.map_frame.get('height');
      this._last_width = this.map_frame.get('width');
      return true;
    }
    return false;
  };

  TileRendererView.prototype.render = function(ctx, indices, args) {
    if (this.map_initialized == null) {
      this._set_data();
      this._map_data();
      this.map_initialized = true;
    }
    if (this._enforce_aspect_ratio()) {
      return;
    }
    this._update();
    if (this.prefetch_timer != null) {
      clearTimeout(this.prefetch_timer);
    }
    return this.prefetch_timer = setTimeout(this._prefetch_tiles, 500);
  };

  TileRendererView.prototype._draw_tile = function(tile_key) {
    var ref, ref1, sh, sw, sx, sxmax, sxmin, sy, symax, symin, tile_obj;
    tile_obj = this.mget('tile_source').tiles[tile_key];
    if (tile_obj != null) {
      ref = this.plot_view.frame.map_to_screen([tile_obj.bounds[0]], [tile_obj.bounds[3]], this.plot_view.canvas), sxmin = ref[0], symin = ref[1];
      ref1 = this.plot_view.frame.map_to_screen([tile_obj.bounds[2]], [tile_obj.bounds[1]], this.plot_view.canvas), sxmax = ref1[0], symax = ref1[1];
      sxmin = sxmin[0];
      symin = symin[0];
      sxmax = sxmax[0];
      symax = symax[0];
      sw = sxmax - sxmin;
      sh = symax - symin;
      sx = sxmin;
      sy = symin;
      return this.map_canvas.drawImage(tile_obj.img, sx, sy, sw, sh);
    }
  };

  TileRendererView.prototype._set_rect = function() {
    var h, l, outline_width, t, w;
    outline_width = this.plot_model.plot.properties.outline_line_width.value();
    l = this.plot_view.canvas.vx_to_sx(this.map_frame.get('left')) + (outline_width / 2);
    t = this.plot_view.canvas.vy_to_sy(this.map_frame.get('top')) + (outline_width / 2);
    w = this.map_frame.get('width') - outline_width;
    h = this.map_frame.get('height') - outline_width;
    this.map_canvas.rect(l, t, w, h);
    return this.map_canvas.clip();
  };

  TileRendererView.prototype._render_tiles = function(tile_keys) {
    var i, len, tile_key;
    this.map_canvas.save();
    this._set_rect();
    this.map_canvas.globalAlpha = this.mget('alpha');
    for (i = 0, len = tile_keys.length; i < len; i++) {
      tile_key = tile_keys[i];
      this._draw_tile(tile_key);
    }
    return this.map_canvas.restore();
  };

  TileRendererView.prototype._prefetch_tiles = function() {
    var bounds, c, cbounds, children, cx, cy, cz, extent, h, i, ref, results, t, tile_source, tiles, w, x, y, z, zoom_level;
    tile_source = this.mget('tile_source');
    extent = this.get_extent();
    h = this.map_frame.get('height');
    w = this.map_frame.get('width');
    zoom_level = this.mget('tile_source').get_level_by_extent(extent, h, w);
    tiles = this.mget('tile_source').get_tiles_by_extent(extent, zoom_level);
    results = [];
    for (t = i = 0, ref = Math.min(10, tiles.length); i <= ref; t = i += 1) {
      x = t[0], y = t[1], z = t[2], bounds = t[3];
      children = this.mget('tile_source').children_by_tile_xyz(x, y, z);
      results.push((function() {
        var j, len, results1;
        results1 = [];
        for (j = 0, len = children.length; j < len; j++) {
          c = children[j];
          cx = c[0], cy = c[1], cz = c[2], cbounds = c[3];
          if (tile_source.tile_xyz_to_key(cx, cy, cz) in tile_source.tiles) {
            continue;
          } else {
            results1.push(this._create_tile(cx, cy, cz, cbounds, true));
          }
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  TileRendererView.prototype._fetch_tiles = function(tiles) {
    var bounds, i, len, results, t, x, y, z;
    results = [];
    for (i = 0, len = tiles.length; i < len; i++) {
      t = tiles[i];
      x = t[0], y = t[1], z = t[2], bounds = t[3];
      results.push(this._create_tile(x, y, z, bounds));
    }
    return results;
  };

  TileRendererView.prototype._update = function() {
    var bounds, c, cached, cbounds, child_key, children, cx, cy, cz, extent, h, i, j, k, key, len, len1, len2, max_zoom, min_zoom, need_load, parent_key, parent_tile, parents, px, py, pz, ref, snap_back, t, tile, tile_source, tiles, w, x, y, z, zoom_level, zooming_out;
    tile_source = this.mget('tile_source');
    min_zoom = tile_source.get('min_zoom');
    max_zoom = tile_source.get('max_zoom');
    tile_source.update();
    extent = this.get_extent();
    zooming_out = this.extent[2] - this.extent[0] < extent[2] - extent[0];
    h = this.map_frame.get('height');
    w = this.map_frame.get('width');
    zoom_level = tile_source.get_level_by_extent(extent, h, w);
    snap_back = false;
    if (zoom_level < min_zoom) {
      extent = this.extent;
      zoom_level = min_zoom;
      snap_back = true;
    } else if (zoom_level > max_zoom) {
      extent = this.extent;
      zoom_level = max_zoom;
      snap_back = true;
    }
    if (snap_back) {
      this.x_range.set({
        x_range: {
          start: extent[0],
          end: extent[2]
        }
      });
      this.y_range.set({
        start: extent[1],
        end: extent[3]
      });
      this.extent = extent;
    }
    this.extent = extent;
    tiles = tile_source.get_tiles_by_extent(extent, zoom_level);
    parents = [];
    need_load = [];
    cached = [];
    children = [];
    for (i = 0, len = tiles.length; i < len; i++) {
      t = tiles[i];
      x = t[0], y = t[1], z = t[2], bounds = t[3];
      key = tile_source.tile_xyz_to_key(x, y, z);
      tile = tile_source.tiles[key];
      if ((tile != null) && tile.loaded === true) {
        cached.push(key);
      } else {
        if (this.mget('render_parents')) {
          ref = tile_source.get_closest_parent_by_tile_xyz(x, y, z), px = ref[0], py = ref[1], pz = ref[2];
          parent_key = tile_source.tile_xyz_to_key(px, py, pz);
          parent_tile = tile_source.tiles[parent_key];
          if ((parent_tile != null) && parent_tile.loaded && indexOf.call(parents, parent_key) < 0) {
            parents.push(parent_key);
          }
          if (zooming_out) {
            children = tile_source.children_by_tile_xyz(x, y, z);
            for (j = 0, len1 = children.length; j < len1; j++) {
              c = children[j];
              cx = c[0], cy = c[1], cz = c[2], cbounds = c[3];
              child_key = tile_source.tile_xyz_to_key(cx, cy, cz);
              if (child_key in tile_source.tiles) {
                children.push(child_key);
              }
            }
          }
        }
      }
      if (tile == null) {
        need_load.push(t);
      }
    }
    this._render_tiles(parents);
    this._render_tiles(children);
    this._render_tiles(cached);
    for (k = 0, len2 = cached.length; k < len2; k++) {
      t = cached[k];
      tile_source.tiles[t].current = true;
    }
    if (this.render_timer != null) {
      clearTimeout(this.render_timer);
    }
    return this.render_timer = setTimeout(((function(_this) {
      return function() {
        return _this._fetch_tiles(need_load);
      };
    })(this)), 65);
  };

  return TileRendererView;

})(Renderer.View);

TileRenderer = (function(superClass) {
  extend(TileRenderer, superClass);

  function TileRenderer() {
    return TileRenderer.__super__.constructor.apply(this, arguments);
  }

  TileRenderer.prototype.default_view = TileRendererView;

  TileRenderer.prototype.type = 'TileRenderer';

  TileRenderer.define({
    alpha: [p.Number, 1.0],
    x_range_name: [p.String, "default"],
    y_range_name: [p.String, "default"],
    tile_source: [
      p.Instance, function() {
        return new wmts.Model();
      }
    ],
    render_parents: [p.Bool, true]
  });

  TileRenderer.override({
    level: 'underlay'
  });

  return TileRenderer;

})(Renderer.Model);

module.exports = {
  Model: TileRenderer,
  View: TileRendererView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../renderers/renderer":"models/renderers/renderer","./image_pool":"models/tiles/image_pool","./wmts_tile_source":"models/tiles/wmts_tile_source","jquery":"jquery","underscore":"underscore"}],"models/tiles/tile_source":[function(require,module,exports){
var ImagePool, Model, TileSource, _, logger, p, tile_utils,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ImagePool = require("./image_pool");

tile_utils = require("./tile_utils");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

Model = require("../../model");

TileSource = (function(superClass) {
  extend(TileSource, superClass);

  TileSource.prototype.type = 'TileSource';

  TileSource.define({
    url: [p.String, ''],
    tile_size: [p.Number, 256],
    max_zoom: [p.Number, 30],
    min_zoom: [p.Number, 0],
    extra_url_vars: [p.Any, {}],
    attribution: [p.String, ''],
    x_origin_offset: [p.Number],
    y_origin_offset: [p.Number],
    initial_resolution: [p.Number]
  });

  TileSource.prototype.initialize = function(options) {
    TileSource.__super__.initialize.call(this, options);
    return this.normalize_case();
  };

  function TileSource(options) {
    if (options == null) {
      options = {};
    }
    TileSource.__super__.constructor.apply(this, arguments);
    this.utils = new tile_utils.ProjectionUtils();
    this.pool = new ImagePool();
    this.tiles = {};
    this.normalize_case();
  }

  TileSource.prototype.string_lookup_replace = function(str, lookup) {
    var key, result_str, value;
    result_str = str;
    for (key in lookup) {
      value = lookup[key];
      result_str = result_str.replace('{' + key + '}', value.toString());
    }
    return result_str;
  };

  TileSource.prototype.normalize_case = function() {
    'Note: should probably be refactored into subclasses.';
    var url;
    url = this.get('url');
    url = url.replace('{x}', '{X}');
    url = url.replace('{y}', '{Y}');
    url = url.replace('{z}', '{Z}');
    url = url.replace('{q}', '{Q}');
    url = url.replace('{xmin}', '{XMIN}');
    url = url.replace('{ymin}', '{YMIN}');
    url = url.replace('{xmax}', '{XMAX}');
    url = url.replace('{ymax}', '{YMAX}');
    return this.set('url', url);
  };

  TileSource.prototype.update = function() {
    var key, ref, results, tile;
    logger.debug("TileSource: tile cache count: " + (Object.keys(this.tiles).length));
    ref = this.tiles;
    results = [];
    for (key in ref) {
      tile = ref[key];
      tile.current = false;
      results.push(tile.retain = false);
    }
    return results;
  };

  TileSource.prototype.tile_xyz_to_key = function(x, y, z) {
    var key;
    key = x + ":" + y + ":" + z;
    return key;
  };

  TileSource.prototype.key_to_tile_xyz = function(key) {
    var c;
    return (function() {
      var i, len, ref, results;
      ref = key.split(':');
      results = [];
      for (i = 0, len = ref.length; i < len; i++) {
        c = ref[i];
        results.push(parseInt(c));
      }
      return results;
    })();
  };

  TileSource.prototype.sort_tiles_from_center = function(tiles, tile_extent) {
    var center_x, center_y, txmax, txmin, tymax, tymin;
    txmin = tile_extent[0], tymin = tile_extent[1], txmax = tile_extent[2], tymax = tile_extent[3];
    center_x = (txmax - txmin) / 2 + txmin;
    center_y = (tymax - tymin) / 2 + tymin;
    tiles.sort(function(a, b) {
      var a_distance, b_distance;
      a_distance = Math.sqrt(Math.pow(center_x - a[0], 2) + Math.pow(center_y - a[1], 2));
      b_distance = Math.sqrt(Math.pow(center_x - b[0], 2) + Math.pow(center_y - b[1], 2));
      return a_distance - b_distance;
    });
    return tiles;
  };

  TileSource.prototype.prune_tiles = function() {
    var key, ref, ref1, results, tile;
    ref = this.tiles;
    for (key in ref) {
      tile = ref[key];
      tile.retain = tile.current || tile.tile_coords[2] < 3;
      if (tile.current) {
        this.retain_neighbors(tile);
        this.retain_children(tile);
        this.retain_parents(tile);
      }
    }
    ref1 = this.tiles;
    results = [];
    for (key in ref1) {
      tile = ref1[key];
      if (!tile.retain) {
        results.push(this.remove_tile(key));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  TileSource.prototype.remove_tile = function(key) {
    var tile;
    tile = this.tiles[key];
    if (tile != null) {
      this.pool.push(tile.img);
      return delete this.tiles[key];
    }
  };

  TileSource.prototype.get_image_url = function(x, y, z) {
    var image_url;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    return image_url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z);
  };

  TileSource.prototype.retain_neighbors = function(reference_tile) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.retain_parents = function(reference_tile) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.retain_children = function(reference_tile) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.tile_xyz_to_quadkey = function(x, y, z) {
    throw Error("Not Implemented");
  };

  TileSource.prototype.quadkey_to_tile_xyz = function(quadkey) {
    throw Error("Not Implemented");
  };

  return TileSource;

})(Model);

module.exports = TileSource;

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../../model":"model","./image_pool":"models/tiles/image_pool","./tile_utils":"models/tiles/tile_utils","underscore":"underscore"}],"models/tiles/tile_utils":[function(require,module,exports){
var ProjectionUtils, mercator, proj4, wgs84;

proj4 = require("proj4");

mercator = proj4.defs('GOOGLE');

wgs84 = proj4.defs('WGS84');

ProjectionUtils = (function() {
  function ProjectionUtils() {
    this.origin_shift = 2 * Math.PI * 6378137 / 2.0;
  }

  ProjectionUtils.prototype.geographic_to_meters = function(xLon, yLat) {
    return proj4(wgs84, mercator, [xLon, yLat]);
  };

  ProjectionUtils.prototype.meters_to_geographic = function(mx, my) {
    return proj4(mercator, wgs84, [mx, my]);
  };

  ProjectionUtils.prototype.geographic_extent_to_meters = function(extent) {
    var ref, ref1, xmax, xmin, ymax, ymin;
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    ref = this.geographic_to_meters(xmin, ymin), xmin = ref[0], ymin = ref[1];
    ref1 = this.geographic_to_meters(xmax, ymax), xmax = ref1[0], ymax = ref1[1];
    return [xmin, ymin, xmax, ymax];
  };

  ProjectionUtils.prototype.meters_extent_to_geographic = function(extent) {
    var ref, ref1, xmax, xmin, ymax, ymin;
    xmin = extent[0], ymin = extent[1], xmax = extent[2], ymax = extent[3];
    ref = this.meters_to_geographic(xmin, ymin), xmin = ref[0], ymin = ref[1];
    ref1 = this.meters_to_geographic(xmax, ymax), xmax = ref1[0], ymax = ref1[1];
    return [xmin, ymin, xmax, ymax];
  };

  return ProjectionUtils;

})();

module.exports = {
  ProjectionUtils: ProjectionUtils
};

},{"proj4":"proj4"}],"models/tiles/tms_tile_source":[function(require,module,exports){
var MercatorTileSource, TMSTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MercatorTileSource = require('./mercator_tile_source');

TMSTileSource = (function(superClass) {
  extend(TMSTileSource, superClass);

  function TMSTileSource() {
    return TMSTileSource.__super__.constructor.apply(this, arguments);
  }

  TMSTileSource.prototype.type = 'TMSTileSource';

  TMSTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    return image_url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z);
  };

  return TMSTileSource;

})(MercatorTileSource);

module.exports = {
  Model: TMSTileSource
};

},{"./mercator_tile_source":"models/tiles/mercator_tile_source"}],"models/tiles/wmts_tile_source":[function(require,module,exports){
var MercatorTileSource, WMTSTileSource,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

MercatorTileSource = require('./mercator_tile_source');

WMTSTileSource = (function(superClass) {
  extend(WMTSTileSource, superClass);

  function WMTSTileSource() {
    return WMTSTileSource.__super__.constructor.apply(this, arguments);
  }

  WMTSTileSource.prototype.type = 'WMTSTileSource';

  WMTSTileSource.prototype.get_image_url = function(x, y, z) {
    var image_url, ref;
    image_url = this.string_lookup_replace(this.get('url'), this.get('extra_url_vars'));
    ref = this.tms_to_wmts(x, y, z), x = ref[0], y = ref[1], z = ref[2];
    return image_url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z);
  };

  return WMTSTileSource;

})(MercatorTileSource);

module.exports = {
  Model: WMTSTileSource
};

},{"./mercator_tile_source":"models/tiles/mercator_tile_source"}],"models/tools/actions/action_tool":[function(require,module,exports){
var ActionTool, ActionToolButtonView, ActionToolView, ButtonTool,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ButtonTool = require("../button_tool");

ActionToolButtonView = (function(superClass) {
  extend(ActionToolButtonView, superClass);

  function ActionToolButtonView() {
    return ActionToolButtonView.__super__.constructor.apply(this, arguments);
  }

  ActionToolButtonView.prototype._clicked = function() {
    return this.model.trigger('do');
  };

  return ActionToolButtonView;

})(ButtonTool.ButtonView);

ActionToolView = (function(superClass) {
  extend(ActionToolView, superClass);

  function ActionToolView() {
    return ActionToolView.__super__.constructor.apply(this, arguments);
  }

  ActionToolView.prototype.initialize = function(options) {
    ActionToolView.__super__.initialize.call(this, options);
    return this.listenTo(this.model, 'do', this["do"]);
  };

  return ActionToolView;

})(ButtonTool.View);

ActionTool = (function(superClass) {
  extend(ActionTool, superClass);

  function ActionTool() {
    return ActionTool.__super__.constructor.apply(this, arguments);
  }

  return ActionTool;

})(ButtonTool.Model);

module.exports = {
  Model: ActionTool,
  View: ActionToolView,
  ButtonView: ActionToolButtonView
};

},{"../button_tool":"models/tools/button_tool"}],"models/tools/actions/help_tool":[function(require,module,exports){
var ActionTool, HelpTool, HelpToolView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ActionTool = require("./action_tool");

p = require("../../../core/properties");

HelpToolView = (function(superClass) {
  extend(HelpToolView, superClass);

  function HelpToolView() {
    return HelpToolView.__super__.constructor.apply(this, arguments);
  }

  HelpToolView.prototype["do"] = function() {
    return window.open(this.mget('redirect'));
  };

  return HelpToolView;

})(ActionTool.View);

HelpTool = (function(superClass) {
  extend(HelpTool, superClass);

  function HelpTool() {
    return HelpTool.__super__.constructor.apply(this, arguments);
  }

  HelpTool.prototype.default_view = HelpToolView;

  HelpTool.prototype.type = "HelpTool";

  HelpTool.prototype.tool_name = "Help";

  HelpTool.prototype.icon = "bk-tool-icon-help";

  HelpTool.define({
    help_tooltip: [p.String, 'Click the question mark to learn more about Bokeh plot tools.'],
    redirect: [p.String, 'http://bokeh.pydata.org/en/latest/docs/user_guide/tools.html']
  });

  HelpTool.prototype.initialize = function(attrs, options) {
    HelpTool.__super__.initialize.call(this, attrs, options);
    return this.override_computed_property('tooltip', function() {
      return this.get('help_tooltip');
    });
  };

  return HelpTool;

})(ActionTool.Model);

module.exports = {
  Model: HelpTool,
  View: HelpToolView
};

},{"../../../core/properties":"core/properties","./action_tool":"models/tools/actions/action_tool","underscore":"underscore"}],"models/tools/actions/redo_tool":[function(require,module,exports){
var ActionTool, RedoTool, RedoToolView,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ActionTool = require("./action_tool");

RedoToolView = (function(superClass) {
  extend(RedoToolView, superClass);

  function RedoToolView() {
    return RedoToolView.__super__.constructor.apply(this, arguments);
  }

  RedoToolView.prototype.initialize = function(options) {
    RedoToolView.__super__.initialize.call(this, options);
    return this.listenTo(this.plot_view, "state_changed", (function(_this) {
      return function() {
        return _this.model.set('disabled', !_this.plot_view.can_redo());
      };
    })(this));
  };

  RedoToolView.prototype["do"] = function() {
    return this.plot_view.redo();
  };

  return RedoToolView;

})(ActionTool.View);

RedoTool = (function(superClass) {
  extend(RedoTool, superClass);

  function RedoTool() {
    return RedoTool.__super__.constructor.apply(this, arguments);
  }

  RedoTool.prototype.default_view = RedoToolView;

  RedoTool.prototype.type = "RedoTool";

  RedoTool.prototype.tool_name = "Redo";

  RedoTool.prototype.icon = "bk-tool-icon-redo";

  RedoTool.override({
    disabled: true
  });

  return RedoTool;

})(ActionTool.Model);

module.exports = {
  Model: RedoTool,
  View: RedoToolView
};

},{"./action_tool":"models/tools/actions/action_tool"}],"models/tools/actions/reset_tool":[function(require,module,exports){
var ActionTool, ResetTool, ResetToolView, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ActionTool = require("./action_tool");

p = require("../../../core/properties");

ResetToolView = (function(superClass) {
  extend(ResetToolView, superClass);

  function ResetToolView() {
    return ResetToolView.__super__.constructor.apply(this, arguments);
  }

  ResetToolView.prototype["do"] = function() {
    this.plot_view.clear_state();
    this.plot_view.reset_range();
    this.plot_view.reset_selection();
    if (this.model.reset_size) {
      return this.plot_view.reset_dimensions();
    }
  };

  return ResetToolView;

})(ActionTool.View);

ResetTool = (function(superClass) {
  extend(ResetTool, superClass);

  function ResetTool() {
    return ResetTool.__super__.constructor.apply(this, arguments);
  }

  ResetTool.prototype.default_view = ResetToolView;

  ResetTool.prototype.type = "ResetTool";

  ResetTool.prototype.tool_name = "Reset";

  ResetTool.prototype.icon = "bk-tool-icon-reset";

  ResetTool.define({
    reset_size: [p.Bool, true]
  });

  return ResetTool;

})(ActionTool.Model);

module.exports = {
  Model: ResetTool,
  View: ResetToolView
};

},{"../../../core/properties":"core/properties","./action_tool":"models/tools/actions/action_tool"}],"models/tools/actions/save_tool":[function(require,module,exports){
var ActionTool, SaveTool, SaveToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ActionTool = require("./action_tool");

SaveToolView = (function(superClass) {
  extend(SaveToolView, superClass);

  function SaveToolView() {
    return SaveToolView.__super__.constructor.apply(this, arguments);
  }

  SaveToolView.prototype["do"] = function() {
    var blob, canvas, link, name;
    canvas = this.plot_view.get_canvas_element();
    name = "bokeh_plot.png";
    if (canvas.msToBlob != null) {
      blob = canvas.msToBlob();
      return window.navigator.msSaveBlob(blob, name);
    } else {
      link = document.createElement('a');
      link.href = canvas.toDataURL('image/png');
      link.download = name;
      link.target = "_blank";
      return link.dispatchEvent(new MouseEvent('click'));
    }
  };

  return SaveToolView;

})(ActionTool.View);

SaveTool = (function(superClass) {
  extend(SaveTool, superClass);

  function SaveTool() {
    return SaveTool.__super__.constructor.apply(this, arguments);
  }

  SaveTool.prototype.default_view = SaveToolView;

  SaveTool.prototype.type = "SaveTool";

  SaveTool.prototype.tool_name = "Save";

  SaveTool.prototype.icon = "bk-tool-icon-save";

  return SaveTool;

})(ActionTool.Model);

module.exports = {
  Model: SaveTool,
  View: SaveToolView
};

},{"./action_tool":"models/tools/actions/action_tool","underscore":"underscore"}],"models/tools/actions/undo_tool":[function(require,module,exports){
var ActionTool, UndoTool, UndoToolView,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

ActionTool = require("./action_tool");

UndoToolView = (function(superClass) {
  extend(UndoToolView, superClass);

  function UndoToolView() {
    return UndoToolView.__super__.constructor.apply(this, arguments);
  }

  UndoToolView.prototype.initialize = function(options) {
    UndoToolView.__super__.initialize.call(this, options);
    return this.listenTo(this.plot_view, "state_changed", (function(_this) {
      return function() {
        return _this.model.set('disabled', !_this.plot_view.can_undo());
      };
    })(this));
  };

  UndoToolView.prototype["do"] = function() {
    return this.plot_view.undo();
  };

  return UndoToolView;

})(ActionTool.View);

UndoTool = (function(superClass) {
  extend(UndoTool, superClass);

  function UndoTool() {
    return UndoTool.__super__.constructor.apply(this, arguments);
  }

  UndoTool.prototype.default_view = UndoToolView;

  UndoTool.prototype.type = "UndoTool";

  UndoTool.prototype.tool_name = "Undo";

  UndoTool.prototype.icon = "bk-tool-icon-undo";

  UndoTool.override({
    disabled: true
  });

  return UndoTool;

})(ActionTool.Model);

module.exports = {
  Model: UndoTool,
  View: UndoToolView
};

},{"./action_tool":"models/tools/actions/action_tool"}],"models/tools/button_tool":[function(require,module,exports){
var Backbone, ButtonTool, ButtonToolButtonView, ButtonToolView, Tool, _, button_tool_template, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Backbone = require("backbone");

Tool = require("./tool");

button_tool_template = require("./button_tool_template");

p = require("../../core/properties");

ButtonToolButtonView = (function(superClass) {
  extend(ButtonToolButtonView, superClass);

  function ButtonToolButtonView() {
    return ButtonToolButtonView.__super__.constructor.apply(this, arguments);
  }

  ButtonToolButtonView.prototype.tagName = "li";

  ButtonToolButtonView.prototype.template = button_tool_template;

  ButtonToolButtonView.prototype.events = function() {
    return {
      'click .bk-toolbar-button': '_clicked'
    };
  };

  ButtonToolButtonView.prototype.initialize = function(options) {
    ButtonToolButtonView.__super__.initialize.call(this, options);
    this.$el.html(this.template({
      model: this.model
    }));
    this.listenTo(this.model, 'change:active', (function(_this) {
      return function() {
        return _this.render();
      };
    })(this));
    this.listenTo(this.model, 'change:disabled', (function(_this) {
      return function() {
        return _this.render();
      };
    })(this));
    return this.render();
  };

  ButtonToolButtonView.prototype.render = function() {
    this.$el.children('button').prop("disabled", this.model.get('disabled')).toggleClass('active', this.model.get('active'));
    return this;
  };

  ButtonToolButtonView.prototype._clicked = function(e) {};

  return ButtonToolButtonView;

})(Backbone.View);

ButtonToolView = (function(superClass) {
  extend(ButtonToolView, superClass);

  function ButtonToolView() {
    return ButtonToolView.__super__.constructor.apply(this, arguments);
  }

  return ButtonToolView;

})(Tool.View);

ButtonTool = (function(superClass) {
  extend(ButtonTool, superClass);

  function ButtonTool() {
    return ButtonTool.__super__.constructor.apply(this, arguments);
  }

  ButtonTool.prototype.icon = null;

  ButtonTool.prototype.initialize = function(attrs, options) {
    ButtonTool.__super__.initialize.call(this, attrs, options);
    return this.define_computed_property('tooltip', function() {
      return this.tool_name;
    });
  };

  ButtonTool.internal({
    disabled: [p.Boolean, false]
  });

  return ButtonTool;

})(Tool.Model);

module.exports = {
  Model: ButtonTool,
  View: ButtonToolView,
  ButtonView: ButtonToolButtonView
};

},{"../../core/properties":"core/properties","./button_tool_template":"models/tools/button_tool_template","./tool":"models/tools/tool","backbone":"backbone","underscore":"underscore"}],"models/tools/button_tool_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [];
  var __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  };
  var __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  };
  var __safe = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else {
      if (!(typeof value !== 'undefined' && value != null)) value = '';
      var result = new String(value);
      result.ecoSafe = true;
      return result;
    }
  };
  var __escape = function(value) {
    return ('' + value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  };
  (function() {
    (function() {
      __out.push('<button type="button" class="bk-toolbar-button hover">\n  <div class=\'bk-btn-icon ');
    
      __out.push(__sanitize(this.model.icon));
    
      __out.push('\' />\n  <span class=\'tip\'>');
    
      __out.push(__sanitize(this.model.get('tooltip')));
    
      __out.push('</span>\n</button>\n');
    
    }).call(this);
    
  }).call(__obj);
  return __out.join('');
};
},{}],"models/tools/gestures/box_select_tool":[function(require,module,exports){
var BoxAnnotation, BoxSelectTool, BoxSelectToolView, DEFAULT_BOX_OVERLAY, SelectTool, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SelectTool = require("./select_tool");

BoxAnnotation = require("../../annotations/box_annotation");

p = require("../../../core/properties");

BoxSelectToolView = (function(superClass) {
  extend(BoxSelectToolView, superClass);

  function BoxSelectToolView() {
    return BoxSelectToolView.__super__.constructor.apply(this, arguments);
  }

  BoxSelectToolView.prototype._pan_start = function(e) {
    var canvas;
    canvas = this.plot_view.canvas;
    this._baseboint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    return null;
  };

  BoxSelectToolView.prototype._pan = function(e) {
    var append, canvas, curpoint, dims, frame, ref, ref1, vxlim, vylim;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    this.mget('overlay').update({
      left: vxlim[0],
      right: vxlim[1],
      top: vylim[1],
      bottom: vylim[0]
    });
    if (this.mget('select_every_mousemove')) {
      append = (ref1 = e.srcEvent.shiftKey) != null ? ref1 : false;
      this._select(vxlim, vylim, false, append);
    }
    return null;
  };

  BoxSelectToolView.prototype._pan_end = function(e) {
    var append, canvas, curpoint, dims, frame, ref, ref1, vxlim, vylim;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    append = (ref1 = e.srcEvent.shiftKey) != null ? ref1 : false;
    this._select(vxlim, vylim, true, append);
    this.mget('overlay').update({
      left: null,
      right: null,
      top: null,
      bottom: null
    });
    this._baseboint = null;
    this.plot_view.push_state('box_select', {
      selection: this.plot_view.get_selection()
    });
    return null;
  };

  BoxSelectToolView.prototype._select = function(arg, arg1, final, append) {
    var ds, geometry, i, len, r, ref, sm, vx0, vx1, vy0, vy1;
    vx0 = arg[0], vx1 = arg[1];
    vy0 = arg1[0], vy1 = arg1[1];
    if (append == null) {
      append = false;
    }
    geometry = {
      type: 'rect',
      vx0: vx0,
      vx1: vx1,
      vy0: vy0,
      vy1: vy1
    };
    ref = this.mget('computed_renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderer_views[r.id], geometry, final, append);
    }
    if (this.mget('callback') != null) {
      this._emit_callback(geometry);
    }
    this._save_geometry(geometry, final, append);
    return null;
  };

  BoxSelectToolView.prototype._emit_callback = function(geometry) {
    var canvas, frame, r, xmapper, ymapper;
    r = this.mget('computed_renderers')[0];
    canvas = this.plot_model.get('canvas');
    frame = this.plot_model.get('frame');
    geometry['sx0'] = canvas.vx_to_sx(geometry.vx0);
    geometry['sx1'] = canvas.vx_to_sx(geometry.vx1);
    geometry['sy0'] = canvas.vy_to_sy(geometry.vy0);
    geometry['sy1'] = canvas.vy_to_sy(geometry.vy1);
    xmapper = frame.get('x_mappers')[r.get('x_range_name')];
    ymapper = frame.get('y_mappers')[r.get('y_range_name')];
    geometry['x0'] = xmapper.map_from_target(geometry.vx0);
    geometry['x1'] = xmapper.map_from_target(geometry.vx1);
    geometry['y0'] = ymapper.map_from_target(geometry.vy0);
    geometry['y1'] = ymapper.map_from_target(geometry.vy1);
    this.mget('callback').execute(this.model, {
      geometry: geometry
    });
  };

  return BoxSelectToolView;

})(SelectTool.View);

DEFAULT_BOX_OVERLAY = function() {
  return new BoxAnnotation.Model({
    level: "overlay",
    render_mode: "css",
    top_units: "screen",
    left_units: "screen",
    bottom_units: "screen",
    right_units: "screen",
    fill_color: "lightgrey",
    fill_alpha: 0.5,
    line_color: "black",
    line_alpha: 1.0,
    line_width: 2,
    line_dash: [4, 4]
  });
};

BoxSelectTool = (function(superClass) {
  extend(BoxSelectTool, superClass);

  function BoxSelectTool() {
    return BoxSelectTool.__super__.constructor.apply(this, arguments);
  }

  BoxSelectTool.prototype.default_view = BoxSelectToolView;

  BoxSelectTool.prototype.type = "BoxSelectTool";

  BoxSelectTool.prototype.tool_name = "Box Select";

  BoxSelectTool.prototype.icon = "bk-tool-icon-box-select";

  BoxSelectTool.prototype.event_type = "pan";

  BoxSelectTool.prototype.default_order = 30;

  BoxSelectTool.define({
    dimensions: [p.Array, ["width", "height"]],
    select_every_mousemove: [p.Bool, false],
    callback: [p.Instance],
    overlay: [p.Instance, DEFAULT_BOX_OVERLAY]
  });

  BoxSelectTool.prototype.initialize = function(attrs, options) {
    BoxSelectTool.__super__.initialize.call(this, attrs, options);
    this.override_computed_property('tooltip', function() {
      return this._get_dim_tooltip(this.tool_name, this._check_dims(this.get('dimensions'), "box select tool"));
    }, false);
    return this.add_dependencies('tooltip', this, ['dimensions']);
  };

  return BoxSelectTool;

})(SelectTool.Model);

module.exports = {
  Model: BoxSelectTool,
  View: BoxSelectToolView
};

},{"../../../core/properties":"core/properties","../../annotations/box_annotation":"models/annotations/box_annotation","./select_tool":"models/tools/gestures/select_tool","underscore":"underscore"}],"models/tools/gestures/box_zoom_tool":[function(require,module,exports){
var BoxAnnotation, BoxZoomTool, BoxZoomToolView, DEFAULT_BOX_OVERLAY, GestureTool, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

GestureTool = require("./gesture_tool");

BoxAnnotation = require("../../annotations/box_annotation");

p = require("../../../core/properties");

BoxZoomToolView = (function(superClass) {
  extend(BoxZoomToolView, superClass);

  function BoxZoomToolView() {
    return BoxZoomToolView.__super__.constructor.apply(this, arguments);
  }

  BoxZoomToolView.prototype._match_aspect = function(basepoint, curpoint, frame) {
    var a, bottom, h, hend, hstart, left, ref, ref1, right, top, va, vend, vh, vstart, vw, w, xmod, ymod;
    hend = frame.get('h_range').get('end');
    hstart = frame.get('h_range').get('start');
    vend = frame.get('v_range').get('end');
    vstart = frame.get('v_range').get('start');
    w = hend - hstart;
    h = vend - vstart;
    a = w / h;
    vw = Math.abs(basepoint[0] - curpoint[0]);
    vh = Math.abs(basepoint[1] - curpoint[1]);
    if (vh === 0) {
      va = 0;
    } else {
      va = vw / vh;
    }
    if (va >= a) {
      ref = [1, va / a], xmod = ref[0], ymod = ref[1];
    } else {
      ref1 = [a / va, 1], xmod = ref1[0], ymod = ref1[1];
    }
    if (basepoint[0] <= curpoint[0]) {
      left = basepoint[0];
      right = basepoint[0] + vw * xmod;
      if (right > hend) {
        right = hend;
      }
    } else {
      right = basepoint[0];
      left = basepoint[0] - vw * xmod;
      if (left < hstart) {
        left = hstart;
      }
    }
    vw = Math.abs(right - left);
    if (basepoint[1] <= curpoint[1]) {
      bottom = basepoint[1];
      top = basepoint[1] + vw / a;
      if (top > vend) {
        top = vend;
      }
    } else {
      top = basepoint[1];
      bottom = basepoint[1] - vw / a;
      if (bottom < vstart) {
        bottom = vstart;
      }
    }
    vh = Math.abs(top - bottom);
    if (basepoint[0] <= curpoint[0]) {
      right = basepoint[0] + a * vh;
    } else {
      left = basepoint[0] - a * vh;
    }
    return [[left, right], [bottom, top]];
  };

  BoxZoomToolView.prototype._pan_start = function(e) {
    var canvas;
    canvas = this.plot_view.canvas;
    this._baseboint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    return null;
  };

  BoxZoomToolView.prototype._pan = function(e) {
    var canvas, curpoint, dims, frame, ref, ref1, vx, vy;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    if (this.mget('match_aspect') && dims.length === 2) {
      ref = this._match_aspect(this._baseboint, curpoint, frame), vx = ref[0], vy = ref[1];
    } else {
      ref1 = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vx = ref1[0], vy = ref1[1];
    }
    this.mget('overlay').update({
      left: vx[0],
      right: vx[1],
      top: vy[1],
      bottom: vy[0]
    });
    return null;
  };

  BoxZoomToolView.prototype._pan_end = function(e) {
    var canvas, curpoint, dims, frame, ref, ref1, vx, vy;
    canvas = this.plot_view.canvas;
    curpoint = [canvas.sx_to_vx(e.bokeh.sx), canvas.sy_to_vy(e.bokeh.sy)];
    frame = this.plot_model.get('frame');
    dims = this.mget('dimensions');
    if (this.mget('match_aspect') && dims.length === 2) {
      ref = this._match_aspect(this._baseboint, curpoint, frame), vx = ref[0], vy = ref[1];
    } else {
      ref1 = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vx = ref1[0], vy = ref1[1];
    }
    this._update(vx, vy);
    this.mget('overlay').update({
      left: null,
      right: null,
      top: null,
      bottom: null
    });
    this._baseboint = null;
    return null;
  };

  BoxZoomToolView.prototype._update = function(vx, vy) {
    var end, mapper, name, ref, ref1, ref2, ref3, start, xrs, yrs, zoom_info;
    if (Math.abs(vx[1] - vx[0]) <= 5 || Math.abs(vy[1] - vy[0]) <= 5) {
      return;
    }
    xrs = {};
    ref = this.plot_view.frame.get('x_mappers');
    for (name in ref) {
      mapper = ref[name];
      ref1 = mapper.v_map_from_target(vx, true), start = ref1[0], end = ref1[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref2 = this.plot_view.frame.get('y_mappers');
    for (name in ref2) {
      mapper = ref2[name];
      ref3 = mapper.v_map_from_target(vy, true), start = ref3[0], end = ref3[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    zoom_info = {
      xrs: xrs,
      yrs: yrs
    };
    this.plot_view.push_state('box_zoom', {
      range: zoom_info
    });
    return this.plot_view.update_range(zoom_info);
  };

  return BoxZoomToolView;

})(GestureTool.View);

DEFAULT_BOX_OVERLAY = function() {
  return new BoxAnnotation.Model({
    level: "overlay",
    render_mode: "css",
    top_units: "screen",
    left_units: "screen",
    bottom_units: "screen",
    right_units: "screen",
    fill_color: "lightgrey",
    fill_alpha: 0.5,
    line_color: "black",
    line_alpha: 1.0,
    line_width: 2,
    line_dash: [4, 4]
  });
};

BoxZoomTool = (function(superClass) {
  extend(BoxZoomTool, superClass);

  function BoxZoomTool() {
    return BoxZoomTool.__super__.constructor.apply(this, arguments);
  }

  BoxZoomTool.prototype.default_view = BoxZoomToolView;

  BoxZoomTool.prototype.type = "BoxZoomTool";

  BoxZoomTool.prototype.tool_name = "Box Zoom";

  BoxZoomTool.prototype.icon = "bk-tool-icon-box-zoom";

  BoxZoomTool.prototype.event_type = "pan";

  BoxZoomTool.prototype.default_order = 20;

  BoxZoomTool.prototype.initialize = function(attrs, options) {
    BoxZoomTool.__super__.initialize.call(this, attrs, options);
    this.override_computed_property('tooltip', function() {
      return this._get_dim_tooltip(this.tool_name, this._check_dims(this.get('dimensions'), "box zoom tool"));
    }, false);
    return this.add_dependencies('tooltip', this, ['dimensions']);
  };

  BoxZoomTool.define({
    dimensions: [p.Array, ["width", "height"]],
    overlay: [p.Instance, DEFAULT_BOX_OVERLAY],
    match_aspect: [p.Bool, false]
  });

  return BoxZoomTool;

})(GestureTool.Model);

module.exports = {
  Model: BoxZoomTool,
  View: BoxZoomToolView
};

},{"../../../core/properties":"core/properties","../../annotations/box_annotation":"models/annotations/box_annotation","./gesture_tool":"models/tools/gestures/gesture_tool","underscore":"underscore"}],"models/tools/gestures/gesture_tool":[function(require,module,exports){
var ButtonTool, GestureTool, GestureToolButtonView, GestureToolView, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

ButtonTool = require("../button_tool");

GestureToolButtonView = (function(superClass) {
  extend(GestureToolButtonView, superClass);

  function GestureToolButtonView() {
    return GestureToolButtonView.__super__.constructor.apply(this, arguments);
  }

  GestureToolButtonView.prototype._clicked = function() {
    var active;
    active = this.model.get('active');
    return this.model.set('active', !active);
  };

  return GestureToolButtonView;

})(ButtonTool.ButtonView);

GestureToolView = (function(superClass) {
  extend(GestureToolView, superClass);

  function GestureToolView() {
    return GestureToolView.__super__.constructor.apply(this, arguments);
  }

  return GestureToolView;

})(ButtonTool.View);

GestureTool = (function(superClass) {
  extend(GestureTool, superClass);

  function GestureTool() {
    return GestureTool.__super__.constructor.apply(this, arguments);
  }

  GestureTool.prototype.event_type = null;

  GestureTool.prototype.default_order = null;

  return GestureTool;

})(ButtonTool.Model);

module.exports = {
  Model: GestureTool,
  View: GestureToolView,
  ButtonView: GestureToolButtonView
};

},{"../button_tool":"models/tools/button_tool","underscore":"underscore"}],"models/tools/gestures/lasso_select_tool":[function(require,module,exports){
var DEFAULT_POLY_OVERLAY, LassoSelectTool, LassoSelectToolView, PolyAnnotation, SelectTool, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SelectTool = require("./select_tool");

PolyAnnotation = require("../../annotations/poly_annotation");

p = require("../../../core/properties");

LassoSelectToolView = (function(superClass) {
  extend(LassoSelectToolView, superClass);

  function LassoSelectToolView() {
    return LassoSelectToolView.__super__.constructor.apply(this, arguments);
  }

  LassoSelectToolView.prototype.initialize = function(options) {
    LassoSelectToolView.__super__.initialize.call(this, options);
    this.listenTo(this.model, 'change:active', this._active_change);
    return this.data = null;
  };

  LassoSelectToolView.prototype._active_change = function() {
    if (!this.mget('active')) {
      return this._clear_overlay();
    }
  };

  LassoSelectToolView.prototype._keyup = function(e) {
    if (e.keyCode === 13) {
      return this._clear_overlay();
    }
  };

  LassoSelectToolView.prototype._pan_start = function(e) {
    var canvas, vx, vy;
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    this.data = {
      vx: [vx],
      vy: [vy]
    };
    return null;
  };

  LassoSelectToolView.prototype._pan = function(e) {
    var append, canvas, h_range, overlay, ref, v_range, vx, vy;
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    h_range = this.plot_model.get('frame').get('h_range');
    v_range = this.plot_model.get('frame').get('v_range');
    if (vx > h_range.get('end')) {
      vx = h_range.get('end');
    }
    if (vx < h_range.get('start')) {
      vx = h_range.get('start');
    }
    if (vy > v_range.get('end')) {
      vy = v_range.get('end');
    }
    if (vy < v_range.get('start')) {
      vy = v_range.get('start');
    }
    this.data.vx.push(vx);
    this.data.vy.push(vy);
    overlay = this.mget('overlay');
    overlay.update({
      xs: this.data.vx,
      ys: this.data.vy
    });
    if (this.mget('select_every_mousemove')) {
      append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
      return this._select(this.data.vx, this.data.vy, false, append);
    }
  };

  LassoSelectToolView.prototype._pan_end = function(e) {
    var append, ref;
    this._clear_overlay();
    append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
    this._select(this.data.vx, this.data.vy, true, append);
    return this.plot_view.push_state('lasso_select', {
      selection: this.plot_view.get_selection()
    });
  };

  LassoSelectToolView.prototype._clear_overlay = function() {
    return this.mget('overlay').update({
      xs: [],
      ys: []
    });
  };

  LassoSelectToolView.prototype._select = function(vx, vy, final, append) {
    var ds, geometry, i, len, r, ref, sm;
    geometry = {
      type: 'poly',
      vx: vx,
      vy: vy
    };
    ref = this.mget('computed_renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderer_views[r.id], geometry, final, append);
    }
    if (this.mget('callback') != null) {
      this._emit_callback(geometry);
    }
    this._save_geometry(geometry, final, append);
    return null;
  };

  LassoSelectToolView.prototype._emit_callback = function(geometry) {
    var canvas, frame, r, xmapper, ymapper;
    r = this.mget('computed_renderers')[0];
    canvas = this.plot_model.get('canvas');
    frame = this.plot_model.get('frame');
    geometry['sx'] = canvas.v_vx_to_sx(geometry.vx);
    geometry['sy'] = canvas.v_vy_to_sy(geometry.vy);
    xmapper = frame.get('x_mappers')[r.get('x_range_name')];
    ymapper = frame.get('y_mappers')[r.get('y_range_name')];
    geometry['x'] = xmapper.v_map_from_target(geometry.vx);
    geometry['y'] = ymapper.v_map_from_target(geometry.vy);
    this.mget('callback').execute(this.model, {
      geometry: geometry
    });
  };

  return LassoSelectToolView;

})(SelectTool.View);

DEFAULT_POLY_OVERLAY = function() {
  return new PolyAnnotation.Model({
    level: "overlay",
    xs_units: "screen",
    ys_units: "screen",
    fill_color: "lightgrey",
    fill_alpha: 0.5,
    line_color: "black",
    line_alpha: 1.0,
    line_width: 2,
    line_dash: [4, 4]
  });
};

LassoSelectTool = (function(superClass) {
  extend(LassoSelectTool, superClass);

  function LassoSelectTool() {
    return LassoSelectTool.__super__.constructor.apply(this, arguments);
  }

  LassoSelectTool.prototype.default_view = LassoSelectToolView;

  LassoSelectTool.prototype.type = "LassoSelectTool";

  LassoSelectTool.prototype.tool_name = "Lasso Select";

  LassoSelectTool.prototype.icon = "bk-tool-icon-lasso-select";

  LassoSelectTool.prototype.event_type = "pan";

  LassoSelectTool.prototype.default_order = 12;

  LassoSelectTool.define({
    select_every_mousemove: [p.Bool, true],
    callback: [p.Instance],
    overlay: [p.Instance, DEFAULT_POLY_OVERLAY]
  });

  return LassoSelectTool;

})(SelectTool.Model);

module.exports = {
  Model: LassoSelectTool,
  View: LassoSelectToolView
};

},{"../../../core/properties":"core/properties","../../annotations/poly_annotation":"models/annotations/poly_annotation","./select_tool":"models/tools/gestures/select_tool","underscore":"underscore"}],"models/tools/gestures/pan_tool":[function(require,module,exports){
var GestureTool, PanTool, PanToolView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

GestureTool = require("./gesture_tool");

p = require("../../../core/properties");

PanToolView = (function(superClass) {
  extend(PanToolView, superClass);

  function PanToolView() {
    return PanToolView.__super__.constructor.apply(this, arguments);
  }

  PanToolView.prototype._pan_start = function(e) {
    var canvas, frame, hr, vr, vx, vy;
    this.last_dx = 0;
    this.last_dy = 0;
    canvas = this.plot_view.canvas;
    frame = this.plot_view.frame;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (!frame.contains(vx, vy)) {
      hr = frame.get('h_range');
      vr = frame.get('v_range');
      if (vx < hr.get('start') || vx > hr.get('end')) {
        this.v_axis_only = true;
      }
      if (vy < vr.get('start') || vy > vr.get('end')) {
        this.h_axis_only = true;
      }
    }
    return this.plot_view.interactive_timestamp = Date.now();
  };

  PanToolView.prototype._pan = function(e) {
    this._update(e.deltaX, -e.deltaY);
    return this.plot_view.interactive_timestamp = Date.now();
  };

  PanToolView.prototype._pan_end = function(e) {
    this.h_axis_only = false;
    this.v_axis_only = false;
    if (this.pan_info != null) {
      return this.plot_view.push_state('pan', {
        range: this.pan_info
      });
    }
  };

  PanToolView.prototype._update = function(dx, dy) {
    var dims, end, frame, hr, is_panning, mapper, name, new_dx, new_dy, ref, ref1, ref2, ref3, sdx, sdy, start, sx0, sx1, sx_high, sx_low, sy0, sy1, sy_high, sy_low, vr, xrs, yrs;
    frame = this.plot_view.frame;
    new_dx = dx - this.last_dx;
    new_dy = dy - this.last_dy;
    hr = _.clone(frame.get('h_range'));
    sx_low = hr.get('start') - new_dx;
    sx_high = hr.get('end') - new_dx;
    vr = _.clone(frame.get('v_range'));
    sy_low = vr.get('start') - new_dy;
    sy_high = vr.get('end') - new_dy;
    dims = this.mget('dimensions');
    if (dims.indexOf('width') > -1 && !this.v_axis_only) {
      sx0 = sx_low;
      sx1 = sx_high;
      sdx = -new_dx;
    } else {
      sx0 = hr.get('start');
      sx1 = hr.get('end');
      sdx = 0;
    }
    if (dims.indexOf('height') > -1 && !this.h_axis_only) {
      sy0 = sy_low;
      sy1 = sy_high;
      sdy = new_dy;
    } else {
      sy0 = vr.get('start');
      sy1 = vr.get('end');
      sdy = 0;
    }
    this.last_dx = dx;
    this.last_dy = dy;
    xrs = {};
    ref = frame.get('x_mappers');
    for (name in ref) {
      mapper = ref[name];
      ref1 = mapper.v_map_from_target([sx0, sx1], true), start = ref1[0], end = ref1[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref2 = frame.get('y_mappers');
    for (name in ref2) {
      mapper = ref2[name];
      ref3 = mapper.v_map_from_target([sy0, sy1], true), start = ref3[0], end = ref3[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    this.pan_info = {
      xrs: xrs,
      yrs: yrs,
      sdx: sdx,
      sdy: sdy
    };
    this.plot_view.update_range(this.pan_info, is_panning = true);
    return null;
  };

  return PanToolView;

})(GestureTool.View);

PanTool = (function(superClass) {
  extend(PanTool, superClass);

  function PanTool() {
    return PanTool.__super__.constructor.apply(this, arguments);
  }

  PanTool.prototype.default_view = PanToolView;

  PanTool.prototype.type = "PanTool";

  PanTool.prototype.tool_name = "Pan";

  PanTool.prototype.icon = "bk-tool-icon-pan";

  PanTool.prototype.event_type = "pan";

  PanTool.prototype.default_order = 10;

  PanTool.define({
    dimensions: [p.Array, ["width", "height"]]
  });

  PanTool.prototype.initialize = function(attrs, options) {
    PanTool.__super__.initialize.call(this, attrs, options);
    this.override_computed_property('tooltip', function() {
      return this._get_dim_tooltip("Pan", this._check_dims(this.get('dimensions'), "pan tool"));
    }, false);
    return this.add_dependencies('tooltip', this, ['dimensions']);
  };

  return PanTool;

})(GestureTool.Model);

module.exports = {
  Model: PanTool,
  View: PanToolView
};

},{"../../../core/properties":"core/properties","./gesture_tool":"models/tools/gestures/gesture_tool","underscore":"underscore"}],"models/tools/gestures/poly_select_tool":[function(require,module,exports){
var DEFAULT_POLY_OVERLAY, PolyAnnotation, PolySelectTool, PolySelectToolView, SelectTool, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SelectTool = require("./select_tool");

PolyAnnotation = require("../../annotations/poly_annotation");

p = require("../../../core/properties");

PolySelectToolView = (function(superClass) {
  extend(PolySelectToolView, superClass);

  function PolySelectToolView() {
    return PolySelectToolView.__super__.constructor.apply(this, arguments);
  }

  PolySelectToolView.prototype.initialize = function(options) {
    PolySelectToolView.__super__.initialize.call(this, options);
    this.listenTo(this.model, 'change:active', this._active_change);
    return this.data = null;
  };

  PolySelectToolView.prototype._active_change = function() {
    if (!this.mget('active')) {
      return this._clear_data();
    }
  };

  PolySelectToolView.prototype._keyup = function(e) {
    if (e.keyCode === 13) {
      return this._clear_data();
    }
  };

  PolySelectToolView.prototype._doubletap = function(e) {
    var append, ref;
    append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
    this._select(this.data.vx, this.data.vy, true, append);
    return this._clear_data();
  };

  PolySelectToolView.prototype._clear_data = function() {
    this.data = null;
    return this.mget('overlay').update({
      xs: [],
      ys: []
    });
  };

  PolySelectToolView.prototype._tap = function(e) {
    var canvas, new_data, overlay, vx, vy;
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (this.data == null) {
      this.data = {
        vx: [vx],
        vy: [vy]
      };
      return null;
    }
    this.data.vx.push(vx);
    this.data.vy.push(vy);
    overlay = this.mget('overlay');
    new_data = {};
    new_data.vx = _.clone(this.data.vx);
    new_data.vy = _.clone(this.data.vy);
    return overlay.update({
      xs: this.data.vx,
      ys: this.data.vy
    });
  };

  PolySelectToolView.prototype._select = function(vx, vy, final, append) {
    var ds, geometry, i, len, r, ref, sm;
    geometry = {
      type: 'poly',
      vx: vx,
      vy: vy
    };
    ref = this.mget('computed_renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      sm.select(this, this.plot_view.renderer_views[r.id], geometry, final, append);
    }
    this._save_geometry(geometry, final, append);
    this.plot_view.push_state('poly_select', {
      selection: this.plot_view.get_selection()
    });
    return null;
  };

  return PolySelectToolView;

})(SelectTool.View);

DEFAULT_POLY_OVERLAY = function() {
  return new PolyAnnotation.Model({
    level: "overlay",
    xs_units: "screen",
    ys_units: "screen",
    fill_color: "lightgrey",
    fill_alpha: 0.5,
    line_color: "black",
    line_alpha: 1.0,
    line_width: 2,
    line_dash: [4, 4]
  });
};

PolySelectTool = (function(superClass) {
  extend(PolySelectTool, superClass);

  function PolySelectTool() {
    return PolySelectTool.__super__.constructor.apply(this, arguments);
  }

  PolySelectTool.prototype.default_view = PolySelectToolView;

  PolySelectTool.prototype.type = "PolySelectTool";

  PolySelectTool.prototype.tool_name = "Poly Select";

  PolySelectTool.prototype.icon = "bk-tool-icon-polygon-select";

  PolySelectTool.prototype.event_type = "tap";

  PolySelectTool.prototype.default_order = 11;

  PolySelectTool.define({
    overlay: [p.Instance, DEFAULT_POLY_OVERLAY]
  });

  return PolySelectTool;

})(SelectTool.Model);

module.exports = {
  Model: PolySelectTool,
  View: PolySelectToolView
};

},{"../../../core/properties":"core/properties","../../annotations/poly_annotation":"models/annotations/poly_annotation","./select_tool":"models/tools/gestures/select_tool","underscore":"underscore"}],"models/tools/gestures/resize_tool":[function(require,module,exports){
var GestureTool, ResizeTool, ResizeToolView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

GestureTool = require("./gesture_tool");

p = require("../../../core/properties");

ResizeToolView = (function(superClass) {
  extend(ResizeToolView, superClass);

  function ResizeToolView() {
    return ResizeToolView.__super__.constructor.apply(this, arguments);
  }

  ResizeToolView.prototype.className = "bk-resize-popup";

  ResizeToolView.prototype.initialize = function(options) {
    var wrapper;
    ResizeToolView.__super__.initialize.call(this, options);
    wrapper = this.plot_view.$el.find('div.bk-canvas-wrapper');
    this.$el.appendTo(wrapper);
    this.$el.hide();
    this.active = false;
    return null;
  };

  ResizeToolView.prototype.activate = function() {
    this.active = true;
    this.render();
    return null;
  };

  ResizeToolView.prototype.deactivate = function() {
    this.active = false;
    this.render();
    return null;
  };

  ResizeToolView.prototype.render = function(ctx) {
    var canvas, frame, left, top;
    if (this.active) {
      canvas = this.plot_view.canvas;
      frame = this.plot_view.frame;
      left = canvas.vx_to_sx(frame.get('h_range').get('end') - 40);
      top = canvas.vy_to_sy(frame.get('v_range').get('start') + 40);
      this.$el.attr('style', "position:absolute; top:" + top + "px; left:" + left + "px;");
      this.$el.show();
    } else {
      this.$el.hide();
    }
    return this;
  };

  ResizeToolView.prototype._pan_start = function(e) {
    var canvas;
    canvas = this.plot_view.canvas;
    this.ch = canvas.get('height');
    this.cw = canvas.get('width');
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  ResizeToolView.prototype._pan = function(e) {
    this._update(e.deltaX, e.deltaY);
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  ResizeToolView.prototype._pan_end = function(e) {
    return this.plot_view.push_state("resize", {
      dimensions: {
        width: this.plot_view.canvas.get("width"),
        height: this.plot_view.canvas.get("height")
      }
    });
  };

  ResizeToolView.prototype._update = function(dx, dy) {
    var new_height, new_width;
    new_width = this.cw + dx;
    new_height = this.cw + dy;
    if (new_width < 100 || new_height < 100) {
      return;
    }
    this.plot_view.update_dimensions(new_width, new_height);
  };

  return ResizeToolView;

})(GestureTool.View);

ResizeTool = (function(superClass) {
  extend(ResizeTool, superClass);

  function ResizeTool() {
    return ResizeTool.__super__.constructor.apply(this, arguments);
  }

  ResizeTool.prototype.default_view = ResizeToolView;

  ResizeTool.prototype.type = "ResizeTool";

  ResizeTool.prototype.tool_name = "Resize";

  ResizeTool.prototype.icon = "bk-tool-icon-resize";

  ResizeTool.prototype.event_type = "pan";

  ResizeTool.prototype.default_order = 40;

  return ResizeTool;

})(GestureTool.Model);

module.exports = {
  Model: ResizeTool,
  View: ResizeToolView
};

},{"../../../core/properties":"core/properties","./gesture_tool":"models/tools/gestures/gesture_tool","underscore":"underscore"}],"models/tools/gestures/select_tool":[function(require,module,exports){
var GestureTool, GlyphRenderer, SelectTool, SelectToolView, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

GestureTool = require("./gesture_tool");

GlyphRenderer = require("../../renderers/glyph_renderer");

logger = require("../../../core/logging").logger;

p = require("../../../core/properties");

SelectToolView = (function(superClass) {
  extend(SelectToolView, superClass);

  function SelectToolView() {
    return SelectToolView.__super__.constructor.apply(this, arguments);
  }

  SelectToolView.prototype._keyup = function(e) {
    var ds, j, len, r, ref, results, sm;
    if (e.keyCode === 27) {
      ref = this.mget('computed_renderers');
      results = [];
      for (j = 0, len = ref.length; j < len; j++) {
        r = ref[j];
        ds = r.get('data_source');
        sm = ds.get('selection_manager');
        results.push(sm.clear());
      }
      return results;
    }
  };

  SelectToolView.prototype._save_geometry = function(geometry, final, append) {
    var g, geoms, i, j, ref, tool_events, xm, ym;
    g = _.clone(geometry);
    xm = this.plot_view.frame.get('x_mappers')['default'];
    ym = this.plot_view.frame.get('y_mappers')['default'];
    if (g.type === 'point') {
      g.x = xm.map_from_target(g.vx);
      g.y = ym.map_from_target(g.vy);
    } else if (g.type === 'rect') {
      g.x0 = xm.map_from_target(g.vx0);
      g.y0 = ym.map_from_target(g.vy0);
      g.x1 = xm.map_from_target(g.vx1);
      g.y1 = ym.map_from_target(g.vy1);
    } else if (g.type === 'poly') {
      g.x = new Array(g.vx.length);
      g.y = new Array(g.vy.length);
      for (i = j = 0, ref = g.vx.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        g.x[i] = xm.map_from_target(g.vx[i]);
        g.y[i] = ym.map_from_target(g.vy[i]);
      }
    } else {
      logger.debug("Unrecognized selection geometry type: '" + g.type + "'");
    }
    if (final) {
      tool_events = this.plot_model.plot.tool_events;
      if (append) {
        geoms = tool_events.get('geometries');
        geoms.push(g);
      } else {
        geoms = [g];
      }
      tool_events.set("geometries", geoms);
    }
    return null;
  };

  return SelectToolView;

})(GestureTool.View);

SelectTool = (function(superClass) {
  extend(SelectTool, superClass);

  function SelectTool() {
    return SelectTool.__super__.constructor.apply(this, arguments);
  }

  SelectTool.define({
    renderers: [p.Array, []],
    names: [p.Array, []]
  });

  SelectTool.internal({
    multi_select_modifier: [p.String, "shift"]
  });

  SelectTool.prototype.initialize = function(attrs, options) {
    SelectTool.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('computed_renderers', function() {
      var all_renderers, names, r, renderers;
      renderers = this.get('renderers');
      names = this.get('names');
      if (renderers.length === 0) {
        all_renderers = this.get('plot').get('renderers');
        renderers = (function() {
          var j, len, results;
          results = [];
          for (j = 0, len = all_renderers.length; j < len; j++) {
            r = all_renderers[j];
            if (r instanceof GlyphRenderer.Model) {
              results.push(r);
            }
          }
          return results;
        })();
      }
      if (names.length > 0) {
        renderers = (function() {
          var j, len, results;
          results = [];
          for (j = 0, len = renderers.length; j < len; j++) {
            r = renderers[j];
            if (names.indexOf(r.get('name')) >= 0) {
              results.push(r);
            }
          }
          return results;
        })();
      }
      return renderers;
    }, true);
    this.add_dependencies('computed_renderers', this, ['renderers', 'names', 'plot']);
    this.add_dependencies('computed_renderers', this.get('plot'), ['renderers']);
    return null;
  };

  return SelectTool;

})(GestureTool.Model);

module.exports = {
  Model: SelectTool,
  View: SelectToolView
};

},{"../../../core/logging":"core/logging","../../../core/properties":"core/properties","../../renderers/glyph_renderer":"models/renderers/glyph_renderer","./gesture_tool":"models/tools/gestures/gesture_tool","underscore":"underscore"}],"models/tools/gestures/tap_tool":[function(require,module,exports){
var SelectTool, TapTool, TapToolView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

SelectTool = require("./select_tool");

p = require("../../../core/properties");

TapToolView = (function(superClass) {
  extend(TapToolView, superClass);

  function TapToolView() {
    return TapToolView.__super__.constructor.apply(this, arguments);
  }

  TapToolView.prototype._tap = function(e) {
    var append, canvas, ref, vx, vy;
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    append = (ref = e.srcEvent.shiftKey) != null ? ref : false;
    return this._select(vx, vy, true, append);
  };

  TapToolView.prototype._select = function(vx, vy, final, append) {
    var callback, cb_data, did_hit, ds, geometry, i, len, r, ref, sm, view;
    geometry = {
      type: 'point',
      vx: vx,
      vy: vy
    };
    callback = this.mget("callback");
    this._save_geometry(geometry, final, append);
    cb_data = {
      geometries: this.plot_model.plot.tool_events.get('geometries')
    };
    ref = this.mget('computed_renderers');
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.get('data_source');
      sm = ds.get('selection_manager');
      view = this.plot_view.renderer_views[r.id];
      if (this.model.behavior === "select") {
        did_hit = sm.select(this, view, geometry, final, append);
      } else {
        did_hit = sm.inspect(this, view, geometry, {
          geometry: geometry
        });
      }
      if (did_hit && (callback != null)) {
        if (_.isFunction(callback)) {
          callback(ds, cb_data);
        } else {
          callback.execute(ds, cb_data);
        }
      }
    }
    if (this.model.behavior === "select") {
      this.plot_view.push_state('tap', {
        selection: this.plot_view.get_selection()
      });
    }
    return null;
  };

  return TapToolView;

})(SelectTool.View);

TapTool = (function(superClass) {
  extend(TapTool, superClass);

  function TapTool() {
    return TapTool.__super__.constructor.apply(this, arguments);
  }

  TapTool.prototype.default_view = TapToolView;

  TapTool.prototype.type = "TapTool";

  TapTool.prototype.tool_name = "Tap";

  TapTool.prototype.icon = "bk-tool-icon-tap-select";

  TapTool.prototype.event_type = "tap";

  TapTool.prototype.default_order = 10;

  TapTool.define({
    behavior: [p.String, "select"],
    callback: [p.Any]
  });

  return TapTool;

})(SelectTool.Model);

module.exports = {
  Model: TapTool,
  View: TapToolView
};

},{"../../../core/properties":"core/properties","./select_tool":"models/tools/gestures/select_tool","underscore":"underscore"}],"models/tools/gestures/wheel_zoom_tool":[function(require,module,exports){
var GestureTool, WheelZoomTool, WheelZoomToolView, _, document, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

GestureTool = require("./gesture_tool");

p = require("../../../core/properties");

if (typeof document === "undefined" || document === null) {
  document = {};
}

WheelZoomToolView = (function(superClass) {
  extend(WheelZoomToolView, superClass);

  function WheelZoomToolView() {
    return WheelZoomToolView.__super__.constructor.apply(this, arguments);
  }

  WheelZoomToolView.prototype._pinch = function(e) {
    var delta;
    if (e.scale >= 1) {
      delta = (e.scale - 1) * 20.0;
    } else {
      delta = -20.0 / e.scale;
    }
    e.bokeh.delta = delta;
    return this._scroll(e);
  };

  WheelZoomToolView.prototype._scroll = function(e) {
    var delta, dims, end, factor, frame, h_axis_only, hr, mapper, multiplier, name, ref, ref1, ref2, ref3, ref4, start, sx0, sx1, sy0, sy1, v_axis_only, vr, vx, vx_high, vx_low, vy, vy_high, vy_low, xrs, yrs, zoom_info;
    frame = this.plot_model.get('frame');
    hr = frame.get('h_range');
    vr = frame.get('v_range');
    vx = this.plot_view.canvas.sx_to_vx(e.bokeh.sx);
    vy = this.plot_view.canvas.sy_to_vy(e.bokeh.sy);
    if (vx < hr.get('start') || vx > hr.get('end')) {
      v_axis_only = true;
    }
    if (vy < vr.get('start') || vy > vr.get('end')) {
      h_axis_only = true;
    }
    if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
      multiplier = 20;
    } else {
      multiplier = 1;
    }
    if (((ref = e.originalEvent) != null ? ref.deltaY : void 0) != null) {
      delta = -e.originalEvent.deltaY * multiplier;
    } else {
      delta = e.bokeh.delta;
    }
    factor = this.mget('speed') * delta;
    if (factor > 0.9) {
      factor = 0.9;
    } else if (factor < -0.9) {
      factor = -0.9;
    }
    vx_low = hr.get('start');
    vx_high = hr.get('end');
    vy_low = vr.get('start');
    vy_high = vr.get('end');
    dims = this.mget('dimensions');
    if (dims.indexOf('width') > -1 && !v_axis_only) {
      sx0 = vx_low - (vx_low - vx) * factor;
      sx1 = vx_high - (vx_high - vx) * factor;
    } else {
      sx0 = vx_low;
      sx1 = vx_high;
    }
    if (dims.indexOf('height') > -1 && !h_axis_only) {
      sy0 = vy_low - (vy_low - vy) * factor;
      sy1 = vy_high - (vy_high - vy) * factor;
    } else {
      sy0 = vy_low;
      sy1 = vy_high;
    }
    xrs = {};
    ref1 = frame.get('x_mappers');
    for (name in ref1) {
      mapper = ref1[name];
      ref2 = mapper.v_map_from_target([sx0, sx1], true), start = ref2[0], end = ref2[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref3 = frame.get('y_mappers');
    for (name in ref3) {
      mapper = ref3[name];
      ref4 = mapper.v_map_from_target([sy0, sy1], true), start = ref4[0], end = ref4[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    zoom_info = {
      xrs: xrs,
      yrs: yrs,
      factor: factor
    };
    this.plot_view.push_state('wheel_zoom', {
      range: zoom_info
    });
    this.plot_view.update_range(zoom_info, false, true);
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  return WheelZoomToolView;

})(GestureTool.View);

WheelZoomTool = (function(superClass) {
  extend(WheelZoomTool, superClass);

  function WheelZoomTool() {
    return WheelZoomTool.__super__.constructor.apply(this, arguments);
  }

  WheelZoomTool.prototype.default_view = WheelZoomToolView;

  WheelZoomTool.prototype.type = "WheelZoomTool";

  WheelZoomTool.prototype.tool_name = "Wheel Zoom";

  WheelZoomTool.prototype.icon = "bk-tool-icon-wheel-zoom";

  WheelZoomTool.prototype.event_type = 'ontouchstart' in window || navigator.maxTouchPoints > 0 ? 'pinch' : 'scroll';

  WheelZoomTool.prototype.default_order = 10;

  WheelZoomTool.prototype.initialize = function(attrs, options) {
    WheelZoomTool.__super__.initialize.call(this, attrs, options);
    this.override_computed_property('tooltip', function() {
      return this._get_dim_tooltip(this.tool_name, this._check_dims(this.get('dimensions'), "wheel zoom tool"));
    }, false);
    return this.add_dependencies('tooltip', this, ['dimensions']);
  };

  WheelZoomTool.define({
    dimensions: [p.Array, ["width", "height"]]
  });

  WheelZoomTool.internal({
    speed: [p.Number, 1 / 600]
  });

  return WheelZoomTool;

})(GestureTool.Model);

module.exports = {
  Model: WheelZoomTool,
  View: WheelZoomToolView
};

},{"../../../core/properties":"core/properties","./gesture_tool":"models/tools/gestures/gesture_tool","underscore":"underscore"}],"models/tools/inspectors/crosshair_tool":[function(require,module,exports){
var CrosshairTool, CrosshairToolView, InspectTool, Span, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

InspectTool = require("./inspect_tool");

Span = require("../../annotations/span");

p = require("../../../core/properties");

CrosshairToolView = (function(superClass) {
  extend(CrosshairToolView, superClass);

  function CrosshairToolView() {
    return CrosshairToolView.__super__.constructor.apply(this, arguments);
  }

  CrosshairToolView.prototype._move = function(e) {
    var canvas, dim, frame, i, len, ref, results, span, vx, vy;
    if (!this.mget('active')) {
      return;
    }
    frame = this.plot_model.get('frame');
    canvas = this.plot_model.get('canvas');
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    ref = this.mget('dimensions');
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      dim = ref[i];
      span = this.mget('spans')[dim];
      if (!frame.contains(vx, vy)) {
        results.push(span.unset('computed_location'));
      } else {
        if (dim === "width") {
          results.push(span.set('computed_location', vy));
        } else {
          results.push(span.set('computed_location', vx));
        }
      }
    }
    return results;
  };

  CrosshairToolView.prototype._move_exit = function(e) {
    var dim, i, len, ref, results, span;
    ref = this.mget('dimensions');
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      dim = ref[i];
      span = this.mget('spans')[dim];
      results.push(span.unset('computed_location'));
    }
    return results;
  };

  return CrosshairToolView;

})(InspectTool.View);

CrosshairTool = (function(superClass) {
  extend(CrosshairTool, superClass);

  function CrosshairTool() {
    return CrosshairTool.__super__.constructor.apply(this, arguments);
  }

  CrosshairTool.prototype.default_view = CrosshairToolView;

  CrosshairTool.prototype.type = "CrosshairTool";

  CrosshairTool.prototype.tool_name = "Crosshair";

  CrosshairTool.define({
    dimensions: [p.Array, ["width", "height"]],
    line_color: [p.Color, 'black'],
    line_width: [p.Number, 1],
    line_alpha: [p.Number, 1.0]
  });

  CrosshairTool.internal({
    location_units: [p.SpatialUnits, "screen"],
    render_mode: [p.RenderMode, "css"],
    spans: [p.Any]
  });

  CrosshairTool.prototype.initialize = function(attrs, options) {
    CrosshairTool.__super__.initialize.call(this, attrs, options);
    this.override_computed_property('tooltip', function() {
      return this._get_dim_tooltip("Crosshair", this._check_dims(this.get('dimensions'), "crosshair tool"));
    }, false);
    this.add_dependencies('tooltip', this, ['dimensions']);
    this.spans = {
      width: new Span.Model({
        for_hover: true,
        dimension: "width",
        render_mode: this.get("render_mode"),
        location_units: this.get("location_units"),
        line_color: this.get("line_color"),
        line_width: this.get('line_width'),
        line_alpha: this.get('line_alpha')
      }),
      height: new Span.Model({
        for_hover: true,
        dimension: "height",
        render_mode: this.get("render_mode"),
        location_units: this.get("location_units"),
        line_color: this.get("line_color"),
        line_width: this.get('line_width'),
        line_alpha: this.get('line_alpha')
      })
    };
    return this.override_computed_property('synthetic_renderers', ((function(_this) {
      return function() {
        return _.values(_this.get("spans"));
      };
    })(this)), true);
  };

  return CrosshairTool;

})(InspectTool.Model);

module.exports = {
  Model: CrosshairTool,
  View: CrosshairToolView
};

},{"../../../core/properties":"core/properties","../../annotations/span":"models/annotations/span","./inspect_tool":"models/tools/inspectors/inspect_tool","underscore":"underscore"}],"models/tools/inspectors/hover_tool":[function(require,module,exports){
var $, GlyphRenderer, HoverTool, HoverToolView, InspectTool, Tooltip, Util, _, _color_to_hex, hittest, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

$ = require("jquery");

InspectTool = require("./inspect_tool");

Tooltip = require("../../annotations/tooltip");

GlyphRenderer = require("../../renderers/glyph_renderer");

hittest = require("../../../common/hittest");

logger = require("../../../core/logging").logger;

p = require("../../../core/properties");

Util = require("../../../util/util");

_color_to_hex = function(color) {
  var blue, digits, green, red, rgb;
  if (color.substr(0, 1) === '#') {
    return color;
  }
  digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);
  red = parseInt(digits[2]);
  green = parseInt(digits[3]);
  blue = parseInt(digits[4]);
  rgb = blue | (green << 8) | (red << 16);
  return digits[1] + '#' + rgb.toString(16);
};

HoverToolView = (function(superClass) {
  extend(HoverToolView, superClass);

  function HoverToolView() {
    return HoverToolView.__super__.constructor.apply(this, arguments);
  }

  HoverToolView.prototype.bind_bokeh_events = function() {
    var j, len, r, ref;
    ref = this.mget('computed_renderers');
    for (j = 0, len = ref.length; j < len; j++) {
      r = ref[j];
      this.listenTo(r.data_source, 'inspect', this._update);
    }
    return this.plot_view.canvas_view.$el.css('cursor', 'crosshair');
  };

  HoverToolView.prototype._clear = function() {
    var ref, results, rid, tt;
    this._inspect(Infinity, Infinity);
    ref = this.mget('ttmodels');
    results = [];
    for (rid in ref) {
      tt = ref[rid];
      results.push(tt.clear());
    }
    return results;
  };

  HoverToolView.prototype._move = function(e) {
    var canvas, vx, vy;
    if (!this.mget('active')) {
      return;
    }
    canvas = this.plot_view.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (!this.plot_view.frame.contains(vx, vy)) {
      return this._clear();
    } else {
      return this._inspect(vx, vy);
    }
  };

  HoverToolView.prototype._move_exit = function() {
    return this._clear();
  };

  HoverToolView.prototype._inspect = function(vx, vy, e) {
    var geometry, hovered_indexes, hovered_renderers, j, len, r, ref, sm;
    geometry = {
      type: 'point',
      vx: vx,
      vy: vy
    };
    if (this.model.mode === 'mouse') {
      geometry['type'] = 'point';
    } else {
      geometry['type'] = 'span';
      if (this.model.mode === 'vline') {
        geometry.direction = 'h';
      } else {
        geometry.direction = 'v';
      }
    }
    hovered_indexes = [];
    hovered_renderers = [];
    ref = this.mget('computed_renderers');
    for (j = 0, len = ref.length; j < len; j++) {
      r = ref[j];
      sm = r.data_source.get('selection_manager');
      sm.inspect(this, this.plot_view.renderer_views[r.id], geometry, {
        "geometry": geometry
      });
    }
    if (this.mget('callback') != null) {
      this._emit_callback(geometry);
    }
  };

  HoverToolView.prototype._update = function(indices, tool, renderer, ds, arg) {
    var canvas, d1x, d1y, d2x, d2y, data_x, data_y, dist1, dist2, frame, geometry, i, i1d, i2d, j, k, len, len1, pt, ref, ref1, ref10, ref11, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, rx, ry, sdatax, sdatay, sx, sy, tooltip, vars, vx, vy, x, xmapper, y, ymapper;
    geometry = arg.geometry;
    tooltip = (ref = this.mget('ttmodels')[renderer.model.id]) != null ? ref : null;
    if (tooltip == null) {
      return;
    }
    tooltip.clear();
    ref1 = [indices['1d'].indices, indices['2d'].indices], i1d = ref1[0], i2d = ref1[1];
    if (indices['0d'].glyph === null && i1d.length === 0 && i2d.length === 0) {
      return;
    }
    vx = geometry.vx;
    vy = geometry.vy;
    canvas = this.plot_model.get('canvas');
    frame = this.plot_model.get('frame');
    sx = canvas.vx_to_sx(vx);
    sy = canvas.vy_to_sy(vy);
    xmapper = frame.get('x_mappers')[renderer.mget('x_range_name')];
    ymapper = frame.get('y_mappers')[renderer.mget('y_range_name')];
    x = xmapper.map_from_target(vx);
    y = ymapper.map_from_target(vy);
    ref2 = indices['0d'].indices;
    for (j = 0, len = ref2.length; j < len; j++) {
      i = ref2[j];
      data_x = renderer.glyph._x[i + 1];
      data_y = renderer.glyph._y[i + 1];
      if (this.model.line_policy === "interp") {
        ref3 = renderer.glyph.get_interpolation_hit(i, geometry), data_x = ref3[0], data_y = ref3[1];
        rx = xmapper.map_to_target(data_x);
        ry = ymapper.map_to_target(data_y);
      } else if (this.model.line_policy === "prev") {
        rx = canvas.sx_to_vx(renderer.glyph.sx[i]);
        ry = canvas.sy_to_vy(renderer.glyph.sy[i]);
      } else if (this.model.line_policy === "next") {
        rx = canvas.sx_to_vx(renderer.glyph.sx[i + 1]);
        ry = canvas.sy_to_vy(renderer.glyph.sy[i + 1]);
      } else if (this.model.line_policy === "nearest") {
        d1x = renderer.glyph.sx[i];
        d1y = renderer.glyph.sy[i];
        dist1 = hittest.dist_2_pts(d1x, d1y, sx, sy);
        d2x = renderer.glyph.sx[i + 1];
        d2y = renderer.glyph.sy[i + 1];
        dist2 = hittest.dist_2_pts(d2x, d2y, sx, sy);
        if (dist1 < dist2) {
          ref4 = [d1x, d1y], sdatax = ref4[0], sdatay = ref4[1];
        } else {
          ref5 = [d2x, d2y], sdatax = ref5[0], sdatay = ref5[1];
          i = i + 1;
        }
        data_x = renderer.glyph._x[i];
        data_y = renderer.glyph._y[i];
        rx = canvas.sx_to_vx(sdatax);
        ry = canvas.sy_to_vy(sdatay);
      } else {
        ref6 = [vx, vy], rx = ref6[0], ry = ref6[1];
      }
      vars = {
        index: i,
        x: x,
        y: y,
        vx: vx,
        vy: vy,
        sx: sx,
        sy: sy,
        data_x: data_x,
        data_y: data_y,
        rx: rx,
        ry: ry
      };
      tooltip.add(rx, ry, this._render_tooltips(ds, i, vars));
    }
    ref7 = indices['1d'].indices;
    for (k = 0, len1 = ref7.length; k < len1; k++) {
      i = ref7[k];
      data_x = (ref8 = renderer.glyph._x) != null ? ref8[i] : void 0;
      data_y = (ref9 = renderer.glyph._y) != null ? ref9[i] : void 0;
      if (this.model.point_policy === 'snap_to_data') {
        pt = renderer.glyph.get_anchor_point(this.model.anchor, i, [sx, sy]);
        if (pt != null) {
          x = pt.x, y = pt.y;
        } else {
          ref10 = renderer.glyph.get_anchor_point("center", i, [sx, sy]), x = ref10.x, y = ref10.y;
        }
        rx = canvas.sx_to_vx(x);
        ry = canvas.sy_to_vy(y);
      } else {
        ref11 = [vx, vy], rx = ref11[0], ry = ref11[1];
      }
      vars = {
        index: i,
        x: x,
        y: y,
        vx: vx,
        vy: vy,
        sx: sx,
        sy: sy,
        data_x: data_x,
        data_y: data_y
      };
      tooltip.add(rx, ry, this._render_tooltips(ds, i, vars));
    }
    return null;
  };

  HoverToolView.prototype._emit_callback = function(geometry) {
    var callback, canvas, data, frame, indices, obj, r, ref, xmapper, ymapper;
    r = this.mget('computed_renderers')[0];
    indices = this.plot_view.renderer_views[r.id].hit_test(geometry);
    canvas = this.plot_model.canvas;
    frame = this.plot_model.frame;
    geometry['sx'] = canvas.vx_to_sx(geometry.vx);
    geometry['sy'] = canvas.vy_to_sy(geometry.vy);
    xmapper = frame.get('x_mappers')[r.get('x_range_name')];
    ymapper = frame.get('y_mappers')[r.get('y_range_name')];
    geometry['x'] = xmapper.map_from_target(geometry.vx);
    geometry['y'] = ymapper.map_from_target(geometry.vy);
    callback = this.model.callback;
    ref = [
      callback, {
        index: indices,
        geometry: geometry
      }
    ], obj = ref[0], data = ref[1];
    if (_.isFunction(callback)) {
      callback(obj, data);
    } else {
      callback.execute(obj, data);
    }
  };

  HoverToolView.prototype._render_tooltips = function(ds, i, vars) {
    var colname, color, column, hex, j, label, len, match, opts, ref, ref1, row, span, swatch, table, td, tooltips, value;
    tooltips = this.mget("tooltips");
    if (_.isString(tooltips)) {
      return $('<div>').html(Util.replace_placeholders(tooltips, ds, i, vars));
    } else if (_.isFunction(tooltips)) {
      return tooltips(ds, vars);
    } else {
      table = $('<table></table>');
      for (j = 0, len = tooltips.length; j < len; j++) {
        ref = tooltips[j], label = ref[0], value = ref[1];
        row = $("<tr></tr>");
        row.append($("<td class='bk-tooltip-row-label'>").text(label + ": "));
        td = $("<td class='bk-tooltip-row-value'></td>");
        if (value.indexOf("$color") >= 0) {
          ref1 = value.match(/\$color(\[.*\])?:(\w*)/), match = ref1[0], opts = ref1[1], colname = ref1[2];
          column = ds.get_column(colname);
          if (column == null) {
            span = $("<span>").text(colname + " unknown");
            td.append(span);
            continue;
          }
          hex = (opts != null ? opts.indexOf("hex") : void 0) >= 0;
          swatch = (opts != null ? opts.indexOf("swatch") : void 0) >= 0;
          color = column[i];
          if (color == null) {
            span = $("<span>(null)</span>");
            td.append(span);
            continue;
          }
          if (hex) {
            color = _color_to_hex(color);
          }
          span = $("<span>").text(color);
          td.append(span);
          if (swatch) {
            span = $("<span class='bk-tooltip-color-block'> </span>");
            span.css({
              backgroundColor: color
            });
          }
          td.append(span);
        } else {
          value = value.replace("$~", "$data_");
          value = Util.replace_placeholders(value, ds, i, vars);
          td.append($('<span>').html(value));
        }
        row.append(td);
        table.append(row);
      }
      return table;
    }
  };

  return HoverToolView;

})(InspectTool.View);

HoverTool = (function(superClass) {
  extend(HoverTool, superClass);

  function HoverTool() {
    return HoverTool.__super__.constructor.apply(this, arguments);
  }

  HoverTool.prototype.default_view = HoverToolView;

  HoverTool.prototype.type = "HoverTool";

  HoverTool.prototype.tool_name = "Hover Tool";

  HoverTool.prototype.icon = "bk-tool-icon-hover";

  HoverTool.define({
    tooltips: [p.Any, [["index", "$index"], ["data (x, y)", "($x, $y)"], ["canvas (x, y)", "($sx, $sy)"]]],
    renderers: [p.Array, []],
    names: [p.Array, []],
    mode: [p.String, 'mouse'],
    point_policy: [p.String, 'snap_to_data'],
    line_policy: [p.String, 'prev'],
    anchor: [p.String, 'center'],
    attachment: [p.String, 'horizontal'],
    callback: [p.Any]
  });

  HoverTool.prototype.initialize = function(attrs, options) {
    HoverTool.__super__.initialize.call(this, attrs, options);
    this.define_computed_property('computed_renderers', function() {
      var all_renderers, names, r, renderers;
      renderers = this.get('renderers');
      names = this.get('names');
      if (renderers.length === 0) {
        all_renderers = this.get('plot').get('renderers');
        renderers = (function() {
          var j, len, results;
          results = [];
          for (j = 0, len = all_renderers.length; j < len; j++) {
            r = all_renderers[j];
            if (r instanceof GlyphRenderer.Model) {
              results.push(r);
            }
          }
          return results;
        })();
      }
      if (names.length > 0) {
        renderers = (function() {
          var j, len, results;
          results = [];
          for (j = 0, len = renderers.length; j < len; j++) {
            r = renderers[j];
            if (names.indexOf(r.get('name')) >= 0) {
              results.push(r);
            }
          }
          return results;
        })();
      }
      return renderers;
    }, true);
    this.add_dependencies('computed_renderers', this, ['renderers', 'names', 'plot']);
    this.add_dependencies('computed_renderers', this.get('plot'), ['renderers']);
    this.define_computed_property('ttmodels', function() {
      var j, len, r, ref, tooltip, tooltips, ttmodels;
      ttmodels = {};
      tooltips = this.get("tooltips");
      if (tooltips != null) {
        ref = this.get('computed_renderers');
        for (j = 0, len = ref.length; j < len; j++) {
          r = ref[j];
          tooltip = new Tooltip.Model({
            custom: _.isString(tooltips) || _.isFunction(tooltips),
            attachment: this.attachment
          });
          ttmodels[r.id] = tooltip;
        }
      }
      return ttmodels;
    }, true);
    this.add_dependencies('ttmodels', this, ['computed_renderers', 'tooltips']);
    this.override_computed_property('synthetic_renderers', (function() {
      return _.values(this.get("ttmodels"));
    }), true);
    return this.add_dependencies('synthetic_renderers', this, ['ttmodels']);
  };

  return HoverTool;

})(InspectTool.Model);

module.exports = {
  Model: HoverTool,
  View: HoverToolView
};

},{"../../../common/hittest":"common/hittest","../../../core/logging":"core/logging","../../../core/properties":"core/properties","../../../util/util":"util/util","../../annotations/tooltip":"models/annotations/tooltip","../../renderers/glyph_renderer":"models/renderers/glyph_renderer","./inspect_tool":"models/tools/inspectors/inspect_tool","jquery":"jquery","underscore":"underscore"}],"models/tools/inspectors/inspect_tool":[function(require,module,exports){
var Backbone, InspectTool, InspectToolListItemView, InspectToolView, Tool, _, inspect_tool_list_item_template,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Backbone = require("backbone");

Tool = require("../tool");

inspect_tool_list_item_template = require("./inspect_tool_list_item_template");

InspectToolListItemView = (function(superClass) {
  extend(InspectToolListItemView, superClass);

  function InspectToolListItemView() {
    return InspectToolListItemView.__super__.constructor.apply(this, arguments);
  }

  InspectToolListItemView.prototype.className = "bk-toolbar-inspector";

  InspectToolListItemView.prototype.template = inspect_tool_list_item_template;

  InspectToolListItemView.prototype.events = {
    'click [type="checkbox"]': '_clicked'
  };

  InspectToolListItemView.prototype.initialize = function(options) {
    this.listenTo(this.model, 'change:active', this.render);
    return this.render();
  };

  InspectToolListItemView.prototype.render = function() {
    this.$el.html(this.template({
      model: this.model
    }));
    return this;
  };

  InspectToolListItemView.prototype._clicked = function(e) {
    var active;
    active = this.model.get('active');
    return this.model.set('active', !active);
  };

  return InspectToolListItemView;

})(Backbone.View);

InspectToolView = (function(superClass) {
  extend(InspectToolView, superClass);

  function InspectToolView() {
    return InspectToolView.__super__.constructor.apply(this, arguments);
  }

  return InspectToolView;

})(Tool.View);

InspectTool = (function(superClass) {
  extend(InspectTool, superClass);

  function InspectTool() {
    return InspectTool.__super__.constructor.apply(this, arguments);
  }

  InspectTool.prototype.event_type = "move";

  InspectTool.override({
    active: true
  });

  InspectTool.prototype.bind_bokeh_events = function() {
    InspectTool.__super__.bind_bokeh_events.call(this);
    return this.listenTo(events, 'move', this._inspect);
  };

  InspectTool.prototype._inspect = function(vx, vy, e) {};

  InspectTool.prototype._exit_inner = function() {};

  InspectTool.prototype._exit_outer = function() {};

  return InspectTool;

})(Tool.Model);

module.exports = {
  Model: InspectTool,
  View: InspectToolView,
  ListItemView: InspectToolListItemView
};

},{"../tool":"models/tools/tool","./inspect_tool_list_item_template":"models/tools/inspectors/inspect_tool_list_item_template","backbone":"backbone","underscore":"underscore"}],"models/tools/inspectors/inspect_tool_list_item_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [];
  var __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  };
  var __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  };
  var __safe = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else {
      if (!(typeof value !== 'undefined' && value != null)) value = '';
      var result = new String(value);
      result.ecoSafe = true;
      return result;
    }
  };
  var __escape = function(value) {
    return ('' + value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  };
  (function() {
    (function() {
      __out.push('<input type="checkbox" ');
    
      if (this.model.active) {
        __out.push('checked');
      }
    
      __out.push('>');
    
      __out.push(__sanitize(this.model.tool_name));
    
      __out.push('</input>\n');
    
    }).call(this);
    
  }).call(__obj);
  return __out.join('');
};
},{}],"models/tools/tool":[function(require,module,exports){
var Model, Renderer, Tool, ToolView, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Renderer = require("../renderers/renderer");

logger = require("../../core/logging").logger;

p = require("../../core/properties");

Model = require("../../model");

ToolView = (function(superClass) {
  extend(ToolView, superClass);

  function ToolView() {
    return ToolView.__super__.constructor.apply(this, arguments);
  }

  ToolView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change:active', (function(_this) {
      return function() {
        if (_this.mget('active')) {
          return _this.activate();
        } else {
          return _this.deactivate();
        }
      };
    })(this));
  };

  ToolView.prototype.activate = function() {};

  ToolView.prototype.deactivate = function() {};

  return ToolView;

})(Renderer.View);

Tool = (function(superClass) {
  extend(Tool, superClass);

  function Tool() {
    return Tool.__super__.constructor.apply(this, arguments);
  }

  Tool.prototype.initialize = function(attrs, options) {
    Tool.__super__.initialize.call(this, attrs, options);
    return this.define_computed_property('synthetic_renderers', (function() {
      return [];
    }), true);
  };

  Tool.define({
    plot: [p.Instance]
  });

  Tool.internal({
    level: [p.RenderLevel, 'overlay'],
    active: [p.Boolean, false]
  });

  Tool.prototype._check_dims = function(dims, tool_name) {
    var hdim, ref, wdim;
    ref = [false, false], wdim = ref[0], hdim = ref[1];
    if (dims.length === 0) {
      logger.warn(tool_name + " given empty dimensions");
    } else if (dims.length === 1) {
      if (dims[0] !== 'width' && dims[0] !== 'height') {
        logger.warn(tool_name + " given unrecognized dimensions: " + dims);
      }
    } else if (dims.length === 2) {
      if (dims.indexOf('width') < 0 || dims.indexOf('height') < 0) {
        logger.warn(tool_name + " given unrecognized dimensions: " + dims);
      }
    } else {
      logger.warn(tool_name + " given more than two dimensions: " + dims);
    }
    if (dims.indexOf('width') >= 0) {
      wdim = true;
    }
    if (dims.indexOf('height') >= 0) {
      hdim = true;
    }
    return [wdim, hdim];
  };

  Tool.prototype._get_dim_tooltip = function(name, arg) {
    var hdim, wdim;
    wdim = arg[0], hdim = arg[1];
    if (wdim && !hdim) {
      return name + " (x-axis)";
    } else if (hdim && !wdim) {
      return name + " (y-axis)";
    } else {
      return name;
    }
  };

  Tool.prototype._get_dim_limits = function(arg, arg1, frame, dims) {
    var hr, vr, vx0, vx1, vxlim, vy0, vy1, vylim;
    vx0 = arg[0], vy0 = arg[1];
    vx1 = arg1[0], vy1 = arg1[1];
    hr = frame.get('h_range');
    if (dims.indexOf('width') >= 0) {
      vxlim = [_.min([vx0, vx1]), _.max([vx0, vx1])];
      vxlim = [_.max([vxlim[0], hr.get('min')]), _.min([vxlim[1], hr.get('max')])];
    } else {
      vxlim = [hr.get('min'), hr.get('max')];
    }
    vr = frame.get('v_range');
    if (dims.indexOf('height') >= 0) {
      vylim = [_.min([vy0, vy1]), _.max([vy0, vy1])];
      vylim = [_.max([vylim[0], vr.get('min')]), _.min([vylim[1], vr.get('max')])];
    } else {
      vylim = [vr.get('min'), vr.get('max')];
    }
    return [vxlim, vylim];
  };

  return Tool;

})(Model);

module.exports = {
  Model: Tool,
  View: ToolView
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../../model":"model","../renderers/renderer":"models/renderers/renderer","underscore":"underscore"}],"models/tools/tool_proxy":[function(require,module,exports){
var Model, ToolProxy, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

p = require("../../core/properties");

Model = require("../../model");

ToolProxy = (function(superClass) {
  extend(ToolProxy, superClass);

  function ToolProxy() {
    return ToolProxy.__super__.constructor.apply(this, arguments);
  }

  ToolProxy.prototype.initialize = function(options) {
    ToolProxy.__super__.initialize.call(this, options);
    this.listenTo(this, 'do', this["do"]);
    return this.listenTo(this, 'change:active', this.set_active);
  };

  ToolProxy.prototype["do"] = function() {
    var i, len, ref, tool;
    ref = this.tools;
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      tool.trigger('do');
    }
    return null;
  };

  ToolProxy.prototype.set_active = function() {
    var i, len, ref, tool;
    ref = this.tools;
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      tool.active = this.active;
    }
    return null;
  };

  ToolProxy.define({
    tools: [p.Array, []],
    active: [p.Bool, false],
    tooltip: [p.String],
    tool_name: [p.String],
    disabled: [p.Bool, false],
    event_type: [p.String],
    icon: [p.String]
  });

  ToolProxy.prototype._clicked = function() {
    var active;
    active = this.model.get('active');
    return this.model.set('active', !active);
  };

  return ToolProxy;

})(Model);

module.exports = {
  ToolProxy: ToolProxy
};

},{"../../core/properties":"core/properties","../../model":"model"}],"models/tools/toolbar":[function(require,module,exports){
var ActionTool, GestureTool, HelpTool, InspectTool, Toolbar, ToolbarBase, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

p = require("../../core/properties");

ActionTool = require("./actions/action_tool");

HelpTool = require("./actions/help_tool");

GestureTool = require("./gestures/gesture_tool");

InspectTool = require("./inspectors/inspect_tool");

ToolbarBase = require("./toolbar_base");

Toolbar = (function(superClass) {
  extend(Toolbar, superClass);

  function Toolbar() {
    return Toolbar.__super__.constructor.apply(this, arguments);
  }

  Toolbar.prototype.type = 'Toolbar';

  Toolbar.prototype.default_view = ToolbarBase.View;

  Toolbar.prototype.initialize = function(attrs, options) {
    Toolbar.__super__.initialize.call(this, attrs, options);
    this.listenTo(this, 'change:tools', this._init_tools);
    return this._init_tools();
  };

  Toolbar.prototype._init_tools = function() {
    var et, i, len, ref, results, tool, tools;
    ref = this.get('tools');
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      if (tool instanceof InspectTool.Model) {
        if (!_.some(this.inspectors, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          this.inspectors = this.inspectors.concat([tool]);
        }
      } else if (tool instanceof HelpTool.Model) {
        if (!_.some(this.help, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          this.help = this.help.concat([tool]);
        }
      } else if (tool instanceof ActionTool.Model) {
        if (!_.some(this.actions, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          this.actions = this.actions.concat([tool]);
        }
      } else if (tool instanceof GestureTool.Model) {
        et = tool.event_type;
        if (!(et in this.gestures)) {
          logger.warn("Toolbar: unknown event type '" + et + "' for tool: " + tool.type + " (" + tool.id + ")");
          continue;
        }
        if (!_.some(this.gestures[et].tools, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          this.gestures[et].tools = this.gestures[et].tools.concat([tool]);
        }
        this.listenTo(tool, 'change:active', _.bind(this._active_change, tool));
      }
    }
    results = [];
    for (et in this.gestures) {
      tools = this.gestures[et].tools;
      if (tools.length === 0) {
        continue;
      }
      this.gestures[et].tools = _.sortBy(tools, function(tool) {
        return tool.default_order;
      });
      if (et === 'tap') {
        if (this.active_tap === null) {
          continue;
        }
        if (this.active_tap === 'auto') {
          this.gestures[et].tools[0].active = true;
        } else {
          this.active_tap.active = true;
        }
      }
      if (et === 'pan') {
        if (this.active_drag === null) {
          continue;
        }
        if (this.active_drag === 'auto') {
          this.gestures[et].tools[0].active = true;
        } else {
          this.active_drag.active = true;
        }
      }
      if (et === 'pinch' || et === 'scroll') {
        if (this.active_scroll === null || this.active_scroll === 'auto') {
          continue;
        }
        results.push(this.active_scroll.active = true);
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  Toolbar.define({
    active_drag: [p.Any, 'auto'],
    active_scroll: [p.Any, 'auto'],
    active_tap: [p.Any, 'auto']
  });

  return Toolbar;

})(ToolbarBase.Model);

module.exports = {
  Model: Toolbar
};

},{"../../core/properties":"core/properties","./actions/action_tool":"models/tools/actions/action_tool","./actions/help_tool":"models/tools/actions/help_tool","./gestures/gesture_tool":"models/tools/gestures/gesture_tool","./inspectors/inspect_tool":"models/tools/inspectors/inspect_tool","./toolbar_base":"models/tools/toolbar_base","underscore":"underscore"}],"models/tools/toolbar_base":[function(require,module,exports){
var $, $$1, ActionTool, EQ, GestureTool, HelpTool, InspectTool, LayoutDOM, ToolbarBase, ToolbarBaseView, Variable, _, logger, p, ref, toolbar_template,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

_ = require("underscore");

$ = require("jquery");

$$1 = require("bootstrap/dropdown");

logger = require("../../core/logging").logger;

ref = require("../../core/layout/solver"), EQ = ref.EQ, Variable = ref.Variable;

p = require("../../core/properties");

LayoutDOM = require("../layouts/layout_dom");

ActionTool = require("./actions/action_tool");

HelpTool = require("./actions/help_tool");

GestureTool = require("./gestures/gesture_tool");

InspectTool = require("./inspectors/inspect_tool");

toolbar_template = require("./toolbar_template");

ToolbarBaseView = (function(superClass) {
  extend(ToolbarBaseView, superClass);

  function ToolbarBaseView() {
    return ToolbarBaseView.__super__.constructor.apply(this, arguments);
  }

  ToolbarBaseView.prototype.className = "bk-toolbar-wrapper";

  ToolbarBaseView.prototype.template = toolbar_template;

  ToolbarBaseView.prototype.render = function() {
    var anchor, button_bar_list, et, gestures, inspectors, location, sticky, ul;
    if (this.model.sizing_mode !== 'fixed') {
      this.$el.css({
        left: this.model._dom_left._value,
        top: this.model._dom_top._value,
        'width': this.model._width._value,
        'height': this.model._height._value
      });
    }
    location = this.model.toolbar_location != null ? this.model.toolbar_location : 'above';
    sticky = this.model.toolbar_sticky === true ? 'sticky' : 'not-sticky';
    this.$el.html(this.template({
      logo: this.mget("logo"),
      location: location,
      sticky: sticky
    }));
    inspectors = this.model.get('inspectors');
    button_bar_list = this.$(".bk-bs-dropdown[type='inspectors']");
    if (inspectors.length === 0) {
      button_bar_list.hide();
    } else {
      anchor = $('<a href="#" data-bk-bs-toggle="dropdown" class="bk-bs-dropdown-toggle">inspect <span class="bk-bs-caret"></a>');
      anchor.appendTo(button_bar_list);
      ul = $('<ul class="bk-bs-dropdown-menu" />');
      _.each(inspectors, function(tool) {
        var item;
        item = $('<li />');
        item.append(new InspectTool.ListItemView({
          model: tool
        }).el);
        return item.appendTo(ul);
      });
      ul.on('click', function(e) {
        return e.stopPropagation();
      });
      ul.appendTo(button_bar_list);
      anchor.dropdown();
    }
    button_bar_list = this.$(".bk-button-bar-list[type='help']");
    _.each(this.model.get('help'), function(item) {
      return button_bar_list.append(new ActionTool.ButtonView({
        model: item
      }).el);
    });
    button_bar_list = this.$(".bk-button-bar-list[type='actions']");
    _.each(this.model.get('actions'), function(item) {
      return button_bar_list.append(new ActionTool.ButtonView({
        model: item
      }).el);
    });
    gestures = this.model.get('gestures');
    for (et in gestures) {
      button_bar_list = this.$(".bk-button-bar-list[type='" + et + "']");
      _.each(gestures[et].tools, function(item) {
        return button_bar_list.append(new GestureTool.ButtonView({
          model: item
        }).el);
      });
    }
    return this;
  };

  return ToolbarBaseView;

})(LayoutDOM.View);

ToolbarBase = (function(superClass) {
  extend(ToolbarBase, superClass);

  function ToolbarBase() {
    this._active_change = bind(this._active_change, this);
    return ToolbarBase.__super__.constructor.apply(this, arguments);
  }

  ToolbarBase.prototype.type = 'ToolbarBase';

  ToolbarBase.prototype.default_view = ToolbarBaseView;

  ToolbarBase.prototype._active_change = function(tool) {
    var currently_active_tool, event_type, gestures;
    event_type = tool.event_type;
    gestures = this.get('gestures');
    currently_active_tool = gestures[event_type].active;
    if ((currently_active_tool != null) && currently_active_tool !== tool) {
      logger.debug("Toolbar: deactivating tool: " + currently_active_tool.type + " (" + currently_active_tool.id + ") for event type '" + event_type + "'");
      currently_active_tool.set('active', false);
    }
    gestures[event_type].active = tool;
    this.set('gestures', gestures);
    logger.debug("Toolbar: activating tool: " + tool.type + " (" + tool.id + ") for event type '" + event_type + "'");
    return null;
  };

  ToolbarBase.prototype.get_constraints = function() {
    var constraints;
    constraints = ToolbarBase.__super__.get_constraints.call(this);
    constraints.push(EQ(this._sizeable, -30));
    return constraints;
  };

  ToolbarBase.define({
    tools: [p.Array, []],
    logo: [p.String, 'normal']
  });

  ToolbarBase.internal({
    gestures: [
      p.Any, function() {
        return {
          pan: {
            tools: [],
            active: null
          },
          tap: {
            tools: [],
            active: null
          },
          doubletap: {
            tools: [],
            active: null
          },
          scroll: {
            tools: [],
            active: null
          },
          pinch: {
            tools: [],
            active: null
          },
          press: {
            tools: [],
            active: null
          },
          rotate: {
            tools: [],
            active: null
          }
        };
      }
    ],
    actions: [p.Array, []],
    inspectors: [p.Array, []],
    help: [p.Array, []],
    toolbar_location: [p.Location, 'right'],
    toolbar_sticky: [p.Bool]
  });

  ToolbarBase.override({
    sizing_mode: null
  });

  return ToolbarBase;

})(LayoutDOM.Model);

module.exports = {
  Model: ToolbarBase,
  View: ToolbarBaseView
};

},{"../../core/layout/solver":"core/layout/solver","../../core/logging":"core/logging","../../core/properties":"core/properties","../layouts/layout_dom":"models/layouts/layout_dom","./actions/action_tool":"models/tools/actions/action_tool","./actions/help_tool":"models/tools/actions/help_tool","./gestures/gesture_tool":"models/tools/gestures/gesture_tool","./inspectors/inspect_tool":"models/tools/inspectors/inspect_tool","./toolbar_template":"models/tools/toolbar_template","bootstrap/dropdown":"bootstrap/dropdown","jquery":"jquery","underscore":"underscore"}],"models/tools/toolbar_box":[function(require,module,exports){
var ActionTool, Box, GestureTool, HelpTool, InspectTool, ToolProxy, ToolbarBase, ToolbarBox, ToolbarBoxToolbar, ToolbarBoxView, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

p = require("../../core/properties");

ActionTool = require("./actions/action_tool");

HelpTool = require("./actions/help_tool");

GestureTool = require("./gestures/gesture_tool");

InspectTool = require("./inspectors/inspect_tool");

ToolbarBase = require("./toolbar_base");

ToolProxy = require("./tool_proxy").ToolProxy;

Box = require("../layouts/box");

ToolbarBoxToolbar = (function(superClass) {
  extend(ToolbarBoxToolbar, superClass);

  function ToolbarBoxToolbar() {
    return ToolbarBoxToolbar.__super__.constructor.apply(this, arguments);
  }

  ToolbarBoxToolbar.prototype.type = 'ToolbarBoxToolbar';

  ToolbarBoxToolbar.prototype.default_view = ToolbarBase.View;

  ToolbarBoxToolbar.prototype.initialize = function(options) {
    ToolbarBoxToolbar.__super__.initialize.call(this, options);
    this._init_tools();
    if (this.merge_tools === true) {
      return this._merge_tools();
    }
  };

  ToolbarBoxToolbar.define({
    merge_tools: [p.Bool, true]
  });

  ToolbarBoxToolbar.prototype._init_tools = function() {
    var et, i, len, ref, results, tool;
    ref = this.get('tools');
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      tool = ref[i];
      if (tool instanceof InspectTool.Model) {
        if (!_.some(this.inspectors, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          results.push(this.inspectors = this.inspectors.concat([tool]));
        } else {
          results.push(void 0);
        }
      } else if (tool instanceof HelpTool.Model) {
        if (!_.some(this.help, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          results.push(this.help = this.help.concat([tool]));
        } else {
          results.push(void 0);
        }
      } else if (tool instanceof ActionTool.Model) {
        if (!_.some(this.actions, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          results.push(this.actions = this.actions.concat([tool]));
        } else {
          results.push(void 0);
        }
      } else if (tool instanceof GestureTool.Model) {
        et = tool.event_type;
        if (!_.some(this.gestures[et].tools, (function(_this) {
          return function(t) {
            return t.id === tool.id;
          };
        })(this))) {
          results.push(this.gestures[et].tools = this.gestures[et].tools.concat([tool]));
        } else {
          results.push(void 0);
        }
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  ToolbarBoxToolbar.prototype._merge_tools = function() {
    var actions, active, et, event_type, gestures, helptool, i, info, inspectors, j, k, l, len, len1, len2, len3, make_proxy, new_help_tools, new_help_urls, proxy, ref, ref1, ref2, ref3, ref4, ref5, results, tool, tool_type, tools;
    inspectors = {};
    actions = {};
    gestures = {};
    new_help_tools = [];
    new_help_urls = [];
    ref = this.help;
    for (i = 0, len = ref.length; i < len; i++) {
      helptool = ref[i];
      if (!_.contains(new_help_urls, helptool.redirect)) {
        new_help_tools.push(helptool);
        new_help_urls.push(helptool.redirect);
      }
    }
    this.help = new_help_tools;
    ref1 = this.gestures;
    for (event_type in ref1) {
      info = ref1[event_type];
      if (!(event_type in gestures)) {
        gestures[event_type] = {};
      }
      ref2 = info.tools;
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        tool = ref2[j];
        if (!(tool.type in gestures[event_type])) {
          gestures[event_type][tool.type] = [];
        }
        gestures[event_type][tool.type].push(tool);
      }
    }
    ref3 = this.inspectors;
    for (k = 0, len2 = ref3.length; k < len2; k++) {
      tool = ref3[k];
      if (!(tool.type in inspectors)) {
        inspectors[tool.type] = [];
      }
      inspectors[tool.type].push(tool);
    }
    ref4 = this.actions;
    for (l = 0, len3 = ref4.length; l < len3; l++) {
      tool = ref4[l];
      if (!(tool.type in actions)) {
        actions[tool.type] = [];
      }
      actions[tool.type].push(tool);
    }
    make_proxy = function(tools, active) {
      if (active == null) {
        active = false;
      }
      return new ToolProxy({
        tools: tools,
        event_type: tools[0].event_type,
        tooltip: tools[0].tool_name,
        tool_name: tools[0].tool_name,
        icon: tools[0].icon,
        active: active
      });
    };
    for (event_type in gestures) {
      this.gestures[event_type].tools = [];
      ref5 = gestures[event_type];
      for (tool_type in ref5) {
        tools = ref5[tool_type];
        if (tools.length > 0) {
          proxy = make_proxy(tools);
          this.gestures[event_type].tools.push(proxy);
          this.listenTo(proxy, 'change:active', _.bind(this._active_change, proxy));
        }
      }
    }
    this.actions = [];
    for (tool_type in actions) {
      tools = actions[tool_type];
      if (tools.length > 0) {
        this.actions.push(make_proxy(tools));
      }
    }
    this.inspectors = [];
    for (tool_type in inspectors) {
      tools = inspectors[tool_type];
      if (tools.length > 0) {
        this.inspectors.push(make_proxy(tools, active = true));
      }
    }
    results = [];
    for (et in this.gestures) {
      tools = this.gestures[et].tools;
      if (tools.length === 0) {
        continue;
      }
      this.gestures[et].tools = _.sortBy(tools, function(tool) {
        return tool.default_order;
      });
      if (et !== 'pinch' && et !== 'scroll') {
        results.push(this.gestures[et].tools[0].set('active', true));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return ToolbarBoxToolbar;

})(ToolbarBase.Model);

ToolbarBoxView = (function(superClass) {
  extend(ToolbarBoxView, superClass);

  function ToolbarBoxView() {
    return ToolbarBoxView.__super__.constructor.apply(this, arguments);
  }

  ToolbarBoxView.prototype.className = 'bk-toolbar-box';

  ToolbarBoxView.prototype.get_width = function() {
    if (this.model._horizontal === true) {
      return 30;
    } else {
      return null;
    }
  };

  ToolbarBoxView.prototype.get_height = function() {
    return 30;
  };

  return ToolbarBoxView;

})(Box.View);

ToolbarBox = (function(superClass) {
  extend(ToolbarBox, superClass);

  function ToolbarBox() {
    return ToolbarBox.__super__.constructor.apply(this, arguments);
  }

  ToolbarBox.prototype.type = 'ToolbarBox';

  ToolbarBox.prototype.default_view = ToolbarBoxView;

  ToolbarBox.prototype.initialize = function(options) {
    var ref;
    ToolbarBox.__super__.initialize.call(this, options);
    this._toolbar = new ToolbarBoxToolbar(options);
    if ((ref = this.toolbar_location) === 'left' || ref === 'right') {
      this._horizontal = true;
      return this._toolbar._sizeable = this._toolbar._width;
    } else {
      this._horizontal = false;
      return this._toolbar._sizeable = this._toolbar._height;
    }
  };

  ToolbarBox.prototype._doc_attached = function() {
    return this._toolbar.attach_document(this.document);
  };

  ToolbarBox.prototype.get_layoutable_children = function() {
    return [this._toolbar];
  };

  ToolbarBox.define({
    toolbar_location: [p.Location, "right"],
    merge_tools: [p.Bool, true],
    tools: [p.Any, []],
    logo: [p.String, "normal"]
  });

  return ToolbarBox;

})(Box.Model);

module.exports = {
  Model: ToolbarBox,
  View: ToolbarBoxView
};

},{"../../core/properties":"core/properties","../layouts/box":"models/layouts/box","./actions/action_tool":"models/tools/actions/action_tool","./actions/help_tool":"models/tools/actions/help_tool","./gestures/gesture_tool":"models/tools/gestures/gesture_tool","./inspectors/inspect_tool":"models/tools/inspectors/inspect_tool","./tool_proxy":"models/tools/tool_proxy","./toolbar_base":"models/tools/toolbar_base","underscore":"underscore"}],"models/tools/toolbar_template":[function(require,module,exports){
module.exports = function(__obj) {
  if (!__obj) __obj = {};
  var __out = [];
  var __capture = function(callback) {
    var out = __out, result;
    __out = [];
    callback.call(this);
    result = __out.join('');
    __out = out;
    return __safe(result);
  };
  var __sanitize = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else if (typeof value !== 'undefined' && value != null) {
      return __escape(value);
    } else {
      return '';
    }
  };
  var __safe = function(value) {
    if (value && value.ecoSafe) {
      return value;
    } else {
      if (!(typeof value !== 'undefined' && value != null)) value = '';
      var result = new String(value);
      result.ecoSafe = true;
      return result;
    }
  };
  var __escape = function(value) {
    return ('' + value)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  };
  (function() {
    (function() {
      __out.push('<div class="bk-toolbar-');
    
      __out.push(__sanitize(this.location));
    
      __out.push(' bk-plot-');
    
      __out.push(__sanitize(this.location));
    
      __out.push(' bk-toolbar-');
    
      __out.push(__sanitize(this.sticky));
    
      __out.push(' bk-toolbar-active">\n  ');
    
      if ((this.logo != null) && this.logo === "grey") {
        __out.push('\n    <a href=\'http://bokeh.pydata.org/\' target=\'_blank\' class=\'bk-logo bk-logo-small grey\'></a>\n  ');
      } else if (this.logo != null) {
        __out.push('\n  <a href=\'http://bokeh.pydata.org/\' target=\'_blank\' class=\'bk-logo bk-logo-small\'></a>\n  ');
      }
    
      __out.push('\n  <div class=\'bk-button-bar\'>\n    <ul class=\'bk-button-bar-list\' type="pan" />\n    <ul class=\'bk-button-bar-list\' type="scroll" />\n    <ul class=\'bk-button-bar-list\' type="pinch" />\n    <ul class=\'bk-button-bar-list\' type="tap" />\n    <ul class=\'bk-button-bar-list\' type="press" />\n    <ul class=\'bk-button-bar-list\' type="rotate" />\n    <ul class=\'bk-button-bar-list\' type="actions" />\n    <div class=\'bk-button-bar-list bk-bs-dropdown\' type="inspectors" />\n    <ul class=\'bk-button-bar-list\' type="help" />\n  </div>\n</div>\n');
    
    }).call(this);
    
  }).call(__obj);
  return __out.join('');
};
},{}],"models/transforms/interpolator":[function(require,module,exports){
var Interpolator, Transform, _, logger, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

_ = require("underscore");

Transform = require("./transform");

p = require("../../core/properties");

logger = require("../../core/logging").logger;

Interpolator = (function(superClass) {
  extend(Interpolator, superClass);

  function Interpolator() {
    return Interpolator.__super__.constructor.apply(this, arguments);
  }

  Interpolator.prototype.initialize = function(attrs, options) {
    Interpolator.__super__.initialize.call(this, attrs, options);
    this._x_sorted = [];
    this._y_sorted = [];
    this._sorted_dirty = true;
    return this.bind('change', function() {
      return this._sorted_dirty = true;
    });
  };

  Interpolator.define({
    x: [p.Any],
    y: [p.Any],
    data: [p.Any],
    clip: [p.Bool, true]
  });

  Interpolator.prototype.sort = function(descending) {
    var column_names, data, i, j, k, list, ref, ref1, ref2, tsx, tsy;
    if (descending == null) {
      descending = false;
    }
    if (typeof (this.get('x')) !== typeof (this.get('y'))) {
      throw Error('The parameters for x and y must be of the same type, either both strings which define a column in the data source or both arrays of the same length');
      return;
    } else {
      if (typeof (this.get('x')) === 'string' && this.get('data') === null) {
        throw Error('If the x and y parameters are not specified as an array, the data parameter is reqired.');
        return;
      }
    }
    if (this._sorted_dirty === false) {
      return;
    }
    tsx = [];
    tsy = [];
    if (typeof (this.get('x')) === 'string') {
      data = this.get('data');
      column_names = data.columns();
      if (ref = this.get('x'), indexOf.call(column_names, ref) < 0) {
        throw Error('The x parameter does not correspond to a valid column name defined in the data parameter');
      }
      if (ref1 = this.get('y'), indexOf.call(column_names, ref1) < 0) {
        throw Error('The x parameter does not correspond to a valid column name defined in the data parameter');
      }
      tsx = data.get_column(this.get('x'));
      tsy = data.get_column(this.get('y'));
    } else {
      tsx = this.get('x');
      tsy = this.get('y');
    }
    if (tsx.length !== tsy.length) {
      throw Error('The length for x and y do not match');
    }
    if (tsx.length < 2) {
      throw Error('x and y must have at least two elements to support interpolation');
    }
    list = [];
    for (j in tsx) {
      list.push({
        'x': tsx[j],
        'y': tsy[j]
      });
    }
    if (descending === true) {
      list.sort(function(a, b) {
        var ref2, ref3;
        return (ref2 = a.x < b.x) != null ? ref2 : -{
          1: (ref3 = a.x === b.x) != null ? ref3 : {
            0: 1
          }
        };
      });
    } else {
      list.sort(function(a, b) {
        var ref2, ref3;
        return (ref2 = a.x > b.x) != null ? ref2 : -{
          1: (ref3 = a.x === b.x) != null ? ref3 : {
            0: 1
          }
        };
      });
    }
    for (k = i = 0, ref2 = list.length - 1; 0 <= ref2 ? i <= ref2 : i >= ref2; k = 0 <= ref2 ? ++i : --i) {
      this._x_sorted[k] = list[k].x;
      this._y_sorted[k] = list[k].y;
    }
    return this._sorted_dirty = false;
  };

  return Interpolator;

})(Transform.Model);

module.exports = {
  Model: Interpolator
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","./transform":"models/transforms/transform","underscore":"underscore"}],"models/transforms/jitter":[function(require,module,exports){
var Jitter, Transform, _, bokeh_math, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Transform = require("./transform");

p = require("../../core/properties");

bokeh_math = require("../../core/util/math");

Jitter = (function(superClass) {
  extend(Jitter, superClass);

  function Jitter() {
    return Jitter.__super__.constructor.apply(this, arguments);
  }

  Jitter.define({
    mean: [p.Number, 0],
    width: [p.Number, 1],
    distribution: [p.Distribution, 'uniform']
  });

  Jitter.prototype.compute = function(x) {
    if (this.get('distribution') === 'uniform') {
      return x + this.get('mean') + ((bokeh_math.random() - 0.5) * this.get('width'));
    }
    if (this.get('distribution') === 'normal') {
      return x + bokeh_math.rnorm(this.get('mean'), this.get('width'));
    }
  };

  Jitter.prototype.v_compute = function(xs) {
    var i, idx, len, result, x;
    result = new Float64Array(xs.length);
    for (idx = i = 0, len = xs.length; i < len; idx = ++i) {
      x = xs[idx];
      result[idx] = this.compute(x);
    }
    return result;
  };

  return Jitter;

})(Transform.Model);

module.exports = {
  Model: Jitter
};

},{"../../core/properties":"core/properties","../../core/util/math":"core/util/math","./transform":"models/transforms/transform","underscore":"underscore"}],"models/transforms/linear_interpolator":[function(require,module,exports){
var Interpolator, LinearInterpolator, Transform, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Transform = require("./transform");

Interpolator = require("./interpolator");

LinearInterpolator = (function(superClass) {
  extend(LinearInterpolator, superClass);

  function LinearInterpolator() {
    return LinearInterpolator.__super__.constructor.apply(this, arguments);
  }

  LinearInterpolator.prototype.defaults = function() {
    return _.extend({}, LinearInterpolator.__super__.defaults.call(this));
  };

  LinearInterpolator.prototype.compute = function(x) {
    var descending, ind, ret, x1, x2, y1, y2;
    this.sort(descending = false);
    if (this.clip === true) {
      if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1]) {
        return null;
      }
    } else {
      if (x < this._x_sorted[0]) {
        return this._y_sorted[0];
      }
      if (x > this._x_sorted[this._x_sorted.length - 1]) {
        return this._y_sorted[this._y_sorted.length - 1];
      }
    }
    ind = _.findLastIndex(this._x_sorted, function(num) {
      return x >= num;
    });
    x1 = this._x_sorted[ind];
    x2 = this._x_sorted[ind + 1];
    y1 = this._y_sorted[ind];
    y2 = this._y_sorted[ind + 1];
    ret = y1 + (((x - x1) / (x2 - x1)) * (y2 - y1));
    return ret;
  };

  LinearInterpolator.prototype.v_compute = function(xs) {
    var i, idx, len, result, x;
    result = new Float64Array(xs.length);
    for (idx = i = 0, len = xs.length; i < len; idx = ++i) {
      x = xs[idx];
      result[idx] = this.compute(x);
    }
    return result;
  };

  return LinearInterpolator;

})(Interpolator.Model);

module.exports = {
  Model: LinearInterpolator
};

},{"./interpolator":"models/transforms/interpolator","./transform":"models/transforms/transform","underscore":"underscore"}],"models/transforms/step_interpolator":[function(require,module,exports){
var Interpolator, StepInterpolator, Transform, _, p,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Transform = require("./transform");

Interpolator = require("./interpolator");

p = require("../../core/properties");

StepInterpolator = (function(superClass) {
  extend(StepInterpolator, superClass);

  function StepInterpolator() {
    return StepInterpolator.__super__.constructor.apply(this, arguments);
  }

  StepInterpolator.define({
    mode: [p.TransformStepMode, "after"]
  });

  StepInterpolator.prototype.compute = function(x) {
    var descending, diffs, ind, mdiff, ret, tx;
    this.sort(descending = false);
    if (this.clip === true) {
      if (x < this._x_sorted[0] || x > this._x_sorted[this._x_sorted.length - 1]) {
        return null;
      }
    } else {
      if (x < this._x_sorted[0]) {
        return this._y_sorted[0];
      }
      if (x > this._x_sorted[this._x_sorted.length - 1]) {
        return this._y_sorted[this._y_sorted.length - 1];
      }
    }
    ind = -1;
    if (this.get('mode') === "after") {
      ind = _.findLastIndex(this._x_sorted, function(num) {
        return x >= num;
      });
    }
    if (this.get('mode') === "before") {
      ind = _.findIndex(this._x_sorted, function(num) {
        return x <= num;
      });
    }
    if (this.get('mode') === "center") {
      diffs = (function() {
        var i, len, ref, results;
        ref = this._x_sorted;
        results = [];
        for (i = 0, len = ref.length; i < len; i++) {
          tx = ref[i];
          results.push(Math.abs(tx - x));
        }
        return results;
      }).call(this);
      mdiff = _.min(diffs);
      ind = _.findIndex(diffs, function(num) {
        return mdiff === num;
      });
    }
    if (ind !== -1) {
      ret = this._y_sorted[ind];
    } else {
      ret = null;
    }
    return ret;
  };

  StepInterpolator.prototype.v_compute = function(xs) {
    var i, idx, len, result, x;
    result = new Float64Array(xs.length);
    for (idx = i = 0, len = xs.length; i < len; idx = ++i) {
      x = xs[idx];
      result[idx] = this.compute(x);
    }
    return result;
  };

  return StepInterpolator;

})(Interpolator.Model);

module.exports = {
  Model: StepInterpolator
};

},{"../../core/properties":"core/properties","./interpolator":"models/transforms/interpolator","./transform":"models/transforms/transform","underscore":"underscore"}],"models/transforms/transform":[function(require,module,exports){
var Model, Transform, _,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

_ = require("underscore");

Model = require("../../model");

Transform = (function(superClass) {
  extend(Transform, superClass);

  function Transform() {
    return Transform.__super__.constructor.apply(this, arguments);
  }

  Transform.prototype.defaults = function() {
    return _.extend({}, Transform.__super__.defaults.call(this));
  };

  return Transform;

})(Model);

module.exports = {
  Model: Transform
};

},{"../../model":"model","underscore":"underscore"}],"palettes/palettes":[function(require,module,exports){
var _, palettes;

_ = require("underscore");

palettes = {
  YlGn: {
    YlGn3: [0x31a354, 0xaddd8e, 0xf7fcb9],
    YlGn4: [0x238443, 0x78c679, 0xc2e699, 0xffffcc],
    YlGn5: [0x006837, 0x31a354, 0x78c679, 0xc2e699, 0xffffcc],
    YlGn6: [0x006837, 0x31a354, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc],
    YlGn7: [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xffffcc],
    YlGn8: [0x005a32, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5],
    YlGn9: [0x004529, 0x006837, 0x238443, 0x41ab5d, 0x78c679, 0xaddd8e, 0xd9f0a3, 0xf7fcb9, 0xffffe5]
  },
  YlGnBu: {
    YlGnBu3: [0x2c7fb8, 0x7fcdbb, 0xedf8b1],
    YlGnBu4: [0x225ea8, 0x41b6c4, 0xa1dab4, 0xffffcc],
    YlGnBu5: [0x253494, 0x2c7fb8, 0x41b6c4, 0xa1dab4, 0xffffcc],
    YlGnBu6: [0x253494, 0x2c7fb8, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc],
    YlGnBu7: [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xffffcc],
    YlGnBu8: [0x0c2c84, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9],
    YlGnBu9: [0x081d58, 0x253494, 0x225ea8, 0x1d91c0, 0x41b6c4, 0x7fcdbb, 0xc7e9b4, 0xedf8b1, 0xffffd9]
  },
  GnBu: {
    GnBu3: [0x43a2ca, 0xa8ddb5, 0xe0f3db],
    GnBu4: [0x2b8cbe, 0x7bccc4, 0xbae4bc, 0xf0f9e8],
    GnBu5: [0x0868ac, 0x43a2ca, 0x7bccc4, 0xbae4bc, 0xf0f9e8],
    GnBu6: [0x0868ac, 0x43a2ca, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8],
    GnBu7: [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xf0f9e8],
    GnBu8: [0x08589e, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0],
    GnBu9: [0x084081, 0x0868ac, 0x2b8cbe, 0x4eb3d3, 0x7bccc4, 0xa8ddb5, 0xccebc5, 0xe0f3db, 0xf7fcf0]
  },
  BuGn: {
    BuGn3: [0x2ca25f, 0x99d8c9, 0xe5f5f9],
    BuGn4: [0x238b45, 0x66c2a4, 0xb2e2e2, 0xedf8fb],
    BuGn5: [0x006d2c, 0x2ca25f, 0x66c2a4, 0xb2e2e2, 0xedf8fb],
    BuGn6: [0x006d2c, 0x2ca25f, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb],
    BuGn7: [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xedf8fb],
    BuGn8: [0x005824, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd],
    BuGn9: [0x00441b, 0x006d2c, 0x238b45, 0x41ae76, 0x66c2a4, 0x99d8c9, 0xccece6, 0xe5f5f9, 0xf7fcfd]
  },
  PuBuGn: {
    PuBuGn3: [0x1c9099, 0xa6bddb, 0xece2f0],
    PuBuGn4: [0x02818a, 0x67a9cf, 0xbdc9e1, 0xf6eff7],
    PuBuGn5: [0x016c59, 0x1c9099, 0x67a9cf, 0xbdc9e1, 0xf6eff7],
    PuBuGn6: [0x016c59, 0x1c9099, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7],
    PuBuGn7: [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xf6eff7],
    PuBuGn8: [0x016450, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb],
    PuBuGn9: [0x014636, 0x016c59, 0x02818a, 0x3690c0, 0x67a9cf, 0xa6bddb, 0xd0d1e6, 0xece2f0, 0xfff7fb]
  },
  PuBu: {
    PuBu3: [0x2b8cbe, 0xa6bddb, 0xece7f2],
    PuBu4: [0x0570b0, 0x74a9cf, 0xbdc9e1, 0xf1eef6],
    PuBu5: [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xbdc9e1, 0xf1eef6],
    PuBu6: [0x045a8d, 0x2b8cbe, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6],
    PuBu7: [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xf1eef6],
    PuBu8: [0x034e7b, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb],
    PuBu9: [0x023858, 0x045a8d, 0x0570b0, 0x3690c0, 0x74a9cf, 0xa6bddb, 0xd0d1e6, 0xece7f2, 0xfff7fb]
  },
  BuPu: {
    BuPu3: [0x8856a7, 0x9ebcda, 0xe0ecf4],
    BuPu4: [0x88419d, 0x8c96c6, 0xb3cde3, 0xedf8fb],
    BuPu5: [0x810f7c, 0x8856a7, 0x8c96c6, 0xb3cde3, 0xedf8fb],
    BuPu6: [0x810f7c, 0x8856a7, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb],
    BuPu7: [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xedf8fb],
    BuPu8: [0x6e016b, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd],
    BuPu9: [0x4d004b, 0x810f7c, 0x88419d, 0x8c6bb1, 0x8c96c6, 0x9ebcda, 0xbfd3e6, 0xe0ecf4, 0xf7fcfd]
  },
  RdPu: {
    RdPu3: [0xc51b8a, 0xfa9fb5, 0xfde0dd],
    RdPu4: [0xae017e, 0xf768a1, 0xfbb4b9, 0xfeebe2],
    RdPu5: [0x7a0177, 0xc51b8a, 0xf768a1, 0xfbb4b9, 0xfeebe2],
    RdPu6: [0x7a0177, 0xc51b8a, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2],
    RdPu7: [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfeebe2],
    RdPu8: [0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3],
    RdPu9: [0x49006a, 0x7a0177, 0xae017e, 0xdd3497, 0xf768a1, 0xfa9fb5, 0xfcc5c0, 0xfde0dd, 0xfff7f3]
  },
  PuRd: {
    PuRd3: [0xdd1c77, 0xc994c7, 0xe7e1ef],
    PuRd4: [0xce1256, 0xdf65b0, 0xd7b5d8, 0xf1eef6],
    PuRd5: [0x980043, 0xdd1c77, 0xdf65b0, 0xd7b5d8, 0xf1eef6],
    PuRd6: [0x980043, 0xdd1c77, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6],
    PuRd7: [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xf1eef6],
    PuRd8: [0x91003f, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9],
    PuRd9: [0x67001f, 0x980043, 0xce1256, 0xe7298a, 0xdf65b0, 0xc994c7, 0xd4b9da, 0xe7e1ef, 0xf7f4f9]
  },
  OrRd: {
    OrRd3: [0xe34a33, 0xfdbb84, 0xfee8c8],
    OrRd4: [0xd7301f, 0xfc8d59, 0xfdcc8a, 0xfef0d9],
    OrRd5: [0xb30000, 0xe34a33, 0xfc8d59, 0xfdcc8a, 0xfef0d9],
    OrRd6: [0xb30000, 0xe34a33, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9],
    OrRd7: [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfef0d9],
    OrRd8: [0x990000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec],
    OrRd9: [0x7f0000, 0xb30000, 0xd7301f, 0xef6548, 0xfc8d59, 0xfdbb84, 0xfdd49e, 0xfee8c8, 0xfff7ec]
  },
  YlOrRd: {
    YlOrRd3: [0xf03b20, 0xfeb24c, 0xffeda0],
    YlOrRd4: [0xe31a1c, 0xfd8d3c, 0xfecc5c, 0xffffb2],
    YlOrRd5: [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfecc5c, 0xffffb2],
    YlOrRd6: [0xbd0026, 0xf03b20, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2],
    YlOrRd7: [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffffb2],
    YlOrRd8: [0xb10026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc],
    YlOrRd9: [0x800026, 0xbd0026, 0xe31a1c, 0xfc4e2a, 0xfd8d3c, 0xfeb24c, 0xfed976, 0xffeda0, 0xffffcc]
  },
  YlOrBr: {
    YlOrBr3: [0xd95f0e, 0xfec44f, 0xfff7bc],
    YlOrBr4: [0xcc4c02, 0xfe9929, 0xfed98e, 0xffffd4],
    YlOrBr5: [0x993404, 0xd95f0e, 0xfe9929, 0xfed98e, 0xffffd4],
    YlOrBr6: [0x993404, 0xd95f0e, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4],
    YlOrBr7: [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xffffd4],
    YlOrBr8: [0x8c2d04, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5],
    YlOrBr9: [0x662506, 0x993404, 0xcc4c02, 0xec7014, 0xfe9929, 0xfec44f, 0xfee391, 0xfff7bc, 0xffffe5]
  },
  Purples: {
    Purples3: [0x756bb1, 0xbcbddc, 0xefedf5],
    Purples4: [0x6a51a3, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7],
    Purples5: [0x54278f, 0x756bb1, 0x9e9ac8, 0xcbc9e2, 0xf2f0f7],
    Purples6: [0x54278f, 0x756bb1, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7],
    Purples7: [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xf2f0f7],
    Purples8: [0x4a1486, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd],
    Purples9: [0x3f007d, 0x54278f, 0x6a51a3, 0x807dba, 0x9e9ac8, 0xbcbddc, 0xdadaeb, 0xefedf5, 0xfcfbfd]
  },
  Blues: {
    Blues3: [0x3182bd, 0x9ecae1, 0xdeebf7],
    Blues4: [0x2171b5, 0x6baed6, 0xbdd7e7, 0xeff3ff],
    Blues5: [0x08519c, 0x3182bd, 0x6baed6, 0xbdd7e7, 0xeff3ff],
    Blues6: [0x08519c, 0x3182bd, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff],
    Blues7: [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xeff3ff],
    Blues8: [0x084594, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff],
    Blues9: [0x08306b, 0x08519c, 0x2171b5, 0x4292c6, 0x6baed6, 0x9ecae1, 0xc6dbef, 0xdeebf7, 0xf7fbff]
  },
  Greens: {
    Greens3: [0x31a354, 0xa1d99b, 0xe5f5e0],
    Greens4: [0x238b45, 0x74c476, 0xbae4b3, 0xedf8e9],
    Greens5: [0x006d2c, 0x31a354, 0x74c476, 0xbae4b3, 0xedf8e9],
    Greens6: [0x006d2c, 0x31a354, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9],
    Greens7: [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xedf8e9],
    Greens8: [0x005a32, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5],
    Greens9: [0x00441b, 0x006d2c, 0x238b45, 0x41ab5d, 0x74c476, 0xa1d99b, 0xc7e9c0, 0xe5f5e0, 0xf7fcf5]
  },
  Oranges: {
    Oranges3: [0xe6550d, 0xfdae6b, 0xfee6ce],
    Oranges4: [0xd94701, 0xfd8d3c, 0xfdbe85, 0xfeedde],
    Oranges5: [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdbe85, 0xfeedde],
    Oranges6: [0xa63603, 0xe6550d, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde],
    Oranges7: [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfeedde],
    Oranges8: [0x8c2d04, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb],
    Oranges9: [0x7f2704, 0xa63603, 0xd94801, 0xf16913, 0xfd8d3c, 0xfdae6b, 0xfdd0a2, 0xfee6ce, 0xfff5eb]
  },
  Reds: {
    Reds3: [0xde2d26, 0xfc9272, 0xfee0d2],
    Reds4: [0xcb181d, 0xfb6a4a, 0xfcae91, 0xfee5d9],
    Reds5: [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfcae91, 0xfee5d9],
    Reds6: [0xa50f15, 0xde2d26, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9],
    Reds7: [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee5d9],
    Reds8: [0x99000d, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0],
    Reds9: [0x67000d, 0xa50f15, 0xcb181d, 0xef3b2c, 0xfb6a4a, 0xfc9272, 0xfcbba1, 0xfee0d2, 0xfff5f0]
  },
  Greys: {
    Greys3: [0x636363, 0xbdbdbd, 0xf0f0f0],
    Greys4: [0x525252, 0x969696, 0xcccccc, 0xf7f7f7],
    Greys5: [0x252525, 0x636363, 0x969696, 0xcccccc, 0xf7f7f7],
    Greys6: [0x252525, 0x636363, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7],
    Greys7: [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf7f7f7],
    Greys8: [0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff],
    Greys9: [0x000000, 0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff],
    Greys10: [0x000000, 0x1c1c1c, 0x383838, 0x555555, 0x717171, 0x8d8d8d, 0xaaaaaa, 0xc6c6c6, 0xe2e2e2, 0xffffff],
    Greys11: [0x000000, 0x191919, 0x333333, 0x4c4c4c, 0x666666, 0x7f7f7f, 0x999999, 0xb2b2b2, 0xcccccc, 0xe5e5e5, 0xffffff],
    Greys256: [0x000000, 0x010101, 0x020202, 0x030303, 0x040404, 0x050505, 0x060606, 0x070707, 0x080808, 0x090909, 0x0a0a0a, 0x0b0b0b, 0x0c0c0c, 0x0d0d0d, 0x0e0e0e, 0x0f0f0f, 0x101010, 0x111111, 0x121212, 0x131313, 0x141414, 0x151515, 0x161616, 0x171717, 0x181818, 0x191919, 0x1a1a1a, 0x1b1b1b, 0x1c1c1c, 0x1d1d1d, 0x1e1e1e, 0x1f1f1f, 0x202020, 0x212121, 0x222222, 0x232323, 0x242424, 0x252525, 0x262626, 0x272727, 0x282828, 0x292929, 0x2a2a2a, 0x2b2b2b, 0x2c2c2c, 0x2d2d2d, 0x2e2e2e, 0x2f2f2f, 0x303030, 0x313131, 0x323232, 0x333333, 0x343434, 0x353535, 0x363636, 0x373737, 0x383838, 0x393939, 0x3a3a3a, 0x3b3b3b, 0x3c3c3c, 0x3d3d3d, 0x3e3e3e, 0x3f3f3f, 0x404040, 0x414141, 0x424242, 0x434343, 0x444444, 0x454545, 0x464646, 0x474747, 0x484848, 0x494949, 0x4a4a4a, 0x4b4b4b, 0x4c4c4c, 0x4d4d4d, 0x4e4e4e, 0x4f4f4f, 0x505050, 0x515151, 0x525252, 0x535353, 0x545454, 0x555555, 0x565656, 0x575757, 0x585858, 0x595959, 0x5a5a5a, 0x5b5b5b, 0x5c5c5c, 0x5d5d5d, 0x5e5e5e, 0x5f5f5f, 0x606060, 0x616161, 0x626262, 0x636363, 0x646464, 0x656565, 0x666666, 0x676767, 0x686868, 0x696969, 0x6a6a6a, 0x6b6b6b, 0x6c6c6c, 0x6d6d6d, 0x6e6e6e, 0x6f6f6f, 0x707070, 0x717171, 0x727272, 0x737373, 0x747474, 0x757575, 0x767676, 0x777777, 0x787878, 0x797979, 0x7a7a7a, 0x7b7b7b, 0x7c7c7c, 0x7d7d7d, 0x7e7e7e, 0x7f7f7f, 0x808080, 0x818181, 0x828282, 0x838383, 0x848484, 0x858585, 0x868686, 0x878787, 0x888888, 0x898989, 0x8a8a8a, 0x8b8b8b, 0x8c8c8c, 0x8d8d8d, 0x8e8e8e, 0x8f8f8f, 0x909090, 0x919191, 0x929292, 0x939393, 0x949494, 0x959595, 0x969696, 0x979797, 0x989898, 0x999999, 0x9a9a9a, 0x9b9b9b, 0x9c9c9c, 0x9d9d9d, 0x9e9e9e, 0x9f9f9f, 0xa0a0a0, 0xa1a1a1, 0xa2a2a2, 0xa3a3a3, 0xa4a4a4, 0xa5a5a5, 0xa6a6a6, 0xa7a7a7, 0xa8a8a8, 0xa9a9a9, 0xaaaaaa, 0xababab, 0xacacac, 0xadadad, 0xaeaeae, 0xafafaf, 0xb0b0b0, 0xb1b1b1, 0xb2b2b2, 0xb3b3b3, 0xb4b4b4, 0xb5b5b5, 0xb6b6b6, 0xb7b7b7, 0xb8b8b8, 0xb9b9b9, 0xbababa, 0xbbbbbb, 0xbcbcbc, 0xbdbdbd, 0xbebebe, 0xbfbfbf, 0xc0c0c0, 0xc1c1c1, 0xc2c2c2, 0xc3c3c3, 0xc4c4c4, 0xc5c5c5, 0xc6c6c6, 0xc7c7c7, 0xc8c8c8, 0xc9c9c9, 0xcacaca, 0xcbcbcb, 0xcccccc, 0xcdcdcd, 0xcecece, 0xcfcfcf, 0xd0d0d0, 0xd1d1d1, 0xd2d2d2, 0xd3d3d3, 0xd4d4d4, 0xd5d5d5, 0xd6d6d6, 0xd7d7d7, 0xd8d8d8, 0xd9d9d9, 0xdadada, 0xdbdbdb, 0xdcdcdc, 0xdddddd, 0xdedede, 0xdfdfdf, 0xe0e0e0, 0xe1e1e1, 0xe2e2e2, 0xe3e3e3, 0xe4e4e4, 0xe5e5e5, 0xe6e6e6, 0xe7e7e7, 0xe8e8e8, 0xe9e9e9, 0xeaeaea, 0xebebeb, 0xececec, 0xededed, 0xeeeeee, 0xefefef, 0xf0f0f0, 0xf1f1f1, 0xf2f2f2, 0xf3f3f3, 0xf4f4f4, 0xf5f5f5, 0xf6f6f6, 0xf7f7f7, 0xf8f8f8, 0xf9f9f9, 0xfafafa, 0xfbfbfb, 0xfcfcfc, 0xfdfdfd, 0xfefefe, 0xffffff]
  },
  PuOr: {
    PuOr3: [0x998ec3, 0xf7f7f7, 0xf1a340],
    PuOr4: [0x5e3c99, 0xb2abd2, 0xfdb863, 0xe66101],
    PuOr5: [0x5e3c99, 0xb2abd2, 0xf7f7f7, 0xfdb863, 0xe66101],
    PuOr6: [0x542788, 0x998ec3, 0xd8daeb, 0xfee0b6, 0xf1a340, 0xb35806],
    PuOr7: [0x542788, 0x998ec3, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xf1a340, 0xb35806],
    PuOr8: [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806],
    PuOr9: [0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806],
    PuOr10: [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08],
    PuOr11: [0x2d004b, 0x542788, 0x8073ac, 0xb2abd2, 0xd8daeb, 0xf7f7f7, 0xfee0b6, 0xfdb863, 0xe08214, 0xb35806, 0x7f3b08]
  },
  BrBG: {
    BrBG3: [0x5ab4ac, 0xf5f5f5, 0xd8b365],
    BrBG4: [0x018571, 0x80cdc1, 0xdfc27d, 0xa6611a],
    BrBG5: [0x018571, 0x80cdc1, 0xf5f5f5, 0xdfc27d, 0xa6611a],
    BrBG6: [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf6e8c3, 0xd8b365, 0x8c510a],
    BrBG7: [0x01665e, 0x5ab4ac, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xd8b365, 0x8c510a],
    BrBG8: [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a],
    BrBG9: [0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a],
    BrBG10: [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005],
    BrBG11: [0x003c30, 0x01665e, 0x35978f, 0x80cdc1, 0xc7eae5, 0xf5f5f5, 0xf6e8c3, 0xdfc27d, 0xbf812d, 0x8c510a, 0x543005]
  },
  PRGn: {
    PRGn3: [0x7fbf7b, 0xf7f7f7, 0xaf8dc3],
    PRGn4: [0x008837, 0xa6dba0, 0xc2a5cf, 0x7b3294],
    PRGn5: [0x008837, 0xa6dba0, 0xf7f7f7, 0xc2a5cf, 0x7b3294],
    PRGn6: [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xe7d4e8, 0xaf8dc3, 0x762a83],
    PRGn7: [0x1b7837, 0x7fbf7b, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xaf8dc3, 0x762a83],
    PRGn8: [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83],
    PRGn9: [0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83],
    PRGn10: [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b],
    PRGn11: [0x00441b, 0x1b7837, 0x5aae61, 0xa6dba0, 0xd9f0d3, 0xf7f7f7, 0xe7d4e8, 0xc2a5cf, 0x9970ab, 0x762a83, 0x40004b]
  },
  PiYG: {
    PiYG3: [0xa1d76a, 0xf7f7f7, 0xe9a3c9],
    PiYG4: [0x4dac26, 0xb8e186, 0xf1b6da, 0xd01c8b],
    PiYG5: [0x4dac26, 0xb8e186, 0xf7f7f7, 0xf1b6da, 0xd01c8b],
    PiYG6: [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xfde0ef, 0xe9a3c9, 0xc51b7d],
    PiYG7: [0x4d9221, 0xa1d76a, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xe9a3c9, 0xc51b7d],
    PiYG8: [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d],
    PiYG9: [0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d],
    PiYG10: [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152],
    PiYG11: [0x276419, 0x4d9221, 0x7fbc41, 0xb8e186, 0xe6f5d0, 0xf7f7f7, 0xfde0ef, 0xf1b6da, 0xde77ae, 0xc51b7d, 0x8e0152]
  },
  RdBu: {
    RdBu3: [0x67a9cf, 0xf7f7f7, 0xef8a62],
    RdBu4: [0x0571b0, 0x92c5de, 0xf4a582, 0xca0020],
    RdBu5: [0x0571b0, 0x92c5de, 0xf7f7f7, 0xf4a582, 0xca0020],
    RdBu6: [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xfddbc7, 0xef8a62, 0xb2182b],
    RdBu7: [0x2166ac, 0x67a9cf, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xef8a62, 0xb2182b],
    RdBu8: [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
    RdBu9: [0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
    RdBu10: [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f],
    RdBu11: [0x053061, 0x2166ac, 0x4393c3, 0x92c5de, 0xd1e5f0, 0xf7f7f7, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f]
  },
  RdGy: {
    RdGy3: [0x999999, 0xffffff, 0xef8a62],
    RdGy4: [0x404040, 0xbababa, 0xf4a582, 0xca0020],
    RdGy5: [0x404040, 0xbababa, 0xffffff, 0xf4a582, 0xca0020],
    RdGy6: [0x4d4d4d, 0x999999, 0xe0e0e0, 0xfddbc7, 0xef8a62, 0xb2182b],
    RdGy7: [0x4d4d4d, 0x999999, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xef8a62, 0xb2182b],
    RdGy8: [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
    RdGy9: [0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b],
    RdGy10: [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f],
    RdGy11: [0x1a1a1a, 0x4d4d4d, 0x878787, 0xbababa, 0xe0e0e0, 0xffffff, 0xfddbc7, 0xf4a582, 0xd6604d, 0xb2182b, 0x67001f]
  },
  RdYlBu: {
    RdYlBu3: [0x91bfdb, 0xffffbf, 0xfc8d59],
    RdYlBu4: [0x2c7bb6, 0xabd9e9, 0xfdae61, 0xd7191c],
    RdYlBu5: [0x2c7bb6, 0xabd9e9, 0xffffbf, 0xfdae61, 0xd7191c],
    RdYlBu6: [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xfee090, 0xfc8d59, 0xd73027],
    RdYlBu7: [0x4575b4, 0x91bfdb, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfc8d59, 0xd73027],
    RdYlBu8: [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027],
    RdYlBu9: [0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027],
    RdYlBu10: [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026],
    RdYlBu11: [0x313695, 0x4575b4, 0x74add1, 0xabd9e9, 0xe0f3f8, 0xffffbf, 0xfee090, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026]
  },
  Spectral: {
    Spectral3: [0x99d594, 0xffffbf, 0xfc8d59],
    Spectral4: [0x2b83ba, 0xabdda4, 0xfdae61, 0xd7191c],
    Spectral5: [0x2b83ba, 0xabdda4, 0xffffbf, 0xfdae61, 0xd7191c],
    Spectral6: [0x3288bd, 0x99d594, 0xe6f598, 0xfee08b, 0xfc8d59, 0xd53e4f],
    Spectral7: [0x3288bd, 0x99d594, 0xe6f598, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd53e4f],
    Spectral8: [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f],
    Spectral9: [0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f],
    Spectral10: [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142],
    Spectral11: [0x5e4fa2, 0x3288bd, 0x66c2a5, 0xabdda4, 0xe6f598, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd53e4f, 0x9e0142]
  },
  RdYlGn: {
    RdYlGn3: [0x91cf60, 0xffffbf, 0xfc8d59],
    RdYlGn4: [0x1a9641, 0xa6d96a, 0xfdae61, 0xd7191c],
    RdYlGn5: [0x1a9641, 0xa6d96a, 0xffffbf, 0xfdae61, 0xd7191c],
    RdYlGn6: [0x1a9850, 0x91cf60, 0xd9ef8b, 0xfee08b, 0xfc8d59, 0xd73027],
    RdYlGn7: [0x1a9850, 0x91cf60, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfc8d59, 0xd73027],
    RdYlGn8: [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027],
    RdYlGn9: [0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027],
    RdYlGn10: [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026],
    RdYlGn11: [0x006837, 0x1a9850, 0x66bd63, 0xa6d96a, 0xd9ef8b, 0xffffbf, 0xfee08b, 0xfdae61, 0xf46d43, 0xd73027, 0xa50026]
  },
  Inferno: {
    Inferno3: [0x440154, 0x208f8c, 0xfde724],
    Inferno4: [0x000003, 0x781c6d, 0xed6825, 0xfcfea4],
    Inferno5: [0x000003, 0x550f6d, 0xba3655, 0xf98c09, 0xfcfea4],
    Inferno6: [0x000003, 0x410967, 0x932567, 0xdc5039, 0xfba40a, 0xfcfea4],
    Inferno7: [0x000003, 0x32095d, 0x781c6d, 0xba3655, 0xed6825, 0xfbb318, 0xfcfea4],
    Inferno8: [0x000003, 0x270b52, 0x63146e, 0x9e2963, 0xd24742, 0xf57c15, 0xfabf25, 0xfcfea4],
    Inferno9: [0x000003, 0x1f0c47, 0x550f6d, 0x88216a, 0xba3655, 0xe35832, 0xf98c09, 0xf8c931, 0xfcfea4],
    Inferno10: [0x000003, 0x1a0b40, 0x4a0b6a, 0x781c6d, 0xa42c60, 0xcd4247, 0xed6825, 0xfb9906, 0xf7cf3a, 0xfcfea4],
    Inferno11: [0x000003, 0x160b39, 0x410967, 0x6a176e, 0x932567, 0xba3655, 0xdc5039, 0xf2751a, 0xfba40a, 0xf6d542, 0xfcfea4],
    Inferno256: [0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02010e, 0x020210, 0x030212, 0x040314, 0x040316, 0x050418, 0x06041b, 0x07051d, 0x08061f, 0x090621, 0x0a0723, 0x0b0726, 0x0d0828, 0x0e082a, 0x0f092d, 0x10092f, 0x120a32, 0x130a34, 0x140b36, 0x160b39, 0x170b3b, 0x190b3e, 0x1a0b40, 0x1c0c43, 0x1d0c45, 0x1f0c47, 0x200c4a, 0x220b4c, 0x240b4e, 0x260b50, 0x270b52, 0x290b54, 0x2b0a56, 0x2d0a58, 0x2e0a5a, 0x300a5c, 0x32095d, 0x34095f, 0x350960, 0x370961, 0x390962, 0x3b0964, 0x3c0965, 0x3e0966, 0x400966, 0x410967, 0x430a68, 0x450a69, 0x460a69, 0x480b6a, 0x4a0b6a, 0x4b0c6b, 0x4d0c6b, 0x4f0d6c, 0x500d6c, 0x520e6c, 0x530e6d, 0x550f6d, 0x570f6d, 0x58106d, 0x5a116d, 0x5b116e, 0x5d126e, 0x5f126e, 0x60136e, 0x62146e, 0x63146e, 0x65156e, 0x66156e, 0x68166e, 0x6a176e, 0x6b176e, 0x6d186e, 0x6e186e, 0x70196e, 0x72196d, 0x731a6d, 0x751b6d, 0x761b6d, 0x781c6d, 0x7a1c6d, 0x7b1d6c, 0x7d1d6c, 0x7e1e6c, 0x801f6b, 0x811f6b, 0x83206b, 0x85206a, 0x86216a, 0x88216a, 0x892269, 0x8b2269, 0x8d2369, 0x8e2468, 0x902468, 0x912567, 0x932567, 0x952666, 0x962666, 0x982765, 0x992864, 0x9b2864, 0x9c2963, 0x9e2963, 0xa02a62, 0xa12b61, 0xa32b61, 0xa42c60, 0xa62c5f, 0xa72d5f, 0xa92e5e, 0xab2e5d, 0xac2f5c, 0xae305b, 0xaf315b, 0xb1315a, 0xb23259, 0xb43358, 0xb53357, 0xb73456, 0xb83556, 0xba3655, 0xbb3754, 0xbd3753, 0xbe3852, 0xbf3951, 0xc13a50, 0xc23b4f, 0xc43c4e, 0xc53d4d, 0xc73e4c, 0xc83e4b, 0xc93f4a, 0xcb4049, 0xcc4148, 0xcd4247, 0xcf4446, 0xd04544, 0xd14643, 0xd24742, 0xd44841, 0xd54940, 0xd64a3f, 0xd74b3e, 0xd94d3d, 0xda4e3b, 0xdb4f3a, 0xdc5039, 0xdd5238, 0xde5337, 0xdf5436, 0xe05634, 0xe25733, 0xe35832, 0xe45a31, 0xe55b30, 0xe65c2e, 0xe65e2d, 0xe75f2c, 0xe8612b, 0xe9622a, 0xea6428, 0xeb6527, 0xec6726, 0xed6825, 0xed6a23, 0xee6c22, 0xef6d21, 0xf06f1f, 0xf0701e, 0xf1721d, 0xf2741c, 0xf2751a, 0xf37719, 0xf37918, 0xf47a16, 0xf57c15, 0xf57e14, 0xf68012, 0xf68111, 0xf78310, 0xf7850e, 0xf8870d, 0xf8880c, 0xf88a0b, 0xf98c09, 0xf98e08, 0xf99008, 0xfa9107, 0xfa9306, 0xfa9506, 0xfa9706, 0xfb9906, 0xfb9b06, 0xfb9d06, 0xfb9e07, 0xfba007, 0xfba208, 0xfba40a, 0xfba60b, 0xfba80d, 0xfbaa0e, 0xfbac10, 0xfbae12, 0xfbb014, 0xfbb116, 0xfbb318, 0xfbb51a, 0xfbb71c, 0xfbb91e, 0xfabb21, 0xfabd23, 0xfabf25, 0xfac128, 0xf9c32a, 0xf9c52c, 0xf9c72f, 0xf8c931, 0xf8cb34, 0xf8cd37, 0xf7cf3a, 0xf7d13c, 0xf6d33f, 0xf6d542, 0xf5d745, 0xf5d948, 0xf4db4b, 0xf4dc4f, 0xf3de52, 0xf3e056, 0xf3e259, 0xf2e45d, 0xf2e660, 0xf1e864, 0xf1e968, 0xf1eb6c, 0xf1ed70, 0xf1ee74, 0xf1f079, 0xf1f27d, 0xf2f381, 0xf2f485, 0xf3f689, 0xf4f78d, 0xf5f891, 0xf6fa95, 0xf7fb99, 0xf9fc9d, 0xfafda0, 0xfcfea4]
  },
  Magma: {
    Magma3: [0x000003, 0xb53679, 0xfbfcbf],
    Magma4: [0x000003, 0x711f81, 0xf0605d, 0xfbfcbf],
    Magma5: [0x000003, 0x4f117b, 0xb53679, 0xfb8660, 0xfbfcbf],
    Magma6: [0x000003, 0x3b0f6f, 0x8c2980, 0xdd4968, 0xfd9f6c, 0xfbfcbf],
    Magma7: [0x000003, 0x2b115e, 0x711f81, 0xb53679, 0xf0605d, 0xfeae76, 0xfbfcbf],
    Magma8: [0x000003, 0x221150, 0x5d177e, 0x972c7f, 0xd1426e, 0xf8755c, 0xfeb97f, 0xfbfcbf],
    Magma9: [0x000003, 0x1b1044, 0x4f117b, 0x812581, 0xb53679, 0xe55063, 0xfb8660, 0xfec286, 0xfbfcbf],
    Magma10: [0x000003, 0x170f3c, 0x430f75, 0x711f81, 0x9e2e7e, 0xcb3e71, 0xf0605d, 0xfc9366, 0xfec78b, 0xfbfcbf],
    Magma11: [0x000003, 0x140d35, 0x3b0f6f, 0x63197f, 0x8c2980, 0xb53679, 0xdd4968, 0xf66e5b, 0xfd9f6c, 0xfdcd90, 0xfbfcbf],
    Magma256: [0x000003, 0x000004, 0x000006, 0x010007, 0x010109, 0x01010b, 0x02020d, 0x02020f, 0x030311, 0x040313, 0x040415, 0x050417, 0x060519, 0x07051b, 0x08061d, 0x09071f, 0x0a0722, 0x0b0824, 0x0c0926, 0x0d0a28, 0x0e0a2a, 0x0f0b2c, 0x100c2f, 0x110c31, 0x120d33, 0x140d35, 0x150e38, 0x160e3a, 0x170f3c, 0x180f3f, 0x1a1041, 0x1b1044, 0x1c1046, 0x1e1049, 0x1f114b, 0x20114d, 0x221150, 0x231152, 0x251155, 0x261157, 0x281159, 0x2a115c, 0x2b115e, 0x2d1060, 0x2f1062, 0x301065, 0x321067, 0x341068, 0x350f6a, 0x370f6c, 0x390f6e, 0x3b0f6f, 0x3c0f71, 0x3e0f72, 0x400f73, 0x420f74, 0x430f75, 0x450f76, 0x470f77, 0x481078, 0x4a1079, 0x4b1079, 0x4d117a, 0x4f117b, 0x50127b, 0x52127c, 0x53137c, 0x55137d, 0x57147d, 0x58157e, 0x5a157e, 0x5b167e, 0x5d177e, 0x5e177f, 0x60187f, 0x61187f, 0x63197f, 0x651a80, 0x661a80, 0x681b80, 0x691c80, 0x6b1c80, 0x6c1d80, 0x6e1e81, 0x6f1e81, 0x711f81, 0x731f81, 0x742081, 0x762181, 0x772181, 0x792281, 0x7a2281, 0x7c2381, 0x7e2481, 0x7f2481, 0x812581, 0x822581, 0x842681, 0x852681, 0x872781, 0x892881, 0x8a2881, 0x8c2980, 0x8d2980, 0x8f2a80, 0x912a80, 0x922b80, 0x942b80, 0x952c80, 0x972c7f, 0x992d7f, 0x9a2d7f, 0x9c2e7f, 0x9e2e7e, 0x9f2f7e, 0xa12f7e, 0xa3307e, 0xa4307d, 0xa6317d, 0xa7317d, 0xa9327c, 0xab337c, 0xac337b, 0xae347b, 0xb0347b, 0xb1357a, 0xb3357a, 0xb53679, 0xb63679, 0xb83778, 0xb93778, 0xbb3877, 0xbd3977, 0xbe3976, 0xc03a75, 0xc23a75, 0xc33b74, 0xc53c74, 0xc63c73, 0xc83d72, 0xca3e72, 0xcb3e71, 0xcd3f70, 0xce4070, 0xd0416f, 0xd1426e, 0xd3426d, 0xd4436d, 0xd6446c, 0xd7456b, 0xd9466a, 0xda4769, 0xdc4869, 0xdd4968, 0xde4a67, 0xe04b66, 0xe14c66, 0xe24d65, 0xe44e64, 0xe55063, 0xe65162, 0xe75262, 0xe85461, 0xea5560, 0xeb5660, 0xec585f, 0xed595f, 0xee5b5e, 0xee5d5d, 0xef5e5d, 0xf0605d, 0xf1615c, 0xf2635c, 0xf3655c, 0xf3675b, 0xf4685b, 0xf56a5b, 0xf56c5b, 0xf66e5b, 0xf6705b, 0xf7715b, 0xf7735c, 0xf8755c, 0xf8775c, 0xf9795c, 0xf97b5d, 0xf97d5d, 0xfa7f5e, 0xfa805e, 0xfa825f, 0xfb8460, 0xfb8660, 0xfb8861, 0xfb8a62, 0xfc8c63, 0xfc8e63, 0xfc9064, 0xfc9265, 0xfc9366, 0xfd9567, 0xfd9768, 0xfd9969, 0xfd9b6a, 0xfd9d6b, 0xfd9f6c, 0xfda16e, 0xfda26f, 0xfda470, 0xfea671, 0xfea873, 0xfeaa74, 0xfeac75, 0xfeae76, 0xfeaf78, 0xfeb179, 0xfeb37b, 0xfeb57c, 0xfeb77d, 0xfeb97f, 0xfebb80, 0xfebc82, 0xfebe83, 0xfec085, 0xfec286, 0xfec488, 0xfec689, 0xfec78b, 0xfec98d, 0xfecb8e, 0xfdcd90, 0xfdcf92, 0xfdd193, 0xfdd295, 0xfdd497, 0xfdd698, 0xfdd89a, 0xfdda9c, 0xfddc9d, 0xfddd9f, 0xfddfa1, 0xfde1a3, 0xfce3a5, 0xfce5a6, 0xfce6a8, 0xfce8aa, 0xfceaac, 0xfcecae, 0xfceeb0, 0xfcf0b1, 0xfcf1b3, 0xfcf3b5, 0xfcf5b7, 0xfbf7b9, 0xfbf9bb, 0xfbfabd, 0xfbfcbf]
  },
  Plasma: {
    Plasma3: [0x0c0786, 0xca4678, 0xeff821],
    Plasma4: [0x0c0786, 0x9b179e, 0xec7853, 0xeff821],
    Plasma5: [0x0c0786, 0x7c02a7, 0xca4678, 0xf79341, 0xeff821],
    Plasma6: [0x0c0786, 0x6a00a7, 0xb02a8f, 0xe06461, 0xfca635, 0xeff821],
    Plasma7: [0x0c0786, 0x5c00a5, 0x9b179e, 0xca4678, 0xec7853, 0xfdb22f, 0xeff821],
    Plasma8: [0x0c0786, 0x5201a3, 0x8908a5, 0xb83289, 0xda5a68, 0xf38748, 0xfdbb2b, 0xeff821],
    Plasma9: [0x0c0786, 0x4a02a0, 0x7c02a7, 0xa82296, 0xca4678, 0xe56b5c, 0xf79341, 0xfdc328, 0xeff821],
    Plasma10: [0x0c0786, 0x45039e, 0x7200a8, 0x9b179e, 0xbc3685, 0xd7566c, 0xec7853, 0xfa9d3a, 0xfcc726, 0xeff821],
    Plasma11: [0x0c0786, 0x40039c, 0x6a00a7, 0x8f0da3, 0xb02a8f, 0xca4678, 0xe06461, 0xf1824c, 0xfca635, 0xfccc25, 0xeff821],
    Plasma256: [0x0c0786, 0x100787, 0x130689, 0x15068a, 0x18068b, 0x1b068c, 0x1d068d, 0x1f058e, 0x21058f, 0x230590, 0x250591, 0x270592, 0x290593, 0x2b0594, 0x2d0494, 0x2f0495, 0x310496, 0x330497, 0x340498, 0x360498, 0x380499, 0x3a049a, 0x3b039a, 0x3d039b, 0x3f039c, 0x40039c, 0x42039d, 0x44039e, 0x45039e, 0x47029f, 0x49029f, 0x4a02a0, 0x4c02a1, 0x4e02a1, 0x4f02a2, 0x5101a2, 0x5201a3, 0x5401a3, 0x5601a3, 0x5701a4, 0x5901a4, 0x5a00a5, 0x5c00a5, 0x5e00a5, 0x5f00a6, 0x6100a6, 0x6200a6, 0x6400a7, 0x6500a7, 0x6700a7, 0x6800a7, 0x6a00a7, 0x6c00a8, 0x6d00a8, 0x6f00a8, 0x7000a8, 0x7200a8, 0x7300a8, 0x7500a8, 0x7601a8, 0x7801a8, 0x7901a8, 0x7b02a8, 0x7c02a7, 0x7e03a7, 0x7f03a7, 0x8104a7, 0x8204a7, 0x8405a6, 0x8506a6, 0x8607a6, 0x8807a5, 0x8908a5, 0x8b09a4, 0x8c0aa4, 0x8e0ca4, 0x8f0da3, 0x900ea3, 0x920fa2, 0x9310a1, 0x9511a1, 0x9612a0, 0x9713a0, 0x99149f, 0x9a159e, 0x9b179e, 0x9d189d, 0x9e199c, 0x9f1a9b, 0xa01b9b, 0xa21c9a, 0xa31d99, 0xa41e98, 0xa51f97, 0xa72197, 0xa82296, 0xa92395, 0xaa2494, 0xac2593, 0xad2692, 0xae2791, 0xaf2890, 0xb02a8f, 0xb12b8f, 0xb22c8e, 0xb42d8d, 0xb52e8c, 0xb62f8b, 0xb7308a, 0xb83289, 0xb93388, 0xba3487, 0xbb3586, 0xbc3685, 0xbd3784, 0xbe3883, 0xbf3982, 0xc03b81, 0xc13c80, 0xc23d80, 0xc33e7f, 0xc43f7e, 0xc5407d, 0xc6417c, 0xc7427b, 0xc8447a, 0xc94579, 0xca4678, 0xcb4777, 0xcc4876, 0xcd4975, 0xce4a75, 0xcf4b74, 0xd04d73, 0xd14e72, 0xd14f71, 0xd25070, 0xd3516f, 0xd4526e, 0xd5536d, 0xd6556d, 0xd7566c, 0xd7576b, 0xd8586a, 0xd95969, 0xda5a68, 0xdb5b67, 0xdc5d66, 0xdc5e66, 0xdd5f65, 0xde6064, 0xdf6163, 0xdf6262, 0xe06461, 0xe16560, 0xe26660, 0xe3675f, 0xe3685e, 0xe46a5d, 0xe56b5c, 0xe56c5b, 0xe66d5a, 0xe76e5a, 0xe87059, 0xe87158, 0xe97257, 0xea7356, 0xea7455, 0xeb7654, 0xec7754, 0xec7853, 0xed7952, 0xed7b51, 0xee7c50, 0xef7d4f, 0xef7e4e, 0xf0804d, 0xf0814d, 0xf1824c, 0xf2844b, 0xf2854a, 0xf38649, 0xf38748, 0xf48947, 0xf48a47, 0xf58b46, 0xf58d45, 0xf68e44, 0xf68f43, 0xf69142, 0xf79241, 0xf79341, 0xf89540, 0xf8963f, 0xf8983e, 0xf9993d, 0xf99a3c, 0xfa9c3b, 0xfa9d3a, 0xfa9f3a, 0xfaa039, 0xfba238, 0xfba337, 0xfba436, 0xfca635, 0xfca735, 0xfca934, 0xfcaa33, 0xfcac32, 0xfcad31, 0xfdaf31, 0xfdb030, 0xfdb22f, 0xfdb32e, 0xfdb52d, 0xfdb62d, 0xfdb82c, 0xfdb92b, 0xfdbb2b, 0xfdbc2a, 0xfdbe29, 0xfdc029, 0xfdc128, 0xfdc328, 0xfdc427, 0xfdc626, 0xfcc726, 0xfcc926, 0xfccb25, 0xfccc25, 0xfcce25, 0xfbd024, 0xfbd124, 0xfbd324, 0xfad524, 0xfad624, 0xfad824, 0xf9d924, 0xf9db24, 0xf8dd24, 0xf8df24, 0xf7e024, 0xf7e225, 0xf6e425, 0xf6e525, 0xf5e726, 0xf5e926, 0xf4ea26, 0xf3ec26, 0xf3ee26, 0xf2f026, 0xf2f126, 0xf1f326, 0xf0f525, 0xf0f623, 0xeff821]
  },
  Viridis: {
    Viridis3: [0x440154, 0x208f8c, 0xfde724],
    Viridis4: [0x440154, 0x30678d, 0x35b778, 0xfde724],
    Viridis5: [0x440154, 0x3b518a, 0x208f8c, 0x5bc862, 0xfde724],
    Viridis6: [0x440154, 0x404387, 0x29788e, 0x22a784, 0x79d151, 0xfde724],
    Viridis7: [0x440154, 0x443982, 0x30678d, 0x208f8c, 0x35b778, 0x8dd644, 0xfde724],
    Viridis8: [0x440154, 0x46317e, 0x365a8c, 0x277e8e, 0x1ea087, 0x49c16d, 0x9dd93a, 0xfde724],
    Viridis9: [0x440154, 0x472b7a, 0x3b518a, 0x2c718e, 0x208f8c, 0x27ad80, 0x5bc862, 0xaadb32, 0xfde724],
    Viridis10: [0x440154, 0x472777, 0x3e4989, 0x30678d, 0x25828e, 0x1e9c89, 0x35b778, 0x6bcd59, 0xb2dd2c, 0xfde724],
    Viridis11: [0x440154, 0x482374, 0x404387, 0x345e8d, 0x29788e, 0x208f8c, 0x22a784, 0x42be71, 0x79d151, 0xbade27, 0xfde724],
    Viridis256: [0x440154, 0x440255, 0x440357, 0x450558, 0x45065a, 0x45085b, 0x46095c, 0x460b5e, 0x460c5f, 0x460e61, 0x470f62, 0x471163, 0x471265, 0x471466, 0x471567, 0x471669, 0x47186a, 0x48196b, 0x481a6c, 0x481c6e, 0x481d6f, 0x481e70, 0x482071, 0x482172, 0x482273, 0x482374, 0x472575, 0x472676, 0x472777, 0x472878, 0x472a79, 0x472b7a, 0x472c7b, 0x462d7c, 0x462f7c, 0x46307d, 0x46317e, 0x45327f, 0x45347f, 0x453580, 0x453681, 0x443781, 0x443982, 0x433a83, 0x433b83, 0x433c84, 0x423d84, 0x423e85, 0x424085, 0x414186, 0x414286, 0x404387, 0x404487, 0x3f4587, 0x3f4788, 0x3e4888, 0x3e4989, 0x3d4a89, 0x3d4b89, 0x3d4c89, 0x3c4d8a, 0x3c4e8a, 0x3b508a, 0x3b518a, 0x3a528b, 0x3a538b, 0x39548b, 0x39558b, 0x38568b, 0x38578c, 0x37588c, 0x37598c, 0x365a8c, 0x365b8c, 0x355c8c, 0x355d8c, 0x345e8d, 0x345f8d, 0x33608d, 0x33618d, 0x32628d, 0x32638d, 0x31648d, 0x31658d, 0x31668d, 0x30678d, 0x30688d, 0x2f698d, 0x2f6a8d, 0x2e6b8e, 0x2e6c8e, 0x2e6d8e, 0x2d6e8e, 0x2d6f8e, 0x2c708e, 0x2c718e, 0x2c728e, 0x2b738e, 0x2b748e, 0x2a758e, 0x2a768e, 0x2a778e, 0x29788e, 0x29798e, 0x287a8e, 0x287a8e, 0x287b8e, 0x277c8e, 0x277d8e, 0x277e8e, 0x267f8e, 0x26808e, 0x26818e, 0x25828e, 0x25838d, 0x24848d, 0x24858d, 0x24868d, 0x23878d, 0x23888d, 0x23898d, 0x22898d, 0x228a8d, 0x228b8d, 0x218c8d, 0x218d8c, 0x218e8c, 0x208f8c, 0x20908c, 0x20918c, 0x1f928c, 0x1f938b, 0x1f948b, 0x1f958b, 0x1f968b, 0x1e978a, 0x1e988a, 0x1e998a, 0x1e998a, 0x1e9a89, 0x1e9b89, 0x1e9c89, 0x1e9d88, 0x1e9e88, 0x1e9f88, 0x1ea087, 0x1fa187, 0x1fa286, 0x1fa386, 0x20a485, 0x20a585, 0x21a685, 0x21a784, 0x22a784, 0x23a883, 0x23a982, 0x24aa82, 0x25ab81, 0x26ac81, 0x27ad80, 0x28ae7f, 0x29af7f, 0x2ab07e, 0x2bb17d, 0x2cb17d, 0x2eb27c, 0x2fb37b, 0x30b47a, 0x32b57a, 0x33b679, 0x35b778, 0x36b877, 0x38b976, 0x39b976, 0x3bba75, 0x3dbb74, 0x3ebc73, 0x40bd72, 0x42be71, 0x44be70, 0x45bf6f, 0x47c06e, 0x49c16d, 0x4bc26c, 0x4dc26b, 0x4fc369, 0x51c468, 0x53c567, 0x55c666, 0x57c665, 0x59c764, 0x5bc862, 0x5ec961, 0x60c960, 0x62ca5f, 0x64cb5d, 0x67cc5c, 0x69cc5b, 0x6bcd59, 0x6dce58, 0x70ce56, 0x72cf55, 0x74d054, 0x77d052, 0x79d151, 0x7cd24f, 0x7ed24e, 0x81d34c, 0x83d34b, 0x86d449, 0x88d547, 0x8bd546, 0x8dd644, 0x90d643, 0x92d741, 0x95d73f, 0x97d83e, 0x9ad83c, 0x9dd93a, 0x9fd938, 0xa2da37, 0xa5da35, 0xa7db33, 0xaadb32, 0xaddc30, 0xafdc2e, 0xb2dd2c, 0xb5dd2b, 0xb7dd29, 0xbade27, 0xbdde26, 0xbfdf24, 0xc2df22, 0xc5df21, 0xc7e01f, 0xcae01e, 0xcde01d, 0xcfe11c, 0xd2e11b, 0xd4e11a, 0xd7e219, 0xdae218, 0xdce218, 0xdfe318, 0xe1e318, 0xe4e318, 0xe7e419, 0xe9e419, 0xece41a, 0xeee51b, 0xf1e51c, 0xf3e51e, 0xf6e61f, 0xf8e621, 0xfae622, 0xfde724]
  },
  Accent: {
    Accent3: [0x7fc97f, 0xbeaed4, 0xfdc086],
    Accent4: [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99],
    Accent5: [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0],
    Accent6: [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f],
    Accent7: [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17],
    Accent8: [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17, 0x666666]
  },
  Dark2: {
    Dark2_3: [0x1b9e77, 0xd95f02, 0x7570b3],
    Dark2_4: [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a],
    Dark2_5: [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e],
    Dark2_6: [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02],
    Dark2_7: [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d],
    Dark2_8: [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666]
  },
  Paired: {
    Paired3: [0xa6cee3, 0x1f78b4, 0xb2df8a],
    Paired4: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c],
    Paired5: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99],
    Paired6: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c],
    Paired7: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f],
    Paired8: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00],
    Paired9: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6],
    Paired10: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a],
    Paired11: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99],
    Paired12: [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99, 0xb15928]
  },
  Pastel1: {
    Pastel1_3: [0xfbb4ae, 0xb3cde3, 0xccebc5],
    Pastel1_4: [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4],
    Pastel1_5: [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6],
    Pastel1_6: [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc],
    Pastel1_7: [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd],
    Pastel1_8: [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec],
    Pastel1_9: [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec, 0xf2f2f2]
  },
  Pastel2: {
    Pastel2_3: [0xb3e2cd, 0xfdcdac, 0xcbd5e8],
    Pastel2_4: [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4],
    Pastel2_5: [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9],
    Pastel2_6: [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae],
    Pastel2_7: [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc],
    Pastel2_8: [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc, 0xcccccc]
  },
  Set1: {
    Set1_3: [0xe41a1c, 0x377eb8, 0x4daf4a],
    Set1_4: [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3],
    Set1_5: [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00],
    Set1_6: [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33],
    Set1_7: [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628],
    Set1_8: [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf],
    Set1_9: [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999]
  },
  Set2: {
    Set2_3: [0x66c2a5, 0xfc8d62, 0x8da0cb],
    Set2_4: [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3],
    Set2_5: [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854],
    Set2_6: [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f],
    Set2_7: [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494],
    Set2_8: [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3]
  },
  Set3: {
    Set3_3: [0x8dd3c7, 0xffffb3, 0xbebada],
    Set3_4: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072],
    Set3_5: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3],
    Set3_6: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462],
    Set3_7: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69],
    Set3_8: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5],
    Set3_9: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9],
    Set3_10: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd],
    Set3_11: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5],
    Set3_12: [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5, 0xffed6f]
  }
};


/* License regarding the Viridis, Magma, Plasma and Inferno color maps */

module.exports = _.extend({}, palettes, palettes.YlGn, palettes.YlGnBu, palettes.GnBu, palettes.BuGn, palettes.PuBuGn, palettes.PuBu, palettes.BuPu, palettes.RdPu, palettes.PuRd, palettes.OrRd, palettes.YlOrRd, palettes.YlOrBr, palettes.Purples, palettes.Blues, palettes.Greens, palettes.Oranges, palettes.Reds, palettes.Greys, palettes.PuOr, palettes.BrBG, palettes.PRGn, palettes.PiYG, palettes.RdBu, palettes.RdGy, palettes.RdYlBu, palettes.Spectral, palettes.RdYlGn, palettes.Inferno, palettes.Magma, palettes.Plasma, palettes.Viridis);

},{"underscore":"underscore"}],"util/bezier":[function(require,module,exports){
var arc_to_bezier, segment_to_bezier;

segment_to_bezier = function(cx, cy, th0, th1, rx, ry, sin_th, cos_th) {
  var a00, a01, a10, a11, t, th_half, x1, x2, x3, y1, y2, y3;
  a00 = cos_th * rx;
  a01 = -sin_th * ry;
  a10 = sin_th * rx;
  a11 = cos_th * ry;
  th_half = 0.5 * (th1 - th0);
  t = (8 / 3) * Math.sin(th_half * 0.5) * Math.sin(th_half * 0.5) / Math.sin(th_half);
  x1 = cx + Math.cos(th0) - t * Math.sin(th0);
  y1 = cy + Math.sin(th0) + t * Math.cos(th0);
  x3 = cx + Math.cos(th1);
  y3 = cy + Math.sin(th1);
  x2 = x3 + t * Math.sin(th1);
  y2 = y3 - t * Math.cos(th1);
  return [a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3];
};

arc_to_bezier = function(ox, oy, radx, rady, rotateX, large, sweep, x, y) {
  var a00, a01, a10, a11, cos_th, d, i, pl, px, py, result, rx, ry, segments, sfactor, sfactor_sq, sin_th, th, th0, th1, th2, th3, th_arc, x0, x1, xc, y0, y1, yc;
  th = rotateX * (Math.PI / 180);
  sin_th = Math.sin(th);
  cos_th = Math.cos(th);
  rx = Math.abs(radx);
  ry = Math.abs(rady);
  px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5;
  py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5;
  pl = (px * px) / (rx * rx) + (py * py) / (ry * ry);
  if (pl > 1) {
    pl = Math.sqrt(pl);
    rx *= pl;
    ry *= pl;
  }
  a00 = cos_th / rx;
  a01 = sin_th / rx;
  a10 = -sin_th / ry;
  a11 = cos_th / ry;
  x0 = a00 * ox + a01 * oy;
  y0 = a10 * ox + a11 * oy;
  x1 = a00 * x + a01 * y;
  y1 = a10 * x + a11 * y;
  d = (x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0);
  sfactor_sq = 1 / d - 0.25;
  if (sfactor_sq < 0) {
    sfactor_sq = 0;
  }
  sfactor = Math.sqrt(sfactor_sq);
  if (sweep === large) {
    sfactor = -sfactor;
  }
  xc = 0.5 * (x0 + x1) - sfactor * (y1 - y0);
  yc = 0.5 * (y0 + y1) + sfactor * (x1 - x0);
  th0 = Math.atan2(y0 - yc, x0 - xc);
  th1 = Math.atan2(y1 - yc, x1 - xc);
  th_arc = th1 - th0;
  if (th_arc < 0 && sweep === 1) {
    th_arc += 2 * Math.PI;
  } else if (th_arc > 0 && sweep === 0) {
    th_arc -= 2 * Math.PI;
  }
  segments = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001)));
  result = (function() {
    var j, ref, results;
    results = [];
    for (i = j = 0, ref = segments; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      th2 = th0 + i * th_arc / segments;
      th3 = th0 + (i + 1) * th_arc / segments;
      results.push(segment_to_bezier(xc, yc, th2, th3, rx, ry, sin_th, cos_th));
    }
    return results;
  })();
  return result;
};

module.exports = {
  arc_to_bezier: arc_to_bezier,
  segment_to_bezier: segment_to_bezier
};

},{}],"util/util":[function(require,module,exports){
var Numbro, SPrintf, _, _format_number, get_indices, replace_placeholders;

_ = require("underscore");

SPrintf = require("sprintf");

Numbro = require("numbro");

_format_number = function(number) {
  var format;
  if (_.isNumber(number)) {
    format = (function() {
      switch (false) {
        case Math.floor(number) !== number:
          return "%d";
        case !(Math.abs(number) > 0.1 && Math.abs(number) < 1000):
          return "%0.3f";
        default:
          return "%0.3e";
      }
    })();
    return SPrintf.sprintf(format, number);
  } else {
    return "" + number;
  }
};

replace_placeholders = function(string, data_source, i, special_vars) {
  if (special_vars == null) {
    special_vars = {};
  }
  string = string.replace(/(^|[^\$])\$(\w+)/g, (function(_this) {
    return function(match, prefix, name) {
      return prefix + "@$" + name;
    };
  })(this));
  string = string.replace(/(^|[^@])@(?:(\$?\w+)|{([^{}]+)})(?:{([^{}]+)})?/g, (function(_this) {
    return function(match, prefix, name, long_name, format) {
      var ref, replacement, value;
      name = long_name != null ? long_name : name;
      value = name[0] === "$" ? special_vars[name.substring(1)] : (ref = data_source.get_column(name)) != null ? ref[i] : void 0;
      replacement = value == null ? "???" : format != null ? Numbro.format(value, format) : _format_number(value);
      return "" + prefix + (_.escape(replacement));
    };
  })(this));
  return string;
};

get_indices = function(data_source) {
  var selected;
  selected = data_source.get("selected");
  if (selected['0d'].glyph) {
    return selected['0d'].indices;
  } else if (selected['1d'].indices.length > 0) {
    return selected['1d'].indices;
  } else if (selected['2d'].indices.length > 0) {
    return selected['2d'].indices;
  } else {
    return [];
  }
};

module.exports = {
  replace_placeholders: replace_placeholders,
  get_indices: get_indices
};

},{"numbro":"numbro/numbro","sprintf":"sprintf","underscore":"underscore"}],"version":[function(require,module,exports){
var version;

version = '0.12.0';

module.exports = version;

},{}],"backbone":[function(require,module,exports){
(function (global){
//     Backbone.js 1.3.3

//     (c) 2010-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Backbone may be freely distributed under the MIT license.
//     For all details and documentation:
//     http://backbonejs.org

(function(factory) {

  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root = (typeof self == 'object' && self.self === self && self) ||
            (typeof global == 'object' && global.global === global && global);

  // Set up Backbone appropriately for the environment. Start with AMD.
  if (typeof define === 'function' && define.amd) {
    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    });

  // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else if (typeof exports !== 'undefined') {
    var _ = require('underscore'), $;
    try { $ = require('jquery'); } catch (e) {}
    factory(root, exports, _, $);

  // Finally, as a browser global.
  } else {
    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
  }

})(function(root, Backbone, _, $) {

  // Initial Setup
  // -------------

  // Save the previous value of the `Backbone` variable, so that it can be
  // restored later on, if `noConflict` is used.
  var previousBackbone = root.Backbone;

  // Create a local reference to a common array method we'll want to use later.
  var slice = Array.prototype.slice;

  // Current version of the library. Keep in sync with `package.json`.
  Backbone.VERSION = '1.3.3';

  // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns
  // the `$` variable.
  Backbone.$ = $;

  // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
  // to its previous owner. Returns a reference to this Backbone object.
  Backbone.noConflict = function() {
    root.Backbone = previousBackbone;
    return this;
  };

  // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
  // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
  // set a `X-Http-Method-Override` header.
  Backbone.emulateHTTP = false;

  // Turn on `emulateJSON` to support legacy servers that can't deal with direct
  // `application/json` requests ... this will encode the body as
  // `application/x-www-form-urlencoded` instead and will send the model in a
  // form param named `model`.
  Backbone.emulateJSON = false;

  // Proxy Backbone class methods to Underscore functions, wrapping the model's
  // `attributes` object or collection's `models` array behind the scenes.
  //
  // collection.filter(function(model) { return model.get('age') > 10 });
  // collection.each(this.addView);
  //
  // `Function#apply` can be slow so we use the method's arg count, if we know it.
  var addMethod = function(length, method, attribute) {
    switch (length) {
      case 1: return function() {
        return _[method](this[attribute]);
      };
      case 2: return function(value) {
        return _[method](this[attribute], value);
      };
      case 3: return function(iteratee, context) {
        return _[method](this[attribute], cb(iteratee, this), context);
      };
      case 4: return function(iteratee, defaultVal, context) {
        return _[method](this[attribute], cb(iteratee, this), defaultVal, context);
      };
      default: return function() {
        var args = slice.call(arguments);
        args.unshift(this[attribute]);
        return _[method].apply(_, args);
      };
    }
  };
  var addUnderscoreMethods = function(Class, methods, attribute) {
    _.each(methods, function(length, method) {
      if (_[method]) Class.prototype[method] = addMethod(length, method, attribute);
    });
  };

  // Support `collection.sortBy('attr')` and `collection.findWhere({id: 1})`.
  var cb = function(iteratee, instance) {
    if (_.isFunction(iteratee)) return iteratee;
    if (_.isObject(iteratee) && !instance._isModel(iteratee)) return modelMatcher(iteratee);
    if (_.isString(iteratee)) return function(model) { return model.get(iteratee); };
    return iteratee;
  };
  var modelMatcher = function(attrs) {
    var matcher = _.matches(attrs);
    return function(model) {
      return matcher(model.attributes);
    };
  };

  // Backbone.Events
  // ---------------

  // A module that can be mixed in to *any object* in order to provide it with
  // a custom event channel. You may bind a callback to an event with `on` or
  // remove with `off`; `trigger`-ing an event fires all callbacks in
  // succession.
  //
  //     var object = {};
  //     _.extend(object, Backbone.Events);
  //     object.on('expand', function(){ alert('expanded'); });
  //     object.trigger('expand');
  //
  var Events = Backbone.Events = {};

  // Regular expression used to split event strings.
  var eventSplitter = /\s+/;

  // Iterates over the standard `event, callback` (as well as the fancy multiple
  // space-separated events `"change blur", callback` and jQuery-style event
  // maps `{event: callback}`).
  var eventsApi = function(iteratee, events, name, callback, opts) {
    var i = 0, names;
    if (name && typeof name === 'object') {
      // Handle event maps.
      if (callback !== void 0 && 'context' in opts && opts.context === void 0) opts.context = callback;
      for (names = _.keys(name); i < names.length ; i++) {
        events = eventsApi(iteratee, events, names[i], name[names[i]], opts);
      }
    } else if (name && eventSplitter.test(name)) {
      // Handle space-separated event names by delegating them individually.
      for (names = name.split(eventSplitter); i < names.length; i++) {
        events = iteratee(events, names[i], callback, opts);
      }
    } else {
      // Finally, standard events.
      events = iteratee(events, name, callback, opts);
    }
    return events;
  };

  // Bind an event to a `callback` function. Passing `"all"` will bind
  // the callback to all events fired.
  Events.on = function(name, callback, context) {
    return internalOn(this, name, callback, context);
  };

  // Guard the `listening` argument from the public API.
  var internalOn = function(obj, name, callback, context, listening) {
    obj._events = eventsApi(onApi, obj._events || {}, name, callback, {
      context: context,
      ctx: obj,
      listening: listening
    });

    if (listening) {
      var listeners = obj._listeners || (obj._listeners = {});
      listeners[listening.id] = listening;
    }

    return obj;
  };

  // Inversion-of-control versions of `on`. Tell *this* object to listen to
  // an event in another object... keeping track of what it's listening to
  // for easier unbinding later.
  Events.listenTo = function(obj, name, callback) {
    if (!obj) return this;
    var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
    var listeningTo = this._listeningTo || (this._listeningTo = {});
    var listening = listeningTo[id];

    // This object is not listening to any other events on `obj` yet.
    // Setup the necessary references to track the listening callbacks.
    if (!listening) {
      var thisId = this._listenId || (this._listenId = _.uniqueId('l'));
      listening = listeningTo[id] = {obj: obj, objId: id, id: thisId, listeningTo: listeningTo, count: 0};
    }

    // Bind callbacks on obj, and keep track of them on listening.
    internalOn(obj, name, callback, this, listening);
    return this;
  };

  // The reducing API that adds a callback to the `events` object.
  var onApi = function(events, name, callback, options) {
    if (callback) {
      var handlers = events[name] || (events[name] = []);
      var context = options.context, ctx = options.ctx, listening = options.listening;
      if (listening) listening.count++;

      handlers.push({callback: callback, context: context, ctx: context || ctx, listening: listening});
    }
    return events;
  };

  // Remove one or many callbacks. If `context` is null, removes all
  // callbacks with that function. If `callback` is null, removes all
  // callbacks for the event. If `name` is null, removes all bound
  // callbacks for all events.
  Events.off = function(name, callback, context) {
    if (!this._events) return this;
    this._events = eventsApi(offApi, this._events, name, callback, {
      context: context,
      listeners: this._listeners
    });
    return this;
  };

  // Tell this object to stop listening to either specific events ... or
  // to every object it's currently listening to.
  Events.stopListening = function(obj, name, callback) {
    var listeningTo = this._listeningTo;
    if (!listeningTo) return this;

    var ids = obj ? [obj._listenId] : _.keys(listeningTo);

    for (var i = 0; i < ids.length; i++) {
      var listening = listeningTo[ids[i]];

      // If listening doesn't exist, this object is not currently
      // listening to obj. Break out early.
      if (!listening) break;

      listening.obj.off(name, callback, this);
    }

    return this;
  };

  // The reducing API that removes a callback from the `events` object.
  var offApi = function(events, name, callback, options) {
    if (!events) return;

    var i = 0, listening;
    var context = options.context, listeners = options.listeners;

    // Delete all events listeners and "drop" events.
    if (!name && !callback && !context) {
      var ids = _.keys(listeners);
      for (; i < ids.length; i++) {
        listening = listeners[ids[i]];
        delete listeners[listening.id];
        delete listening.listeningTo[listening.objId];
      }
      return;
    }

    var names = name ? [name] : _.keys(events);
    for (; i < names.length; i++) {
      name = names[i];
      var handlers = events[name];

      // Bail out if there are no events stored.
      if (!handlers) break;

      // Replace events if there are any remaining.  Otherwise, clean up.
      var remaining = [];
      for (var j = 0; j < handlers.length; j++) {
        var handler = handlers[j];
        if (
          callback && callback !== handler.callback &&
            callback !== handler.callback._callback ||
              context && context !== handler.context
        ) {
          remaining.push(handler);
        } else {
          listening = handler.listening;
          if (listening && --listening.count === 0) {
            delete listeners[listening.id];
            delete listening.listeningTo[listening.objId];
          }
        }
      }

      // Update tail event if the list has any events.  Otherwise, clean up.
      if (remaining.length) {
        events[name] = remaining;
      } else {
        delete events[name];
      }
    }
    return events;
  };

  // Bind an event to only be triggered a single time. After the first time
  // the callback is invoked, its listener will be removed. If multiple events
  // are passed in using the space-separated syntax, the handler will fire
  // once for each event, not once for a combination of all events.
  Events.once = function(name, callback, context) {
    // Map the event into a `{event: once}` object.
    var events = eventsApi(onceMap, {}, name, callback, _.bind(this.off, this));
    if (typeof name === 'string' && context == null) callback = void 0;
    return this.on(events, callback, context);
  };

  // Inversion-of-control versions of `once`.
  Events.listenToOnce = function(obj, name, callback) {
    // Map the event into a `{event: once}` object.
    var events = eventsApi(onceMap, {}, name, callback, _.bind(this.stopListening, this, obj));
    return this.listenTo(obj, events);
  };

  // Reduces the event callbacks into a map of `{event: onceWrapper}`.
  // `offer` unbinds the `onceWrapper` after it has been called.
  var onceMap = function(map, name, callback, offer) {
    if (callback) {
      var once = map[name] = _.once(function() {
        offer(name, once);
        callback.apply(this, arguments);
      });
      once._callback = callback;
    }
    return map;
  };

  // Trigger one or many events, firing all bound callbacks. Callbacks are
  // passed the same arguments as `trigger` is, apart from the event name
  // (unless you're listening on `"all"`, which will cause your callback to
  // receive the true name of the event as the first argument).
  Events.trigger = function(name) {
    if (!this._events) return this;

    var length = Math.max(0, arguments.length - 1);
    var args = Array(length);
    for (var i = 0; i < length; i++) args[i] = arguments[i + 1];

    eventsApi(triggerApi, this._events, name, void 0, args);
    return this;
  };

  // Handles triggering the appropriate event callbacks.
  var triggerApi = function(objEvents, name, callback, args) {
    if (objEvents) {
      var events = objEvents[name];
      var allEvents = objEvents.all;
      if (events && allEvents) allEvents = allEvents.slice();
      if (events) triggerEvents(events, args);
      if (allEvents) triggerEvents(allEvents, [name].concat(args));
    }
    return objEvents;
  };

  // A difficult-to-believe, but optimized internal dispatch function for
  // triggering events. Tries to keep the usual cases speedy (most internal
  // Backbone events have 3 arguments).
  var triggerEvents = function(events, args) {
    var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
    switch (args.length) {
      case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
      case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
      case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
      case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
      default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
    }
  };

  // Aliases for backwards compatibility.
  Events.bind   = Events.on;
  Events.unbind = Events.off;

  // Allow the `Backbone` object to serve as a global event bus, for folks who
  // want global "pubsub" in a convenient place.
  _.extend(Backbone, Events);

  // Backbone.Model
  // --------------

  // Backbone **Models** are the basic data object in the framework --
  // frequently representing a row in a table in a database on your server.
  // A discrete chunk of data and a bunch of useful, related methods for
  // performing computations and transformations on that data.

  // Create a new model with the specified attributes. A client id (`cid`)
  // is automatically generated and assigned for you.
  var Model = Backbone.Model = function(attributes, options) {
    var attrs = attributes || {};
    options || (options = {});
    this.cid = _.uniqueId(this.cidPrefix);
    this.attributes = {};
    if (options.collection) this.collection = options.collection;
    if (options.parse) attrs = this.parse(attrs, options) || {};
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);
    this.set(attrs, options);
    this.changed = {};
    this.initialize.apply(this, arguments);
  };

  // Attach all inheritable methods to the Model prototype.
  _.extend(Model.prototype, Events, {

    // A hash of attributes whose current and previous value differ.
    changed: null,

    // The value returned during the last failed validation.
    validationError: null,

    // The default name for the JSON `id` attribute is `"id"`. MongoDB and
    // CouchDB users may want to set this to `"_id"`.
    idAttribute: 'id',

    // The prefix is used to create the client id which is used to identify models locally.
    // You may want to override this if you're experiencing name clashes with model ids.
    cidPrefix: 'c',

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Return a copy of the model's `attributes` object.
    toJSON: function(options) {
      return _.clone(this.attributes);
    },

    // Proxy `Backbone.sync` by default -- but override this if you need
    // custom syncing semantics for *this* particular model.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Get the value of an attribute.
    get: function(attr) {
      return this.attributes[attr];
    },

    // Get the HTML-escaped value of an attribute.
    escape: function(attr) {
      return _.escape(this.get(attr));
    },

    // Returns `true` if the attribute contains a value that is not null
    // or undefined.
    has: function(attr) {
      return this.get(attr) != null;
    },

    // Special-cased proxy to underscore's `_.matches` method.
    matches: function(attrs) {
      return !!_.iteratee(attrs, this)(this.attributes);
    },

    // Set a hash of model attributes on the object, firing `"change"`. This is
    // the core primitive operation of a model, updating the data and notifying
    // anyone who needs to know about the change in state. The heart of the beast.
    set: function(key, val, options) {
      if (key == null) return this;

      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options || (options = {});

      // Run validation.
      if (!this._validate(attrs, options)) return false;

      // Extract attributes and options.
      var unset      = options.unset;
      var silent     = options.silent;
      var changes    = [];
      var changing   = this._changing;
      this._changing = true;

      if (!changing) {
        this._previousAttributes = _.clone(this.attributes);
        this.changed = {};
      }

      var current = this.attributes;
      var changed = this.changed;
      var prev    = this._previousAttributes;

      // For each `set` attribute, update or delete the current value.
      for (var attr in attrs) {
        val = attrs[attr];
        if (!_.isEqual(current[attr], val)) changes.push(attr);
        if (!_.isEqual(prev[attr], val)) {
          changed[attr] = val;
        } else {
          delete changed[attr];
        }
        unset ? delete current[attr] : current[attr] = val;
      }

      // Update the `id`.
      if (this.idAttribute in attrs) this.id = this.get(this.idAttribute);

      // Trigger all relevant attribute changes.
      if (!silent) {
        if (changes.length) this._pending = options;
        for (var i = 0; i < changes.length; i++) {
          this.trigger('change:' + changes[i], this, current[changes[i]], options);
        }
      }

      // You might be wondering why there's a `while` loop here. Changes can
      // be recursively nested within `"change"` events.
      if (changing) return this;
      if (!silent) {
        while (this._pending) {
          options = this._pending;
          this._pending = false;
          this.trigger('change', this, options);
        }
      }
      this._pending = false;
      this._changing = false;
      return this;
    },

    // Remove an attribute from the model, firing `"change"`. `unset` is a noop
    // if the attribute doesn't exist.
    unset: function(attr, options) {
      return this.set(attr, void 0, _.extend({}, options, {unset: true}));
    },

    // Clear all attributes on the model, firing `"change"`.
    clear: function(options) {
      var attrs = {};
      for (var key in this.attributes) attrs[key] = void 0;
      return this.set(attrs, _.extend({}, options, {unset: true}));
    },

    // Determine if the model has changed since the last `"change"` event.
    // If you specify an attribute name, determine if that attribute has changed.
    hasChanged: function(attr) {
      if (attr == null) return !_.isEmpty(this.changed);
      return _.has(this.changed, attr);
    },

    // Return an object containing all the attributes that have changed, or
    // false if there are no changed attributes. Useful for determining what
    // parts of a view need to be updated and/or what attributes need to be
    // persisted to the server. Unset attributes will be set to undefined.
    // You can also pass an attributes object to diff against the model,
    // determining if there *would be* a change.
    changedAttributes: function(diff) {
      if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
      var old = this._changing ? this._previousAttributes : this.attributes;
      var changed = {};
      for (var attr in diff) {
        var val = diff[attr];
        if (_.isEqual(old[attr], val)) continue;
        changed[attr] = val;
      }
      return _.size(changed) ? changed : false;
    },

    // Get the previous value of an attribute, recorded at the time the last
    // `"change"` event was fired.
    previous: function(attr) {
      if (attr == null || !this._previousAttributes) return null;
      return this._previousAttributes[attr];
    },

    // Get all of the attributes of the model at the time of the previous
    // `"change"` event.
    previousAttributes: function() {
      return _.clone(this._previousAttributes);
    },

    // Fetch the model from the server, merging the response with the model's
    // local attributes. Any changed attributes will trigger a "change" event.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var model = this;
      var success = options.success;
      options.success = function(resp) {
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (!model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Set a hash of model attributes, and sync the model to the server.
    // If the server returns an attributes hash that differs, the model's
    // state will be `set` again.
    save: function(key, val, options) {
      // Handle both `"key", value` and `{key: value}` -style arguments.
      var attrs;
      if (key == null || typeof key === 'object') {
        attrs = key;
        options = val;
      } else {
        (attrs = {})[key] = val;
      }

      options = _.extend({validate: true, parse: true}, options);
      var wait = options.wait;

      // If we're not waiting and attributes exist, save acts as
      // `set(attr).save(null, opts)` with validation. Otherwise, check if
      // the model will be valid when the attributes, if any, are set.
      if (attrs && !wait) {
        if (!this.set(attrs, options)) return false;
      } else if (!this._validate(attrs, options)) {
        return false;
      }

      // After a successful server-side save, the client is (optionally)
      // updated with the server-side state.
      var model = this;
      var success = options.success;
      var attributes = this.attributes;
      options.success = function(resp) {
        // Ensure attributes are restored during synchronous saves.
        model.attributes = attributes;
        var serverAttrs = options.parse ? model.parse(resp, options) : resp;
        if (wait) serverAttrs = _.extend({}, attrs, serverAttrs);
        if (serverAttrs && !model.set(serverAttrs, options)) return false;
        if (success) success.call(options.context, model, resp, options);
        model.trigger('sync', model, resp, options);
      };
      wrapError(this, options);

      // Set temporary attributes if `{wait: true}` to properly find new ids.
      if (attrs && wait) this.attributes = _.extend({}, attributes, attrs);

      var method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
      if (method === 'patch' && !options.attrs) options.attrs = attrs;
      var xhr = this.sync(method, this, options);

      // Restore attributes.
      this.attributes = attributes;

      return xhr;
    },

    // Destroy this model on the server if it was already persisted.
    // Optimistically removes the model from its collection, if it has one.
    // If `wait: true` is passed, waits for the server to respond before removal.
    destroy: function(options) {
      options = options ? _.clone(options) : {};
      var model = this;
      var success = options.success;
      var wait = options.wait;

      var destroy = function() {
        model.stopListening();
        model.trigger('destroy', model, model.collection, options);
      };

      options.success = function(resp) {
        if (wait) destroy();
        if (success) success.call(options.context, model, resp, options);
        if (!model.isNew()) model.trigger('sync', model, resp, options);
      };

      var xhr = false;
      if (this.isNew()) {
        _.defer(options.success);
      } else {
        wrapError(this, options);
        xhr = this.sync('delete', this, options);
      }
      if (!wait) destroy();
      return xhr;
    },

    // Default URL for the model's representation on the server -- if you're
    // using Backbone's restful methods, override this to change the endpoint
    // that will be called.
    url: function() {
      var base =
        _.result(this, 'urlRoot') ||
        _.result(this.collection, 'url') ||
        urlError();
      if (this.isNew()) return base;
      var id = this.get(this.idAttribute);
      return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id);
    },

    // **parse** converts a response into the hash of attributes to be `set` on
    // the model. The default implementation is just to pass the response along.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new model with identical attributes to this one.
    clone: function() {
      return new this.constructor(this.attributes);
    },

    // A model is new if it has never been saved to the server, and lacks an id.
    isNew: function() {
      return !this.has(this.idAttribute);
    },

    // Check if the model is currently in a valid state.
    isValid: function(options) {
      return this._validate({}, _.extend({}, options, {validate: true}));
    },

    // Run validation against the next complete set of model attributes,
    // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
    _validate: function(attrs, options) {
      if (!options.validate || !this.validate) return true;
      attrs = _.extend({}, this.attributes, attrs);
      var error = this.validationError = this.validate(attrs, options) || null;
      if (!error) return true;
      this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
      return false;
    }

  });

  // Underscore methods that we want to implement on the Model, mapped to the
  // number of arguments they take.
  var modelMethods = {keys: 1, values: 1, pairs: 1, invert: 1, pick: 0,
      omit: 0, chain: 1, isEmpty: 1};

  // Mix in each Underscore method as a proxy to `Model#attributes`.
  addUnderscoreMethods(Model, modelMethods, 'attributes');

  // Backbone.Collection
  // -------------------

  // If models tend to represent a single row of data, a Backbone Collection is
  // more analogous to a table full of data ... or a small slice or page of that
  // table, or a collection of rows that belong together for a particular reason
  // -- all of the messages in this particular folder, all of the documents
  // belonging to this particular author, and so on. Collections maintain
  // indexes of their models, both in order, and for lookup by `id`.

  // Create a new **Collection**, perhaps to contain a specific type of `model`.
  // If a `comparator` is specified, the Collection will maintain
  // its models in sort order, as they're added and removed.
  var Collection = Backbone.Collection = function(models, options) {
    options || (options = {});
    if (options.model) this.model = options.model;
    if (options.comparator !== void 0) this.comparator = options.comparator;
    this._reset();
    this.initialize.apply(this, arguments);
    if (models) this.reset(models, _.extend({silent: true}, options));
  };

  // Default options for `Collection#set`.
  var setOptions = {add: true, remove: true, merge: true};
  var addOptions = {add: true, remove: false};

  // Splices `insert` into `array` at index `at`.
  var splice = function(array, insert, at) {
    at = Math.min(Math.max(at, 0), array.length);
    var tail = Array(array.length - at);
    var length = insert.length;
    var i;
    for (i = 0; i < tail.length; i++) tail[i] = array[i + at];
    for (i = 0; i < length; i++) array[i + at] = insert[i];
    for (i = 0; i < tail.length; i++) array[i + length + at] = tail[i];
  };

  // Define the Collection's inheritable methods.
  _.extend(Collection.prototype, Events, {

    // The default model for a collection is just a **Backbone.Model**.
    // This should be overridden in most cases.
    model: Model,

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // The JSON representation of a Collection is an array of the
    // models' attributes.
    toJSON: function(options) {
      return this.map(function(model) { return model.toJSON(options); });
    },

    // Proxy `Backbone.sync` by default.
    sync: function() {
      return Backbone.sync.apply(this, arguments);
    },

    // Add a model, or list of models to the set. `models` may be Backbone
    // Models or raw JavaScript objects to be converted to Models, or any
    // combination of the two.
    add: function(models, options) {
      return this.set(models, _.extend({merge: false}, options, addOptions));
    },

    // Remove a model, or a list of models from the set.
    remove: function(models, options) {
      options = _.extend({}, options);
      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();
      var removed = this._removeModels(models, options);
      if (!options.silent && removed.length) {
        options.changes = {added: [], merged: [], removed: removed};
        this.trigger('update', this, options);
      }
      return singular ? removed[0] : removed;
    },

    // Update a collection by `set`-ing a new list of models, adding new ones,
    // removing models that are no longer present, and merging models that
    // already exist in the collection, as necessary. Similar to **Model#set**,
    // the core operation for updating the data contained by the collection.
    set: function(models, options) {
      if (models == null) return;

      options = _.extend({}, setOptions, options);
      if (options.parse && !this._isModel(models)) {
        models = this.parse(models, options) || [];
      }

      var singular = !_.isArray(models);
      models = singular ? [models] : models.slice();

      var at = options.at;
      if (at != null) at = +at;
      if (at > this.length) at = this.length;
      if (at < 0) at += this.length + 1;

      var set = [];
      var toAdd = [];
      var toMerge = [];
      var toRemove = [];
      var modelMap = {};

      var add = options.add;
      var merge = options.merge;
      var remove = options.remove;

      var sort = false;
      var sortable = this.comparator && at == null && options.sort !== false;
      var sortAttr = _.isString(this.comparator) ? this.comparator : null;

      // Turn bare objects into model references, and prevent invalid models
      // from being added.
      var model, i;
      for (i = 0; i < models.length; i++) {
        model = models[i];

        // If a duplicate is found, prevent it from being added and
        // optionally merge it into the existing model.
        var existing = this.get(model);
        if (existing) {
          if (merge && model !== existing) {
            var attrs = this._isModel(model) ? model.attributes : model;
            if (options.parse) attrs = existing.parse(attrs, options);
            existing.set(attrs, options);
            toMerge.push(existing);
            if (sortable && !sort) sort = existing.hasChanged(sortAttr);
          }
          if (!modelMap[existing.cid]) {
            modelMap[existing.cid] = true;
            set.push(existing);
          }
          models[i] = existing;

        // If this is a new, valid model, push it to the `toAdd` list.
        } else if (add) {
          model = models[i] = this._prepareModel(model, options);
          if (model) {
            toAdd.push(model);
            this._addReference(model, options);
            modelMap[model.cid] = true;
            set.push(model);
          }
        }
      }

      // Remove stale models.
      if (remove) {
        for (i = 0; i < this.length; i++) {
          model = this.models[i];
          if (!modelMap[model.cid]) toRemove.push(model);
        }
        if (toRemove.length) this._removeModels(toRemove, options);
      }

      // See if sorting is needed, update `length` and splice in new models.
      var orderChanged = false;
      var replace = !sortable && add && remove;
      if (set.length && replace) {
        orderChanged = this.length !== set.length || _.some(this.models, function(m, index) {
          return m !== set[index];
        });
        this.models.length = 0;
        splice(this.models, set, 0);
        this.length = this.models.length;
      } else if (toAdd.length) {
        if (sortable) sort = true;
        splice(this.models, toAdd, at == null ? this.length : at);
        this.length = this.models.length;
      }

      // Silently sort the collection if appropriate.
      if (sort) this.sort({silent: true});

      // Unless silenced, it's time to fire all appropriate add/sort/update events.
      if (!options.silent) {
        for (i = 0; i < toAdd.length; i++) {
          if (at != null) options.index = at + i;
          model = toAdd[i];
          model.trigger('add', model, this, options);
        }
        if (sort || orderChanged) this.trigger('sort', this, options);
        if (toAdd.length || toRemove.length || toMerge.length) {
          options.changes = {
            added: toAdd,
            removed: toRemove,
            merged: toMerge
          };
          this.trigger('update', this, options);
        }
      }

      // Return the added (or merged) model (or models).
      return singular ? models[0] : models;
    },

    // When you have more items than you want to add or remove individually,
    // you can reset the entire set with a new list of models, without firing
    // any granular `add` or `remove` events. Fires `reset` when finished.
    // Useful for bulk operations and optimizations.
    reset: function(models, options) {
      options = options ? _.clone(options) : {};
      for (var i = 0; i < this.models.length; i++) {
        this._removeReference(this.models[i], options);
      }
      options.previousModels = this.models;
      this._reset();
      models = this.add(models, _.extend({silent: true}, options));
      if (!options.silent) this.trigger('reset', this, options);
      return models;
    },

    // Add a model to the end of the collection.
    push: function(model, options) {
      return this.add(model, _.extend({at: this.length}, options));
    },

    // Remove a model from the end of the collection.
    pop: function(options) {
      var model = this.at(this.length - 1);
      return this.remove(model, options);
    },

    // Add a model to the beginning of the collection.
    unshift: function(model, options) {
      return this.add(model, _.extend({at: 0}, options));
    },

    // Remove a model from the beginning of the collection.
    shift: function(options) {
      var model = this.at(0);
      return this.remove(model, options);
    },

    // Slice out a sub-array of models from the collection.
    slice: function() {
      return slice.apply(this.models, arguments);
    },

    // Get a model from the set by id, cid, model object with id or cid
    // properties, or an attributes object that is transformed through modelId.
    get: function(obj) {
      if (obj == null) return void 0;
      return this._byId[obj] ||
        this._byId[this.modelId(obj.attributes || obj)] ||
        obj.cid && this._byId[obj.cid];
    },

    // Returns `true` if the model is in the collection.
    has: function(obj) {
      return this.get(obj) != null;
    },

    // Get the model at the given index.
    at: function(index) {
      if (index < 0) index += this.length;
      return this.models[index];
    },

    // Return models with matching attributes. Useful for simple cases of
    // `filter`.
    where: function(attrs, first) {
      return this[first ? 'find' : 'filter'](attrs);
    },

    // Return the first model with matching attributes. Useful for simple cases
    // of `find`.
    findWhere: function(attrs) {
      return this.where(attrs, true);
    },

    // Force the collection to re-sort itself. You don't need to call this under
    // normal circumstances, as the set will maintain sort order as each item
    // is added.
    sort: function(options) {
      var comparator = this.comparator;
      if (!comparator) throw new Error('Cannot sort a set without a comparator');
      options || (options = {});

      var length = comparator.length;
      if (_.isFunction(comparator)) comparator = _.bind(comparator, this);

      // Run sort based on type of `comparator`.
      if (length === 1 || _.isString(comparator)) {
        this.models = this.sortBy(comparator);
      } else {
        this.models.sort(comparator);
      }
      if (!options.silent) this.trigger('sort', this, options);
      return this;
    },

    // Pluck an attribute from each model in the collection.
    pluck: function(attr) {
      return this.map(attr + '');
    },

    // Fetch the default set of models for this collection, resetting the
    // collection when they arrive. If `reset: true` is passed, the response
    // data will be passed through the `reset` method instead of `set`.
    fetch: function(options) {
      options = _.extend({parse: true}, options);
      var success = options.success;
      var collection = this;
      options.success = function(resp) {
        var method = options.reset ? 'reset' : 'set';
        collection[method](resp, options);
        if (success) success.call(options.context, collection, resp, options);
        collection.trigger('sync', collection, resp, options);
      };
      wrapError(this, options);
      return this.sync('read', this, options);
    },

    // Create a new instance of a model in this collection. Add the model to the
    // collection immediately, unless `wait: true` is passed, in which case we
    // wait for the server to agree.
    create: function(model, options) {
      options = options ? _.clone(options) : {};
      var wait = options.wait;
      model = this._prepareModel(model, options);
      if (!model) return false;
      if (!wait) this.add(model, options);
      var collection = this;
      var success = options.success;
      options.success = function(m, resp, callbackOpts) {
        if (wait) collection.add(m, callbackOpts);
        if (success) success.call(callbackOpts.context, m, resp, callbackOpts);
      };
      model.save(null, options);
      return model;
    },

    // **parse** converts a response into a list of models to be added to the
    // collection. The default implementation is just to pass it through.
    parse: function(resp, options) {
      return resp;
    },

    // Create a new collection with an identical list of models as this one.
    clone: function() {
      return new this.constructor(this.models, {
        model: this.model,
        comparator: this.comparator
      });
    },

    // Define how to uniquely identify models in the collection.
    modelId: function(attrs) {
      return attrs[this.model.prototype.idAttribute || 'id'];
    },

    // Private method to reset all internal state. Called when the collection
    // is first initialized or reset.
    _reset: function() {
      this.length = 0;
      this.models = [];
      this._byId  = {};
    },

    // Prepare a hash of attributes (or other model) to be added to this
    // collection.
    _prepareModel: function(attrs, options) {
      if (this._isModel(attrs)) {
        if (!attrs.collection) attrs.collection = this;
        return attrs;
      }
      options = options ? _.clone(options) : {};
      options.collection = this;
      var model = new this.model(attrs, options);
      if (!model.validationError) return model;
      this.trigger('invalid', this, model.validationError, options);
      return false;
    },

    // Internal method called by both remove and set.
    _removeModels: function(models, options) {
      var removed = [];
      for (var i = 0; i < models.length; i++) {
        var model = this.get(models[i]);
        if (!model) continue;

        var index = this.indexOf(model);
        this.models.splice(index, 1);
        this.length--;

        // Remove references before triggering 'remove' event to prevent an
        // infinite loop. #3693
        delete this._byId[model.cid];
        var id = this.modelId(model.attributes);
        if (id != null) delete this._byId[id];

        if (!options.silent) {
          options.index = index;
          model.trigger('remove', model, this, options);
        }

        removed.push(model);
        this._removeReference(model, options);
      }
      return removed;
    },

    // Method for checking whether an object should be considered a model for
    // the purposes of adding to the collection.
    _isModel: function(model) {
      return model instanceof Model;
    },

    // Internal method to create a model's ties to a collection.
    _addReference: function(model, options) {
      this._byId[model.cid] = model;
      var id = this.modelId(model.attributes);
      if (id != null) this._byId[id] = model;
      model.on('all', this._onModelEvent, this);
    },

    // Internal method to sever a model's ties to a collection.
    _removeReference: function(model, options) {
      delete this._byId[model.cid];
      var id = this.modelId(model.attributes);
      if (id != null) delete this._byId[id];
      if (this === model.collection) delete model.collection;
      model.off('all', this._onModelEvent, this);
    },

    // Internal method called every time a model in the set fires an event.
    // Sets need to update their indexes when models change ids. All other
    // events simply proxy through. "add" and "remove" events that originate
    // in other collections are ignored.
    _onModelEvent: function(event, model, collection, options) {
      if (model) {
        if ((event === 'add' || event === 'remove') && collection !== this) return;
        if (event === 'destroy') this.remove(model, options);
        if (event === 'change') {
          var prevId = this.modelId(model.previousAttributes());
          var id = this.modelId(model.attributes);
          if (prevId !== id) {
            if (prevId != null) delete this._byId[prevId];
            if (id != null) this._byId[id] = model;
          }
        }
      }
      this.trigger.apply(this, arguments);
    }

  });

  // Underscore methods that we want to implement on the Collection.
  // 90% of the core usefulness of Backbone Collections is actually implemented
  // right here:
  var collectionMethods = {forEach: 3, each: 3, map: 3, collect: 3, reduce: 0,
      foldl: 0, inject: 0, reduceRight: 0, foldr: 0, find: 3, detect: 3, filter: 3,
      select: 3, reject: 3, every: 3, all: 3, some: 3, any: 3, include: 3, includes: 3,
      contains: 3, invoke: 0, max: 3, min: 3, toArray: 1, size: 1, first: 3,
      head: 3, take: 3, initial: 3, rest: 3, tail: 3, drop: 3, last: 3,
      without: 0, difference: 0, indexOf: 3, shuffle: 1, lastIndexOf: 3,
      isEmpty: 1, chain: 1, sample: 3, partition: 3, groupBy: 3, countBy: 3,
      sortBy: 3, indexBy: 3, findIndex: 3, findLastIndex: 3};

  // Mix in each Underscore method as a proxy to `Collection#models`.
  addUnderscoreMethods(Collection, collectionMethods, 'models');

  // Backbone.View
  // -------------

  // Backbone Views are almost more convention than they are actual code. A View
  // is simply a JavaScript object that represents a logical chunk of UI in the
  // DOM. This might be a single item, an entire list, a sidebar or panel, or
  // even the surrounding frame which wraps your whole app. Defining a chunk of
  // UI as a **View** allows you to define your DOM events declaratively, without
  // having to worry about render order ... and makes it easy for the view to
  // react to specific changes in the state of your models.

  // Creating a Backbone.View creates its initial element outside of the DOM,
  // if an existing element is not provided...
  var View = Backbone.View = function(options) {
    this.cid = _.uniqueId('view');
    _.extend(this, _.pick(options, viewOptions));
    this._ensureElement();
    this.initialize.apply(this, arguments);
  };

  // Cached regex to split keys for `delegate`.
  var delegateEventSplitter = /^(\S+)\s*(.*)$/;

  // List of view options to be set as properties.
  var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];

  // Set up all inheritable **Backbone.View** properties and methods.
  _.extend(View.prototype, Events, {

    // The default `tagName` of a View's element is `"div"`.
    tagName: 'div',

    // jQuery delegate for element lookup, scoped to DOM elements within the
    // current view. This should be preferred to global lookups where possible.
    $: function(selector) {
      return this.$el.find(selector);
    },

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // **render** is the core function that your view should override, in order
    // to populate its element (`this.el`), with the appropriate HTML. The
    // convention is for **render** to always return `this`.
    render: function() {
      return this;
    },

    // Remove this view by taking the element out of the DOM, and removing any
    // applicable Backbone.Events listeners.
    remove: function() {
      this._removeElement();
      this.stopListening();
      return this;
    },

    // Remove this view's element from the document and all event listeners
    // attached to it. Exposed for subclasses using an alternative DOM
    // manipulation API.
    _removeElement: function() {
      this.$el.remove();
    },

    // Change the view's element (`this.el` property) and re-delegate the
    // view's events on the new element.
    setElement: function(element) {
      this.undelegateEvents();
      this._setElement(element);
      this.delegateEvents();
      return this;
    },

    // Creates the `this.el` and `this.$el` references for this view using the
    // given `el`. `el` can be a CSS selector or an HTML string, a jQuery
    // context or an element. Subclasses can override this to utilize an
    // alternative DOM manipulation API and are only required to set the
    // `this.el` property.
    _setElement: function(el) {
      this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
      this.el = this.$el[0];
    },

    // Set callbacks, where `this.events` is a hash of
    //
    // *{"event selector": "callback"}*
    //
    //     {
    //       'mousedown .title':  'edit',
    //       'click .button':     'save',
    //       'click .open':       function(e) { ... }
    //     }
    //
    // pairs. Callbacks will be bound to the view, with `this` set properly.
    // Uses event delegation for efficiency.
    // Omitting the selector binds the event to `this.el`.
    delegateEvents: function(events) {
      events || (events = _.result(this, 'events'));
      if (!events) return this;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[method];
        if (!method) continue;
        var match = key.match(delegateEventSplitter);
        this.delegate(match[1], match[2], _.bind(method, this));
      }
      return this;
    },

    // Add a single event listener to the view's element (or a child element
    // using `selector`). This only works for delegate-able events: not `focus`,
    // `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
    delegate: function(eventName, selector, listener) {
      this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Clears all callbacks previously bound to the view by `delegateEvents`.
    // You usually don't need to use this, but may wish to if you have multiple
    // Backbone views attached to the same DOM element.
    undelegateEvents: function() {
      if (this.$el) this.$el.off('.delegateEvents' + this.cid);
      return this;
    },

    // A finer-grained `undelegateEvents` for removing a single delegated event.
    // `selector` and `listener` are both optional.
    undelegate: function(eventName, selector, listener) {
      this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
      return this;
    },

    // Produces a DOM element to be assigned to your view. Exposed for
    // subclasses using an alternative DOM manipulation API.
    _createElement: function(tagName) {
      return document.createElement(tagName);
    },

    // Ensure that the View has a DOM element to render into.
    // If `this.el` is a string, pass it through `$()`, take the first
    // matching element, and re-assign it to `el`. Otherwise, create
    // an element from the `id`, `className` and `tagName` properties.
    _ensureElement: function() {
      if (!this.el) {
        var attrs = _.extend({}, _.result(this, 'attributes'));
        if (this.id) attrs.id = _.result(this, 'id');
        if (this.className) attrs['class'] = _.result(this, 'className');
        this.setElement(this._createElement(_.result(this, 'tagName')));
        this._setAttributes(attrs);
      } else {
        this.setElement(_.result(this, 'el'));
      }
    },

    // Set attributes from a hash on this view's element.  Exposed for
    // subclasses using an alternative DOM manipulation API.
    _setAttributes: function(attributes) {
      this.$el.attr(attributes);
    }

  });

  // Backbone.sync
  // -------------

  // Override this function to change the manner in which Backbone persists
  // models to the server. You will be passed the type of request, and the
  // model in question. By default, makes a RESTful Ajax request
  // to the model's `url()`. Some possible customizations could be:
  //
  // * Use `setTimeout` to batch rapid-fire updates into a single request.
  // * Send up the models as XML instead of JSON.
  // * Persist models via WebSockets instead of Ajax.
  //
  // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
  // as `POST`, with a `_method` parameter containing the true HTTP method,
  // as well as all requests with the body as `application/x-www-form-urlencoded`
  // instead of `application/json` with the model in a param named `model`.
  // Useful when interfacing with server-side languages like **PHP** that make
  // it difficult to read the body of `PUT` requests.
  Backbone.sync = function(method, model, options) {
    var type = methodMap[method];

    // Default options, unless specified.
    _.defaults(options || (options = {}), {
      emulateHTTP: Backbone.emulateHTTP,
      emulateJSON: Backbone.emulateJSON
    });

    // Default JSON-request options.
    var params = {type: type, dataType: 'json'};

    // Ensure that we have a URL.
    if (!options.url) {
      params.url = _.result(model, 'url') || urlError();
    }

    // Ensure that we have the appropriate request data.
    if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
      params.contentType = 'application/json';
      params.data = JSON.stringify(options.attrs || model.toJSON(options));
    }

    // For older servers, emulate JSON by encoding the request into an HTML-form.
    if (options.emulateJSON) {
      params.contentType = 'application/x-www-form-urlencoded';
      params.data = params.data ? {model: params.data} : {};
    }

    // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
    // And an `X-HTTP-Method-Override` header.
    if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
      params.type = 'POST';
      if (options.emulateJSON) params.data._method = type;
      var beforeSend = options.beforeSend;
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader('X-HTTP-Method-Override', type);
        if (beforeSend) return beforeSend.apply(this, arguments);
      };
    }

    // Don't process data on a non-GET request.
    if (params.type !== 'GET' && !options.emulateJSON) {
      params.processData = false;
    }

    // Pass along `textStatus` and `errorThrown` from jQuery.
    var error = options.error;
    options.error = function(xhr, textStatus, errorThrown) {
      options.textStatus = textStatus;
      options.errorThrown = errorThrown;
      if (error) error.call(options.context, xhr, textStatus, errorThrown);
    };

    // Make the request, allowing the user to override any Ajax options.
    var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
    model.trigger('request', model, xhr, options);
    return xhr;
  };

  // Map from CRUD to HTTP for our default `Backbone.sync` implementation.
  var methodMap = {
    'create': 'POST',
    'update': 'PUT',
    'patch': 'PATCH',
    'delete': 'DELETE',
    'read': 'GET'
  };

  // Set the default implementation of `Backbone.ajax` to proxy through to `$`.
  // Override this if you'd like to use a different library.
  Backbone.ajax = function() {
    return Backbone.$.ajax.apply(Backbone.$, arguments);
  };

  // Backbone.Router
  // ---------------

  // Routers map faux-URLs to actions, and fire events when routes are
  // matched. Creating a new one sets its `routes` hash, if not set statically.
  var Router = Backbone.Router = function(options) {
    options || (options = {});
    if (options.routes) this.routes = options.routes;
    this._bindRoutes();
    this.initialize.apply(this, arguments);
  };

  // Cached regular expressions for matching named param parts and splatted
  // parts of route strings.
  var optionalParam = /\((.*?)\)/g;
  var namedParam    = /(\(\?)?:\w+/g;
  var splatParam    = /\*\w+/g;
  var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;

  // Set up all inheritable **Backbone.Router** properties and methods.
  _.extend(Router.prototype, Events, {

    // Initialize is an empty function by default. Override it with your own
    // initialization logic.
    initialize: function(){},

    // Manually bind a single named route to a callback. For example:
    //
    //     this.route('search/:query/p:num', 'search', function(query, num) {
    //       ...
    //     });
    //
    route: function(route, name, callback) {
      if (!_.isRegExp(route)) route = this._routeToRegExp(route);
      if (_.isFunction(name)) {
        callback = name;
        name = '';
      }
      if (!callback) callback = this[name];
      var router = this;
      Backbone.history.route(route, function(fragment) {
        var args = router._extractParameters(route, fragment);
        if (router.execute(callback, args, name) !== false) {
          router.trigger.apply(router, ['route:' + name].concat(args));
          router.trigger('route', name, args);
          Backbone.history.trigger('route', router, name, args);
        }
      });
      return this;
    },

    // Execute a route handler with the provided parameters.  This is an
    // excellent place to do pre-route setup or post-route cleanup.
    execute: function(callback, args, name) {
      if (callback) callback.apply(this, args);
    },

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
      return this;
    },

    // Bind all defined routes to `Backbone.history`. We have to reverse the
    // order of the routes here to support behavior where the most general
    // routes can be defined at the bottom of the route map.
    _bindRoutes: function() {
      if (!this.routes) return;
      this.routes = _.result(this, 'routes');
      var route, routes = _.keys(this.routes);
      while ((route = routes.pop()) != null) {
        this.route(route, this.routes[route]);
      }
    },

    // Convert a route string into a regular expression, suitable for matching
    // against the current location hash.
    _routeToRegExp: function(route) {
      route = route.replace(escapeRegExp, '\\$&')
                   .replace(optionalParam, '(?:$1)?')
                   .replace(namedParam, function(match, optional) {
                     return optional ? match : '([^/?]+)';
                   })
                   .replace(splatParam, '([^?]*?)');
      return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
    },

    // Given a route, and a URL fragment that it matches, return the array of
    // extracted decoded parameters. Empty or unmatched parameters will be
    // treated as `null` to normalize cross-browser behavior.
    _extractParameters: function(route, fragment) {
      var params = route.exec(fragment).slice(1);
      return _.map(params, function(param, i) {
        // Don't decode the search params.
        if (i === params.length - 1) return param || null;
        return param ? decodeURIComponent(param) : null;
      });
    }

  });

  // Backbone.History
  // ----------------

  // Handles cross-browser history management, based on either
  // [pushState](http://diveintohtml5.info/history.html) and real URLs, or
  // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
  // and URL fragments. If the browser supports neither (old IE, natch),
  // falls back to polling.
  var History = Backbone.History = function() {
    this.handlers = [];
    this.checkUrl = _.bind(this.checkUrl, this);

    // Ensure that `History` can be used outside of the browser.
    if (typeof window !== 'undefined') {
      this.location = window.location;
      this.history = window.history;
    }
  };

  // Cached regex for stripping a leading hash/slash and trailing space.
  var routeStripper = /^[#\/]|\s+$/g;

  // Cached regex for stripping leading and trailing slashes.
  var rootStripper = /^\/+|\/+$/g;

  // Cached regex for stripping urls of hash.
  var pathStripper = /#.*$/;

  // Has the history handling already been started?
  History.started = false;

  // Set up all inheritable **Backbone.History** properties and methods.
  _.extend(History.prototype, Events, {

    // The default interval to poll for hash changes, if necessary, is
    // twenty times a second.
    interval: 50,

    // Are we at the app root?
    atRoot: function() {
      var path = this.location.pathname.replace(/[^\/]$/, '$&/');
      return path === this.root && !this.getSearch();
    },

    // Does the pathname match the root?
    matchRoot: function() {
      var path = this.decodeFragment(this.location.pathname);
      var rootPath = path.slice(0, this.root.length - 1) + '/';
      return rootPath === this.root;
    },

    // Unicode characters in `location.pathname` are percent encoded so they're
    // decoded for comparison. `%25` should not be decoded since it may be part
    // of an encoded parameter.
    decodeFragment: function(fragment) {
      return decodeURI(fragment.replace(/%25/g, '%2525'));
    },

    // In IE6, the hash fragment and search params are incorrect if the
    // fragment contains `?`.
    getSearch: function() {
      var match = this.location.href.replace(/#.*/, '').match(/\?.+/);
      return match ? match[0] : '';
    },

    // Gets the true hash value. Cannot use location.hash directly due to bug
    // in Firefox where location.hash will always be decoded.
    getHash: function(window) {
      var match = (window || this).location.href.match(/#(.*)$/);
      return match ? match[1] : '';
    },

    // Get the pathname and search params, without the root.
    getPath: function() {
      var path = this.decodeFragment(
        this.location.pathname + this.getSearch()
      ).slice(this.root.length - 1);
      return path.charAt(0) === '/' ? path.slice(1) : path;
    },

    // Get the cross-browser normalized URL fragment from the path or hash.
    getFragment: function(fragment) {
      if (fragment == null) {
        if (this._usePushState || !this._wantsHashChange) {
          fragment = this.getPath();
        } else {
          fragment = this.getHash();
        }
      }
      return fragment.replace(routeStripper, '');
    },

    // Start the hash change handling, returning `true` if the current URL matches
    // an existing route, and `false` otherwise.
    start: function(options) {
      if (History.started) throw new Error('Backbone.history has already been started');
      History.started = true;

      // Figure out the initial configuration. Do we need an iframe?
      // Is pushState desired ... is it available?
      this.options          = _.extend({root: '/'}, this.options, options);
      this.root             = this.options.root;
      this._wantsHashChange = this.options.hashChange !== false;
      this._hasHashChange   = 'onhashchange' in window && (document.documentMode === void 0 || document.documentMode > 7);
      this._useHashChange   = this._wantsHashChange && this._hasHashChange;
      this._wantsPushState  = !!this.options.pushState;
      this._hasPushState    = !!(this.history && this.history.pushState);
      this._usePushState    = this._wantsPushState && this._hasPushState;
      this.fragment         = this.getFragment();

      // Normalize root to always include a leading and trailing slash.
      this.root = ('/' + this.root + '/').replace(rootStripper, '/');

      // Transition from hashChange to pushState or vice versa if both are
      // requested.
      if (this._wantsHashChange && this._wantsPushState) {

        // If we've started off with a route from a `pushState`-enabled
        // browser, but we're currently in a browser that doesn't support it...
        if (!this._hasPushState && !this.atRoot()) {
          var rootPath = this.root.slice(0, -1) || '/';
          this.location.replace(rootPath + '#' + this.getPath());
          // Return immediately as browser will do redirect to new url
          return true;

        // Or if we've started out with a hash-based route, but we're currently
        // in a browser where it could be `pushState`-based instead...
        } else if (this._hasPushState && this.atRoot()) {
          this.navigate(this.getHash(), {replace: true});
        }

      }

      // Proxy an iframe to handle location events if the browser doesn't
      // support the `hashchange` event, HTML5 history, or the user wants
      // `hashChange` but not `pushState`.
      if (!this._hasHashChange && this._wantsHashChange && !this._usePushState) {
        this.iframe = document.createElement('iframe');
        this.iframe.src = 'javascript:0';
        this.iframe.style.display = 'none';
        this.iframe.tabIndex = -1;
        var body = document.body;
        // Using `appendChild` will throw on IE < 9 if the document is not ready.
        var iWindow = body.insertBefore(this.iframe, body.firstChild).contentWindow;
        iWindow.document.open();
        iWindow.document.close();
        iWindow.location.hash = '#' + this.fragment;
      }

      // Add a cross-platform `addEventListener` shim for older browsers.
      var addEventListener = window.addEventListener || function(eventName, listener) {
        return attachEvent('on' + eventName, listener);
      };

      // Depending on whether we're using pushState or hashes, and whether
      // 'onhashchange' is supported, determine how we check the URL state.
      if (this._usePushState) {
        addEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        addEventListener('hashchange', this.checkUrl, false);
      } else if (this._wantsHashChange) {
        this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
      }

      if (!this.options.silent) return this.loadUrl();
    },

    // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
    // but possibly useful for unit testing Routers.
    stop: function() {
      // Add a cross-platform `removeEventListener` shim for older browsers.
      var removeEventListener = window.removeEventListener || function(eventName, listener) {
        return detachEvent('on' + eventName, listener);
      };

      // Remove window listeners.
      if (this._usePushState) {
        removeEventListener('popstate', this.checkUrl, false);
      } else if (this._useHashChange && !this.iframe) {
        removeEventListener('hashchange', this.checkUrl, false);
      }

      // Clean up the iframe if necessary.
      if (this.iframe) {
        document.body.removeChild(this.iframe);
        this.iframe = null;
      }

      // Some environments will throw when clearing an undefined interval.
      if (this._checkUrlInterval) clearInterval(this._checkUrlInterval);
      History.started = false;
    },

    // Add a route to be tested when the fragment changes. Routes added later
    // may override previous routes.
    route: function(route, callback) {
      this.handlers.unshift({route: route, callback: callback});
    },

    // Checks the current URL to see if it has changed, and if it has,
    // calls `loadUrl`, normalizing across the hidden iframe.
    checkUrl: function(e) {
      var current = this.getFragment();

      // If the user pressed the back button, the iframe's hash will have
      // changed and we should use that for comparison.
      if (current === this.fragment && this.iframe) {
        current = this.getHash(this.iframe.contentWindow);
      }

      if (current === this.fragment) return false;
      if (this.iframe) this.navigate(current);
      this.loadUrl();
    },

    // Attempt to load the current URL fragment. If a route succeeds with a
    // match, returns `true`. If no defined routes matches the fragment,
    // returns `false`.
    loadUrl: function(fragment) {
      // If the root doesn't match, no routes can match either.
      if (!this.matchRoot()) return false;
      fragment = this.fragment = this.getFragment(fragment);
      return _.some(this.handlers, function(handler) {
        if (handler.route.test(fragment)) {
          handler.callback(fragment);
          return true;
        }
      });
    },

    // Save a fragment into the hash history, or replace the URL state if the
    // 'replace' option is passed. You are responsible for properly URL-encoding
    // the fragment in advance.
    //
    // The options object can contain `trigger: true` if you wish to have the
    // route callback be fired (not usually desirable), or `replace: true`, if
    // you wish to modify the current URL without adding an entry to the history.
    navigate: function(fragment, options) {
      if (!History.started) return false;
      if (!options || options === true) options = {trigger: !!options};

      // Normalize the fragment.
      fragment = this.getFragment(fragment || '');

      // Don't include a trailing slash on the root.
      var rootPath = this.root;
      if (fragment === '' || fragment.charAt(0) === '?') {
        rootPath = rootPath.slice(0, -1) || '/';
      }
      var url = rootPath + fragment;

      // Strip the hash and decode for matching.
      fragment = this.decodeFragment(fragment.replace(pathStripper, ''));

      if (this.fragment === fragment) return;
      this.fragment = fragment;

      // If pushState is available, we use it to set the fragment as a real URL.
      if (this._usePushState) {
        this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);

      // If hash changes haven't been explicitly disabled, update the hash
      // fragment to store history.
      } else if (this._wantsHashChange) {
        this._updateHash(this.location, fragment, options.replace);
        if (this.iframe && fragment !== this.getHash(this.iframe.contentWindow)) {
          var iWindow = this.iframe.contentWindow;

          // Opening and closing the iframe tricks IE7 and earlier to push a
          // history entry on hash-tag change.  When replace is true, we don't
          // want this.
          if (!options.replace) {
            iWindow.document.open();
            iWindow.document.close();
          }

          this._updateHash(iWindow.location, fragment, options.replace);
        }

      // If you've told us that you explicitly don't want fallback hashchange-
      // based history, then `navigate` becomes a page refresh.
      } else {
        return this.location.assign(url);
      }
      if (options.trigger) return this.loadUrl(fragment);
    },

    // Update the hash location, either replacing the current entry, or adding
    // a new one to the browser history.
    _updateHash: function(location, fragment, replace) {
      if (replace) {
        var href = location.href.replace(/(javascript:|#).*$/, '');
        location.replace(href + '#' + fragment);
      } else {
        // Some browsers require that `hash` contains a leading #.
        location.hash = '#' + fragment;
      }
    }

  });

  // Create the default Backbone.history.
  Backbone.history = new History;

  // Helpers
  // -------

  // Helper function to correctly set up the prototype chain for subclasses.
  // Similar to `goog.inherits`, but uses a hash of prototype properties and
  // class properties to be extended.
  var extend = function(protoProps, staticProps) {
    var parent = this;
    var child;

    // The constructor function for the new subclass is either defined by you
    // (the "constructor" property in your `extend` definition), or defaulted
    // by us to simply call the parent constructor.
    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    // Add static properties to the constructor function, if supplied.
    _.extend(child, parent, staticProps);

    // Set the prototype chain to inherit from `parent`, without calling
    // `parent`'s constructor function and add the prototype properties.
    child.prototype = _.create(parent.prototype, protoProps);
    child.prototype.constructor = child;

    // Set a convenience property in case the parent's prototype is needed
    // later.
    child.__super__ = parent.prototype;

    return child;
  };

  // Set up inheritance for the model, collection, router, view and history.
  Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend;

  // Throw an error when a URL is needed, and none is supplied.
  var urlError = function() {
    throw new Error('A "url" property or function must be specified');
  };

  // Wrap an optional error callback with a fallback error event.
  var wrapError = function(model, options) {
    var error = options.error;
    options.error = function(resp) {
      if (error) error.call(options.context, model, resp, options);
      model.trigger('error', model, resp, options);
    };
  };

  return Backbone;
});

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"jquery":"jquery","underscore":"underscore"}],"_process":[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 () {
  try {
    cachedSetTimeout = setTimeout;
  } catch (e) {
    cachedSetTimeout = function () {
      throw new Error('setTimeout is not defined');
    }
  }
  try {
    cachedClearTimeout = clearTimeout;
  } catch (e) {
    cachedClearTimeout = function () {
      throw new Error('clearTimeout is not defined');
    }
  }
} ())
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 = cachedSetTimeout.call(null, 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;
    cachedClearTimeout.call(null, 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) {
        cachedSetTimeout.call(null, drainQueue, 0);
    }
};

// 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.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; };

},{}],"es6-promise":[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/jakearchibald/es6-promise/master/LICENSE
 * @version   3.0.2
 */

(function() {
    "use strict";
    function lib$es6$promise$utils$$objectOrFunction(x) {
      return typeof x === 'function' || (typeof x === 'object' && x !== null);
    }

    function lib$es6$promise$utils$$isFunction(x) {
      return typeof x === 'function';
    }

    function lib$es6$promise$utils$$isMaybeThenable(x) {
      return typeof x === 'object' && x !== null;
    }

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

    var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
    var lib$es6$promise$asap$$len = 0;
    var lib$es6$promise$asap$$toString = {}.toString;
    var lib$es6$promise$asap$$vertxNext;
    var lib$es6$promise$asap$$customSchedulerFn;

    var lib$es6$promise$asap$$asap = function asap(callback, arg) {
      lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
      lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
      lib$es6$promise$asap$$len += 2;
      if (lib$es6$promise$asap$$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 (lib$es6$promise$asap$$customSchedulerFn) {
          lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
        } else {
          lib$es6$promise$asap$$scheduleFlush();
        }
      }
    }

    function lib$es6$promise$asap$$setScheduler(scheduleFn) {
      lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
    }

    function lib$es6$promise$asap$$setAsap(asapFn) {
      lib$es6$promise$asap$$asap = asapFn;
    }

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

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

    // node
    function lib$es6$promise$asap$$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() {
        process.nextTick(lib$es6$promise$asap$$flush);
      };
    }

    // vertx
    function lib$es6$promise$asap$$useVertxTimer() {
      return function() {
        lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
      };
    }

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

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

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

    function lib$es6$promise$asap$$useSetTimeout() {
      return function() {
        setTimeout(lib$es6$promise$asap$$flush, 1);
      };
    }

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

        callback(arg);

        lib$es6$promise$asap$$queue[i] = undefined;
        lib$es6$promise$asap$$queue[i+1] = undefined;
      }

      lib$es6$promise$asap$$len = 0;
    }

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

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

    function lib$es6$promise$$internal$$noop() {}

    var lib$es6$promise$$internal$$PENDING   = void 0;
    var lib$es6$promise$$internal$$FULFILLED = 1;
    var lib$es6$promise$$internal$$REJECTED  = 2;

    var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();

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

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

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

    function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
      try {
        then.call(value, fulfillmentHandler, rejectionHandler);
      } catch(e) {
        return e;
      }
    }

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

          lib$es6$promise$$internal$$reject(promise, reason);
        }, 'Settle: ' + (promise._label || ' unknown promise'));

        if (!sealed && error) {
          sealed = true;
          lib$es6$promise$$internal$$reject(promise, error);
        }
      }, promise);
    }

    function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
      if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
        lib$es6$promise$$internal$$fulfill(promise, thenable._result);
      } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
        lib$es6$promise$$internal$$reject(promise, thenable._result);
      } else {
        lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
          lib$es6$promise$$internal$$resolve(promise, value);
        }, function(reason) {
          lib$es6$promise$$internal$$reject(promise, reason);
        });
      }
    }

    function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
      if (maybeThenable.constructor === promise.constructor) {
        lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
      } else {
        var then = lib$es6$promise$$internal$$getThen(maybeThenable);

        if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
          lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
        } else if (then === undefined) {
          lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
        } else if (lib$es6$promise$utils$$isFunction(then)) {
          lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
        } else {
          lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
        }
      }
    }

    function lib$es6$promise$$internal$$resolve(promise, value) {
      if (promise === value) {
        lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
      } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
        lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
      } else {
        lib$es6$promise$$internal$$fulfill(promise, value);
      }
    }

    function lib$es6$promise$$internal$$publishRejection(promise) {
      if (promise._onerror) {
        promise._onerror(promise._result);
      }

      lib$es6$promise$$internal$$publish(promise);
    }

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

      promise._result = value;
      promise._state = lib$es6$promise$$internal$$FULFILLED;

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

    function lib$es6$promise$$internal$$reject(promise, reason) {
      if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
      promise._state = lib$es6$promise$$internal$$REJECTED;
      promise._result = reason;

      lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
    }

    function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
      var subscribers = parent._subscribers;
      var length = subscribers.length;

      parent._onerror = null;

      subscribers[length] = child;
      subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
      subscribers[length + lib$es6$promise$$internal$$REJECTED]  = onRejection;

      if (length === 0 && parent._state) {
        lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
      }
    }

    function lib$es6$promise$$internal$$publish(promise) {
      var subscribers = promise._subscribers;
      var settled = promise._state;

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

      var child, callback, detail = promise._result;

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

        if (child) {
          lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
        } else {
          callback(detail);
        }
      }

      promise._subscribers.length = 0;
    }

    function lib$es6$promise$$internal$$ErrorObject() {
      this.error = null;
    }

    var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();

    function lib$es6$promise$$internal$$tryCatch(callback, detail) {
      try {
        return callback(detail);
      } catch(e) {
        lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
        return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
      }
    }

    function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
      var hasCallback = lib$es6$promise$utils$$isFunction(callback),
          value, error, succeeded, failed;

      if (hasCallback) {
        value = lib$es6$promise$$internal$$tryCatch(callback, detail);

        if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
          failed = true;
          error = value.error;
          value = null;
        } else {
          succeeded = true;
        }

        if (promise === value) {
          lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
          return;
        }

      } else {
        value = detail;
        succeeded = true;
      }

      if (promise._state !== lib$es6$promise$$internal$$PENDING) {
        // noop
      } else if (hasCallback && succeeded) {
        lib$es6$promise$$internal$$resolve(promise, value);
      } else if (failed) {
        lib$es6$promise$$internal$$reject(promise, error);
      } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
        lib$es6$promise$$internal$$fulfill(promise, value);
      } else if (settled === lib$es6$promise$$internal$$REJECTED) {
        lib$es6$promise$$internal$$reject(promise, value);
      }
    }

    function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
      try {
        resolver(function resolvePromise(value){
          lib$es6$promise$$internal$$resolve(promise, value);
        }, function rejectPromise(reason) {
          lib$es6$promise$$internal$$reject(promise, reason);
        });
      } catch(e) {
        lib$es6$promise$$internal$$reject(promise, e);
      }
    }

    function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
      var enumerator = this;

      enumerator._instanceConstructor = Constructor;
      enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);

      if (enumerator._validateInput(input)) {
        enumerator._input     = input;
        enumerator.length     = input.length;
        enumerator._remaining = input.length;

        enumerator._init();

        if (enumerator.length === 0) {
          lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
        } else {
          enumerator.length = enumerator.length || 0;
          enumerator._enumerate();
          if (enumerator._remaining === 0) {
            lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
          }
        }
      } else {
        lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
      }
    }

    lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
      return lib$es6$promise$utils$$isArray(input);
    };

    lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
      return new Error('Array Methods must be provided an Array');
    };

    lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
      this._result = new Array(this.length);
    };

    var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;

    lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
      var enumerator = this;

      var length  = enumerator.length;
      var promise = enumerator.promise;
      var input   = enumerator._input;

      for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
        enumerator._eachEntry(input[i], i);
      }
    };

    lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
      var enumerator = this;
      var c = enumerator._instanceConstructor;

      if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
        if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
          entry._onerror = null;
          enumerator._settledAt(entry._state, i, entry._result);
        } else {
          enumerator._willSettleAt(c.resolve(entry), i);
        }
      } else {
        enumerator._remaining--;
        enumerator._result[i] = entry;
      }
    };

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

      if (promise._state === lib$es6$promise$$internal$$PENDING) {
        enumerator._remaining--;

        if (state === lib$es6$promise$$internal$$REJECTED) {
          lib$es6$promise$$internal$$reject(promise, value);
        } else {
          enumerator._result[i] = value;
        }
      }

      if (enumerator._remaining === 0) {
        lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
      }
    };

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

      lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
        enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
      }, function(reason) {
        enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
      });
    };
    function lib$es6$promise$promise$all$$all(entries) {
      return new lib$es6$promise$enumerator$$default(this, entries).promise;
    }
    var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
    function lib$es6$promise$promise$race$$race(entries) {
      /*jshint validthis:true */
      var Constructor = this;

      var promise = new Constructor(lib$es6$promise$$internal$$noop);

      if (!lib$es6$promise$utils$$isArray(entries)) {
        lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
        return promise;
      }

      var length = entries.length;

      function onFulfillment(value) {
        lib$es6$promise$$internal$$resolve(promise, value);
      }

      function onRejection(reason) {
        lib$es6$promise$$internal$$reject(promise, reason);
      }

      for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
        lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
      }

      return promise;
    }
    var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
    function lib$es6$promise$promise$resolve$$resolve(object) {
      /*jshint validthis:true */
      var Constructor = this;

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

      var promise = new Constructor(lib$es6$promise$$internal$$noop);
      lib$es6$promise$$internal$$resolve(promise, object);
      return promise;
    }
    var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
    function lib$es6$promise$promise$reject$$reject(reason) {
      /*jshint validthis:true */
      var Constructor = this;
      var promise = new Constructor(lib$es6$promise$$internal$$noop);
      lib$es6$promise$$internal$$reject(promise, reason);
      return promise;
    }
    var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;

    var lib$es6$promise$promise$$counter = 0;

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

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

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

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

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

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

      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
      var promise = new Promise(function(resolve, reject) {
        // on success
        resolve(value);

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

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

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

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

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

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

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

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

      Unlike callbacks, promises are great composable primitives.

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

        return values;
      });
      ```

      @class Promise
      @param {function} resolver
      Useful for tooling.
      @constructor
    */
    function lib$es6$promise$promise$$Promise(resolver) {
      this._id = lib$es6$promise$promise$$counter++;
      this._state = undefined;
      this._result = undefined;
      this._subscribers = [];

      if (lib$es6$promise$$internal$$noop !== resolver) {
        if (!lib$es6$promise$utils$$isFunction(resolver)) {
          lib$es6$promise$promise$$needsResolver();
        }

        if (!(this instanceof lib$es6$promise$promise$$Promise)) {
          lib$es6$promise$promise$$needsNew();
        }

        lib$es6$promise$$internal$$initializePromise(this, resolver);
      }
    }

    lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
    lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
    lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
    lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
    lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
    lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
    lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;

    lib$es6$promise$promise$$Promise.prototype = {
      constructor: lib$es6$promise$promise$$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
      var 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
      var author, books;

      try {
        author = findAuthor();
        books  = findBooksByAuthor(author);
        // success
      } catch(reason) {
        // failure
      }
      ```

      Errback Example

      ```js

      function foundBooks(books) {

      }

      function failure(reason) {

      }

      findAuthor(function(author, err){
        if (err) {
          failure(err);
          // failure
        } else {
          try {
            findBoooksByAuthor(author, function(books, err) {
              if (err) {
                failure(err);
              } else {
                try {
                  foundBooks(books);
                } catch(reason) {
                  failure(reason);
                }
              }
            });
          } catch(error) {
            failure(err);
          }
          // success
        }
      });
      ```

      Promise Example;

      ```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: function(onFulfillment, onRejection) {
        var parent = this;
        var state = parent._state;

        if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
          return this;
        }

        var child = new this.constructor(lib$es6$promise$$internal$$noop);
        var result = parent._result;

        if (state) {
          var callback = arguments[state - 1];
          lib$es6$promise$asap$$asap(function(){
            lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
          });
        } else {
          lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
        }

        return child;
      },

    /**
      `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(onRejection) {
        return this.then(null, onRejection);
      }
    };
    function lib$es6$promise$polyfill$$polyfill() {
      var local;

      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 && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
        return;
      }

      local.Promise = lib$es6$promise$promise$$default;
    }
    var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;

    var lib$es6$promise$umd$$ES6Promise = {
      'Promise': lib$es6$promise$promise$$default,
      'polyfill': lib$es6$promise$polyfill$$default
    };

    /* global define:true module:true window: true */
    if (typeof define === 'function' && define['amd']) {
      define(function() { return lib$es6$promise$umd$$ES6Promise; });
    } else if (typeof module !== 'undefined' && module['exports']) {
      module['exports'] = lib$es6$promise$umd$$ES6Promise;
    } else if (typeof this !== 'undefined') {
      this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
    }

    lib$es6$promise$polyfill$$default();
}).call(this);


}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{"_process":"_process"}],"hammerjs/hammer":[function(require,module,exports){
/*! Hammer.JS - v2.0.7 - 2016-04-22
 * http://hammerjs.github.io/
 *
 * Copyright (c) 2016 Jorik Tangelder;
 * Licensed under the MIT license */
(function(window, document, exportName, undefined) {
  'use strict';

var VENDOR_PREFIXES = ['', 'webkit', 'Moz', 'MS', 'ms', 'o'];
var TEST_ELEMENT = document.createElement('div');

var TYPE_FUNCTION = 'function';

var round = Math.round;
var abs = Math.abs;
var now = Date.now;

/**
 * set a timeout with a given scope
 * @param {Function} fn
 * @param {Number} timeout
 * @param {Object} context
 * @returns {number}
 */
function setTimeoutContext(fn, timeout, context) {
    return setTimeout(bindFn(fn, context), timeout);
}

/**
 * if the argument is an array, we want to execute the fn on each entry
 * if it aint an array we don't want to do a thing.
 * this is used by all the methods that accept a single and array argument.
 * @param {*|Array} arg
 * @param {String} fn
 * @param {Object} [context]
 * @returns {Boolean}
 */
function invokeArrayArg(arg, fn, context) {
    if (Array.isArray(arg)) {
        each(arg, context[fn], context);
        return true;
    }
    return false;
}

/**
 * walk objects and arrays
 * @param {Object} obj
 * @param {Function} iterator
 * @param {Object} context
 */
function each(obj, iterator, context) {
    var i;

    if (!obj) {
        return;
    }

    if (obj.forEach) {
        obj.forEach(iterator, context);
    } else if (obj.length !== undefined) {
        i = 0;
        while (i < obj.length) {
            iterator.call(context, obj[i], i, obj);
            i++;
        }
    } else {
        for (i in obj) {
            obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj);
        }
    }
}

/**
 * wrap a method with a deprecation warning and stack trace
 * @param {Function} method
 * @param {String} name
 * @param {String} message
 * @returns {Function} A new function wrapping the supplied method.
 */
function deprecate(method, name, message) {
    var deprecationMessage = 'DEPRECATED METHOD: ' + name + '\n' + message + ' AT \n';
    return function() {
        var e = new Error('get-stack-trace');
        var stack = e && e.stack ? e.stack.replace(/^[^\(]+?[\n$]/gm, '')
            .replace(/^\s+at\s+/gm, '')
            .replace(/^Object.<anonymous>\s*\(/gm, '{anonymous}()@') : 'Unknown Stack Trace';

        var log = window.console && (window.console.warn || window.console.log);
        if (log) {
            log.call(window.console, deprecationMessage, stack);
        }
        return method.apply(this, arguments);
    };
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} target
 * @param {...Object} objects_to_assign
 * @returns {Object} target
 */
var assign;
if (typeof Object.assign !== 'function') {
    assign = function assign(target) {
        if (target === undefined || target === null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }

        var output = Object(target);
        for (var index = 1; index < arguments.length; index++) {
            var source = arguments[index];
            if (source !== undefined && source !== null) {
                for (var nextKey in source) {
                    if (source.hasOwnProperty(nextKey)) {
                        output[nextKey] = source[nextKey];
                    }
                }
            }
        }
        return output;
    };
} else {
    assign = Object.assign;
}

/**
 * extend object.
 * means that properties in dest will be overwritten by the ones in src.
 * @param {Object} dest
 * @param {Object} src
 * @param {Boolean} [merge=false]
 * @returns {Object} dest
 */
var extend = deprecate(function extend(dest, src, merge) {
    var keys = Object.keys(src);
    var i = 0;
    while (i < keys.length) {
        if (!merge || (merge && dest[keys[i]] === undefined)) {
            dest[keys[i]] = src[keys[i]];
        }
        i++;
    }
    return dest;
}, 'extend', 'Use `assign`.');

/**
 * merge the values from src in the dest.
 * means that properties that exist in dest will not be overwritten by src
 * @param {Object} dest
 * @param {Object} src
 * @returns {Object} dest
 */
var merge = deprecate(function merge(dest, src) {
    return extend(dest, src, true);
}, 'merge', 'Use `assign`.');

/**
 * simple class inheritance
 * @param {Function} child
 * @param {Function} base
 * @param {Object} [properties]
 */
function inherit(child, base, properties) {
    var baseP = base.prototype,
        childP;

    childP = child.prototype = Object.create(baseP);
    childP.constructor = child;
    childP._super = baseP;

    if (properties) {
        assign(childP, properties);
    }
}

/**
 * simple function bind
 * @param {Function} fn
 * @param {Object} context
 * @returns {Function}
 */
function bindFn(fn, context) {
    return function boundFn() {
        return fn.apply(context, arguments);
    };
}

/**
 * let a boolean value also be a function that must return a boolean
 * this first item in args will be used as the context
 * @param {Boolean|Function} val
 * @param {Array} [args]
 * @returns {Boolean}
 */
function boolOrFn(val, args) {
    if (typeof val == TYPE_FUNCTION) {
        return val.apply(args ? args[0] || undefined : undefined, args);
    }
    return val;
}

/**
 * use the val2 when val1 is undefined
 * @param {*} val1
 * @param {*} val2
 * @returns {*}
 */
function ifUndefined(val1, val2) {
    return (val1 === undefined) ? val2 : val1;
}

/**
 * addEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */
function addEventListeners(target, types, handler) {
    each(splitStr(types), function(type) {
        target.addEventListener(type, handler, false);
    });
}

/**
 * removeEventListener with multiple events at once
 * @param {EventTarget} target
 * @param {String} types
 * @param {Function} handler
 */
function removeEventListeners(target, types, handler) {
    each(splitStr(types), function(type) {
        target.removeEventListener(type, handler, false);
    });
}

/**
 * find if a node is in the given parent
 * @method hasParent
 * @param {HTMLElement} node
 * @param {HTMLElement} parent
 * @return {Boolean} found
 */
function hasParent(node, parent) {
    while (node) {
        if (node == parent) {
            return true;
        }
        node = node.parentNode;
    }
    return false;
}

/**
 * small indexOf wrapper
 * @param {String} str
 * @param {String} find
 * @returns {Boolean} found
 */
function inStr(str, find) {
    return str.indexOf(find) > -1;
}

/**
 * split string on whitespace
 * @param {String} str
 * @returns {Array} words
 */
function splitStr(str) {
    return str.trim().split(/\s+/g);
}

/**
 * find if a array contains the object using indexOf or a simple polyFill
 * @param {Array} src
 * @param {String} find
 * @param {String} [findByKey]
 * @return {Boolean|Number} false when not found, or the index
 */
function inArray(src, find, findByKey) {
    if (src.indexOf && !findByKey) {
        return src.indexOf(find);
    } else {
        var i = 0;
        while (i < src.length) {
            if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) {
                return i;
            }
            i++;
        }
        return -1;
    }
}

/**
 * convert array-like objects to real arrays
 * @param {Object} obj
 * @returns {Array}
 */
function toArray(obj) {
    return Array.prototype.slice.call(obj, 0);
}

/**
 * unique array with objects based on a key (like 'id') or just by the array's value
 * @param {Array} src [{id:1},{id:2},{id:1}]
 * @param {String} [key]
 * @param {Boolean} [sort=False]
 * @returns {Array} [{id:1},{id:2}]
 */
function uniqueArray(src, key, sort) {
    var results = [];
    var values = [];
    var i = 0;

    while (i < src.length) {
        var val = key ? src[i][key] : src[i];
        if (inArray(values, val) < 0) {
            results.push(src[i]);
        }
        values[i] = val;
        i++;
    }

    if (sort) {
        if (!key) {
            results = results.sort();
        } else {
            results = results.sort(function sortUniqueArray(a, b) {
                return a[key] > b[key];
            });
        }
    }

    return results;
}

/**
 * get the prefixed property
 * @param {Object} obj
 * @param {String} property
 * @returns {String|Undefined} prefixed
 */
function prefixed(obj, property) {
    var prefix, prop;
    var camelProp = property[0].toUpperCase() + property.slice(1);

    var i = 0;
    while (i < VENDOR_PREFIXES.length) {
        prefix = VENDOR_PREFIXES[i];
        prop = (prefix) ? prefix + camelProp : property;

        if (prop in obj) {
            return prop;
        }
        i++;
    }
    return undefined;
}

/**
 * get a unique id
 * @returns {number} uniqueId
 */
var _uniqueId = 1;
function uniqueId() {
    return _uniqueId++;
}

/**
 * get the window object of an element
 * @param {HTMLElement} element
 * @returns {DocumentView|Window}
 */
function getWindowForElement(element) {
    var doc = element.ownerDocument || element;
    return (doc.defaultView || doc.parentWindow || window);
}

var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i;

var SUPPORT_TOUCH = ('ontouchstart' in window);
var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined;
var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent);

var INPUT_TYPE_TOUCH = 'touch';
var INPUT_TYPE_PEN = 'pen';
var INPUT_TYPE_MOUSE = 'mouse';
var INPUT_TYPE_KINECT = 'kinect';

var COMPUTE_INTERVAL = 25;

var INPUT_START = 1;
var INPUT_MOVE = 2;
var INPUT_END = 4;
var INPUT_CANCEL = 8;

var DIRECTION_NONE = 1;
var DIRECTION_LEFT = 2;
var DIRECTION_RIGHT = 4;
var DIRECTION_UP = 8;
var DIRECTION_DOWN = 16;

var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT;
var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN;
var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;

var PROPS_XY = ['x', 'y'];
var PROPS_CLIENT_XY = ['clientX', 'clientY'];

/**
 * create new input type manager
 * @param {Manager} manager
 * @param {Function} callback
 * @returns {Input}
 * @constructor
 */
function Input(manager, callback) {
    var self = this;
    this.manager = manager;
    this.callback = callback;
    this.element = manager.element;
    this.target = manager.options.inputTarget;

    // smaller wrapper around the handler, for the scope and the enabled state of the manager,
    // so when disabled the input events are completely bypassed.
    this.domHandler = function(ev) {
        if (boolOrFn(manager.options.enable, [manager])) {
            self.handler(ev);
        }
    };

    this.init();

}

Input.prototype = {
    /**
     * should handle the inputEvent data and trigger the callback
     * @virtual
     */
    handler: function() { },

    /**
     * bind the events
     */
    init: function() {
        this.evEl && addEventListeners(this.element, this.evEl, this.domHandler);
        this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler);
        this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
    },

    /**
     * unbind the events
     */
    destroy: function() {
        this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler);
        this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler);
        this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler);
    }
};

/**
 * create new input type manager
 * called by the Manager constructor
 * @param {Hammer} manager
 * @returns {Input}
 */
function createInputInstance(manager) {
    var Type;
    var inputClass = manager.options.inputClass;

    if (inputClass) {
        Type = inputClass;
    } else if (SUPPORT_POINTER_EVENTS) {
        Type = PointerEventInput;
    } else if (SUPPORT_ONLY_TOUCH) {
        Type = TouchInput;
    } else if (!SUPPORT_TOUCH) {
        Type = MouseInput;
    } else {
        Type = TouchMouseInput;
    }
    return new (Type)(manager, inputHandler);
}

/**
 * handle input events
 * @param {Manager} manager
 * @param {String} eventType
 * @param {Object} input
 */
function inputHandler(manager, eventType, input) {
    var pointersLen = input.pointers.length;
    var changedPointersLen = input.changedPointers.length;
    var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0));
    var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0));

    input.isFirst = !!isFirst;
    input.isFinal = !!isFinal;

    if (isFirst) {
        manager.session = {};
    }

    // source event is the normalized value of the domEvents
    // like 'touchstart, mouseup, pointerdown'
    input.eventType = eventType;

    // compute scale, rotation etc
    computeInputData(manager, input);

    // emit secret event
    manager.emit('hammer.input', input);

    manager.recognize(input);
    manager.session.prevInput = input;
}

/**
 * extend the data with some usable properties like scale, rotate, velocity etc
 * @param {Object} manager
 * @param {Object} input
 */
function computeInputData(manager, input) {
    var session = manager.session;
    var pointers = input.pointers;
    var pointersLength = pointers.length;

    // store the first input to calculate the distance and direction
    if (!session.firstInput) {
        session.firstInput = simpleCloneInputData(input);
    }

    // to compute scale and rotation we need to store the multiple touches
    if (pointersLength > 1 && !session.firstMultiple) {
        session.firstMultiple = simpleCloneInputData(input);
    } else if (pointersLength === 1) {
        session.firstMultiple = false;
    }

    var firstInput = session.firstInput;
    var firstMultiple = session.firstMultiple;
    var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center;

    var center = input.center = getCenter(pointers);
    input.timeStamp = now();
    input.deltaTime = input.timeStamp - firstInput.timeStamp;

    input.angle = getAngle(offsetCenter, center);
    input.distance = getDistance(offsetCenter, center);

    computeDeltaXY(session, input);
    input.offsetDirection = getDirection(input.deltaX, input.deltaY);

    var overallVelocity = getVelocity(input.deltaTime, input.deltaX, input.deltaY);
    input.overallVelocityX = overallVelocity.x;
    input.overallVelocityY = overallVelocity.y;
    input.overallVelocity = (abs(overallVelocity.x) > abs(overallVelocity.y)) ? overallVelocity.x : overallVelocity.y;

    input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1;
    input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0;

    input.maxPointers = !session.prevInput ? input.pointers.length : ((input.pointers.length >
        session.prevInput.maxPointers) ? input.pointers.length : session.prevInput.maxPointers);

    computeIntervalInputData(session, input);

    // find the correct target
    var target = manager.element;
    if (hasParent(input.srcEvent.target, target)) {
        target = input.srcEvent.target;
    }
    input.target = target;
}

function computeDeltaXY(session, input) {
    var center = input.center;
    var offset = session.offsetDelta || {};
    var prevDelta = session.prevDelta || {};
    var prevInput = session.prevInput || {};

    if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) {
        prevDelta = session.prevDelta = {
            x: prevInput.deltaX || 0,
            y: prevInput.deltaY || 0
        };

        offset = session.offsetDelta = {
            x: center.x,
            y: center.y
        };
    }

    input.deltaX = prevDelta.x + (center.x - offset.x);
    input.deltaY = prevDelta.y + (center.y - offset.y);
}

/**
 * velocity is calculated every x ms
 * @param {Object} session
 * @param {Object} input
 */
function computeIntervalInputData(session, input) {
    var last = session.lastInterval || input,
        deltaTime = input.timeStamp - last.timeStamp,
        velocity, velocityX, velocityY, direction;

    if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) {
        var deltaX = input.deltaX - last.deltaX;
        var deltaY = input.deltaY - last.deltaY;

        var v = getVelocity(deltaTime, deltaX, deltaY);
        velocityX = v.x;
        velocityY = v.y;
        velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y;
        direction = getDirection(deltaX, deltaY);

        session.lastInterval = input;
    } else {
        // use latest velocity info if it doesn't overtake a minimum period
        velocity = last.velocity;
        velocityX = last.velocityX;
        velocityY = last.velocityY;
        direction = last.direction;
    }

    input.velocity = velocity;
    input.velocityX = velocityX;
    input.velocityY = velocityY;
    input.direction = direction;
}

/**
 * create a simple clone from the input used for storage of firstInput and firstMultiple
 * @param {Object} input
 * @returns {Object} clonedInputData
 */
function simpleCloneInputData(input) {
    // make a simple copy of the pointers because we will get a reference if we don't
    // we only need clientXY for the calculations
    var pointers = [];
    var i = 0;
    while (i < input.pointers.length) {
        pointers[i] = {
            clientX: round(input.pointers[i].clientX),
            clientY: round(input.pointers[i].clientY)
        };
        i++;
    }

    return {
        timeStamp: now(),
        pointers: pointers,
        center: getCenter(pointers),
        deltaX: input.deltaX,
        deltaY: input.deltaY
    };
}

/**
 * get the center of all the pointers
 * @param {Array} pointers
 * @return {Object} center contains `x` and `y` properties
 */
function getCenter(pointers) {
    var pointersLength = pointers.length;

    // no need to loop when only one touch
    if (pointersLength === 1) {
        return {
            x: round(pointers[0].clientX),
            y: round(pointers[0].clientY)
        };
    }

    var x = 0, y = 0, i = 0;
    while (i < pointersLength) {
        x += pointers[i].clientX;
        y += pointers[i].clientY;
        i++;
    }

    return {
        x: round(x / pointersLength),
        y: round(y / pointersLength)
    };
}

/**
 * calculate the velocity between two points. unit is in px per ms.
 * @param {Number} deltaTime
 * @param {Number} x
 * @param {Number} y
 * @return {Object} velocity `x` and `y`
 */
function getVelocity(deltaTime, x, y) {
    return {
        x: x / deltaTime || 0,
        y: y / deltaTime || 0
    };
}

/**
 * get the direction between two points
 * @param {Number} x
 * @param {Number} y
 * @return {Number} direction
 */
function getDirection(x, y) {
    if (x === y) {
        return DIRECTION_NONE;
    }

    if (abs(x) >= abs(y)) {
        return x < 0 ? DIRECTION_LEFT : DIRECTION_RIGHT;
    }
    return y < 0 ? DIRECTION_UP : DIRECTION_DOWN;
}

/**
 * calculate the absolute distance between two points
 * @param {Object} p1 {x, y}
 * @param {Object} p2 {x, y}
 * @param {Array} [props] containing x and y keys
 * @return {Number} distance
 */
function getDistance(p1, p2, props) {
    if (!props) {
        props = PROPS_XY;
    }
    var x = p2[props[0]] - p1[props[0]],
        y = p2[props[1]] - p1[props[1]];

    return Math.sqrt((x * x) + (y * y));
}

/**
 * calculate the angle between two coordinates
 * @param {Object} p1
 * @param {Object} p2
 * @param {Array} [props] containing x and y keys
 * @return {Number} angle
 */
function getAngle(p1, p2, props) {
    if (!props) {
        props = PROPS_XY;
    }
    var x = p2[props[0]] - p1[props[0]],
        y = p2[props[1]] - p1[props[1]];
    return Math.atan2(y, x) * 180 / Math.PI;
}

/**
 * calculate the rotation degrees between two pointersets
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} rotation
 */
function getRotation(start, end) {
    return getAngle(end[1], end[0], PROPS_CLIENT_XY) + getAngle(start[1], start[0], PROPS_CLIENT_XY);
}

/**
 * calculate the scale factor between two pointersets
 * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out
 * @param {Array} start array of pointers
 * @param {Array} end array of pointers
 * @return {Number} scale
 */
function getScale(start, end) {
    return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY);
}

var MOUSE_INPUT_MAP = {
    mousedown: INPUT_START,
    mousemove: INPUT_MOVE,
    mouseup: INPUT_END
};

var MOUSE_ELEMENT_EVENTS = 'mousedown';
var MOUSE_WINDOW_EVENTS = 'mousemove mouseup';

/**
 * Mouse events input
 * @constructor
 * @extends Input
 */
function MouseInput() {
    this.evEl = MOUSE_ELEMENT_EVENTS;
    this.evWin = MOUSE_WINDOW_EVENTS;

    this.pressed = false; // mousedown state

    Input.apply(this, arguments);
}

inherit(MouseInput, Input, {
    /**
     * handle mouse events
     * @param {Object} ev
     */
    handler: function MEhandler(ev) {
        var eventType = MOUSE_INPUT_MAP[ev.type];

        // on start we want to have the left mouse button down
        if (eventType & INPUT_START && ev.button === 0) {
            this.pressed = true;
        }

        if (eventType & INPUT_MOVE && ev.which !== 1) {
            eventType = INPUT_END;
        }

        // mouse must be down
        if (!this.pressed) {
            return;
        }

        if (eventType & INPUT_END) {
            this.pressed = false;
        }

        this.callback(this.manager, eventType, {
            pointers: [ev],
            changedPointers: [ev],
            pointerType: INPUT_TYPE_MOUSE,
            srcEvent: ev
        });
    }
});

var POINTER_INPUT_MAP = {
    pointerdown: INPUT_START,
    pointermove: INPUT_MOVE,
    pointerup: INPUT_END,
    pointercancel: INPUT_CANCEL,
    pointerout: INPUT_CANCEL
};

// in IE10 the pointer types is defined as an enum
var IE10_POINTER_TYPE_ENUM = {
    2: INPUT_TYPE_TOUCH,
    3: INPUT_TYPE_PEN,
    4: INPUT_TYPE_MOUSE,
    5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816
};

var POINTER_ELEMENT_EVENTS = 'pointerdown';
var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel';

// IE10 has prefixed support, and case-sensitive
if (window.MSPointerEvent && !window.PointerEvent) {
    POINTER_ELEMENT_EVENTS = 'MSPointerDown';
    POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel';
}

/**
 * Pointer events input
 * @constructor
 * @extends Input
 */
function PointerEventInput() {
    this.evEl = POINTER_ELEMENT_EVENTS;
    this.evWin = POINTER_WINDOW_EVENTS;

    Input.apply(this, arguments);

    this.store = (this.manager.session.pointerEvents = []);
}

inherit(PointerEventInput, Input, {
    /**
     * handle mouse events
     * @param {Object} ev
     */
    handler: function PEhandler(ev) {
        var store = this.store;
        var removePointer = false;

        var eventTypeNormalized = ev.type.toLowerCase().replace('ms', '');
        var eventType = POINTER_INPUT_MAP[eventTypeNormalized];
        var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType;

        var isTouch = (pointerType == INPUT_TYPE_TOUCH);

        // get index of the event in the store
        var storeIndex = inArray(store, ev.pointerId, 'pointerId');

        // start and mouse must be down
        if (eventType & INPUT_START && (ev.button === 0 || isTouch)) {
            if (storeIndex < 0) {
                store.push(ev);
                storeIndex = store.length - 1;
            }
        } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
            removePointer = true;
        }

        // it not found, so the pointer hasn't been down (so it's probably a hover)
        if (storeIndex < 0) {
            return;
        }

        // update the event in the store
        store[storeIndex] = ev;

        this.callback(this.manager, eventType, {
            pointers: store,
            changedPointers: [ev],
            pointerType: pointerType,
            srcEvent: ev
        });

        if (removePointer) {
            // remove from the store
            store.splice(storeIndex, 1);
        }
    }
});

var SINGLE_TOUCH_INPUT_MAP = {
    touchstart: INPUT_START,
    touchmove: INPUT_MOVE,
    touchend: INPUT_END,
    touchcancel: INPUT_CANCEL
};

var SINGLE_TOUCH_TARGET_EVENTS = 'touchstart';
var SINGLE_TOUCH_WINDOW_EVENTS = 'touchstart touchmove touchend touchcancel';

/**
 * Touch events input
 * @constructor
 * @extends Input
 */
function SingleTouchInput() {
    this.evTarget = SINGLE_TOUCH_TARGET_EVENTS;
    this.evWin = SINGLE_TOUCH_WINDOW_EVENTS;
    this.started = false;

    Input.apply(this, arguments);
}

inherit(SingleTouchInput, Input, {
    handler: function TEhandler(ev) {
        var type = SINGLE_TOUCH_INPUT_MAP[ev.type];

        // should we handle the touch events?
        if (type === INPUT_START) {
            this.started = true;
        }

        if (!this.started) {
            return;
        }

        var touches = normalizeSingleTouches.call(this, ev, type);

        // when done, reset the started state
        if (type & (INPUT_END | INPUT_CANCEL) && touches[0].length - touches[1].length === 0) {
            this.started = false;
        }

        this.callback(this.manager, type, {
            pointers: touches[0],
            changedPointers: touches[1],
            pointerType: INPUT_TYPE_TOUCH,
            srcEvent: ev
        });
    }
});

/**
 * @this {TouchInput}
 * @param {Object} ev
 * @param {Number} type flag
 * @returns {undefined|Array} [all, changed]
 */
function normalizeSingleTouches(ev, type) {
    var all = toArray(ev.touches);
    var changed = toArray(ev.changedTouches);

    if (type & (INPUT_END | INPUT_CANCEL)) {
        all = uniqueArray(all.concat(changed), 'identifier', true);
    }

    return [all, changed];
}

var TOUCH_INPUT_MAP = {
    touchstart: INPUT_START,
    touchmove: INPUT_MOVE,
    touchend: INPUT_END,
    touchcancel: INPUT_CANCEL
};

var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel';

/**
 * Multi-user touch events input
 * @constructor
 * @extends Input
 */
function TouchInput() {
    this.evTarget = TOUCH_TARGET_EVENTS;
    this.targetIds = {};

    Input.apply(this, arguments);
}

inherit(TouchInput, Input, {
    handler: function MTEhandler(ev) {
        var type = TOUCH_INPUT_MAP[ev.type];
        var touches = getTouches.call(this, ev, type);
        if (!touches) {
            return;
        }

        this.callback(this.manager, type, {
            pointers: touches[0],
            changedPointers: touches[1],
            pointerType: INPUT_TYPE_TOUCH,
            srcEvent: ev
        });
    }
});

/**
 * @this {TouchInput}
 * @param {Object} ev
 * @param {Number} type flag
 * @returns {undefined|Array} [all, changed]
 */
function getTouches(ev, type) {
    var allTouches = toArray(ev.touches);
    var targetIds = this.targetIds;

    // when there is only one touch, the process can be simplified
    if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) {
        targetIds[allTouches[0].identifier] = true;
        return [allTouches, allTouches];
    }

    var i,
        targetTouches,
        changedTouches = toArray(ev.changedTouches),
        changedTargetTouches = [],
        target = this.target;

    // get target touches from touches
    targetTouches = allTouches.filter(function(touch) {
        return hasParent(touch.target, target);
    });

    // collect touches
    if (type === INPUT_START) {
        i = 0;
        while (i < targetTouches.length) {
            targetIds[targetTouches[i].identifier] = true;
            i++;
        }
    }

    // filter changed touches to only contain touches that exist in the collected target ids
    i = 0;
    while (i < changedTouches.length) {
        if (targetIds[changedTouches[i].identifier]) {
            changedTargetTouches.push(changedTouches[i]);
        }

        // cleanup removed touches
        if (type & (INPUT_END | INPUT_CANCEL)) {
            delete targetIds[changedTouches[i].identifier];
        }
        i++;
    }

    if (!changedTargetTouches.length) {
        return;
    }

    return [
        // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel'
        uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true),
        changedTargetTouches
    ];
}

/**
 * Combined touch and mouse input
 *
 * Touch has a higher priority then mouse, and while touching no mouse events are allowed.
 * This because touch devices also emit mouse events while doing a touch.
 *
 * @constructor
 * @extends Input
 */

var DEDUP_TIMEOUT = 2500;
var DEDUP_DISTANCE = 25;

function TouchMouseInput() {
    Input.apply(this, arguments);

    var handler = bindFn(this.handler, this);
    this.touch = new TouchInput(this.manager, handler);
    this.mouse = new MouseInput(this.manager, handler);

    this.primaryTouch = null;
    this.lastTouches = [];
}

inherit(TouchMouseInput, Input, {
    /**
     * handle mouse and touch events
     * @param {Hammer} manager
     * @param {String} inputEvent
     * @param {Object} inputData
     */
    handler: function TMEhandler(manager, inputEvent, inputData) {
        var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH),
            isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE);

        if (isMouse && inputData.sourceCapabilities && inputData.sourceCapabilities.firesTouchEvents) {
            return;
        }

        // when we're in a touch event, record touches to  de-dupe synthetic mouse event
        if (isTouch) {
            recordTouches.call(this, inputEvent, inputData);
        } else if (isMouse && isSyntheticEvent.call(this, inputData)) {
            return;
        }

        this.callback(manager, inputEvent, inputData);
    },

    /**
     * remove the event listeners
     */
    destroy: function destroy() {
        this.touch.destroy();
        this.mouse.destroy();
    }
});

function recordTouches(eventType, eventData) {
    if (eventType & INPUT_START) {
        this.primaryTouch = eventData.changedPointers[0].identifier;
        setLastTouch.call(this, eventData);
    } else if (eventType & (INPUT_END | INPUT_CANCEL)) {
        setLastTouch.call(this, eventData);
    }
}

function setLastTouch(eventData) {
    var touch = eventData.changedPointers[0];

    if (touch.identifier === this.primaryTouch) {
        var lastTouch = {x: touch.clientX, y: touch.clientY};
        this.lastTouches.push(lastTouch);
        var lts = this.lastTouches;
        var removeLastTouch = function() {
            var i = lts.indexOf(lastTouch);
            if (i > -1) {
                lts.splice(i, 1);
            }
        };
        setTimeout(removeLastTouch, DEDUP_TIMEOUT);
    }
}

function isSyntheticEvent(eventData) {
    var x = eventData.srcEvent.clientX, y = eventData.srcEvent.clientY;
    for (var i = 0; i < this.lastTouches.length; i++) {
        var t = this.lastTouches[i];
        var dx = Math.abs(x - t.x), dy = Math.abs(y - t.y);
        if (dx <= DEDUP_DISTANCE && dy <= DEDUP_DISTANCE) {
            return true;
        }
    }
    return false;
}

var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction');
var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined;

// magical touchAction value
var TOUCH_ACTION_COMPUTE = 'compute';
var TOUCH_ACTION_AUTO = 'auto';
var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented
var TOUCH_ACTION_NONE = 'none';
var TOUCH_ACTION_PAN_X = 'pan-x';
var TOUCH_ACTION_PAN_Y = 'pan-y';
var TOUCH_ACTION_MAP = getTouchActionProps();

/**
 * Touch Action
 * sets the touchAction property or uses the js alternative
 * @param {Manager} manager
 * @param {String} value
 * @constructor
 */
function TouchAction(manager, value) {
    this.manager = manager;
    this.set(value);
}

TouchAction.prototype = {
    /**
     * set the touchAction value on the element or enable the polyfill
     * @param {String} value
     */
    set: function(value) {
        // find out the touch-action by the event handlers
        if (value == TOUCH_ACTION_COMPUTE) {
            value = this.compute();
        }

        if (NATIVE_TOUCH_ACTION && this.manager.element.style && TOUCH_ACTION_MAP[value]) {
            this.manager.element.style[PREFIXED_TOUCH_ACTION] = value;
        }
        this.actions = value.toLowerCase().trim();
    },

    /**
     * just re-set the touchAction value
     */
    update: function() {
        this.set(this.manager.options.touchAction);
    },

    /**
     * compute the value for the touchAction property based on the recognizer's settings
     * @returns {String} value
     */
    compute: function() {
        var actions = [];
        each(this.manager.recognizers, function(recognizer) {
            if (boolOrFn(recognizer.options.enable, [recognizer])) {
                actions = actions.concat(recognizer.getTouchAction());
            }
        });
        return cleanTouchActions(actions.join(' '));
    },

    /**
     * this method is called on each input cycle and provides the preventing of the browser behavior
     * @param {Object} input
     */
    preventDefaults: function(input) {
        var srcEvent = input.srcEvent;
        var direction = input.offsetDirection;

        // if the touch action did prevented once this session
        if (this.manager.session.prevented) {
            srcEvent.preventDefault();
            return;
        }

        var actions = this.actions;
        var hasNone = inStr(actions, TOUCH_ACTION_NONE) && !TOUCH_ACTION_MAP[TOUCH_ACTION_NONE];
        var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_Y];
        var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X) && !TOUCH_ACTION_MAP[TOUCH_ACTION_PAN_X];

        if (hasNone) {
            //do not prevent defaults if this is a tap gesture

            var isTapPointer = input.pointers.length === 1;
            var isTapMovement = input.distance < 2;
            var isTapTouchTime = input.deltaTime < 250;

            if (isTapPointer && isTapMovement && isTapTouchTime) {
                return;
            }
        }

        if (hasPanX && hasPanY) {
            // `pan-x pan-y` means browser handles all scrolling/panning, do not prevent
            return;
        }

        if (hasNone ||
            (hasPanY && direction & DIRECTION_HORIZONTAL) ||
            (hasPanX && direction & DIRECTION_VERTICAL)) {
            return this.preventSrc(srcEvent);
        }
    },

    /**
     * call preventDefault to prevent the browser's default behavior (scrolling in most cases)
     * @param {Object} srcEvent
     */
    preventSrc: function(srcEvent) {
        this.manager.session.prevented = true;
        srcEvent.preventDefault();
    }
};

/**
 * when the touchActions are collected they are not a valid value, so we need to clean things up. *
 * @param {String} actions
 * @returns {*}
 */
function cleanTouchActions(actions) {
    // none
    if (inStr(actions, TOUCH_ACTION_NONE)) {
        return TOUCH_ACTION_NONE;
    }

    var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X);
    var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y);

    // if both pan-x and pan-y are set (different recognizers
    // for different directions, e.g. horizontal pan but vertical swipe?)
    // we need none (as otherwise with pan-x pan-y combined none of these
    // recognizers will work, since the browser would handle all panning
    if (hasPanX && hasPanY) {
        return TOUCH_ACTION_NONE;
    }

    // pan-x OR pan-y
    if (hasPanX || hasPanY) {
        return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y;
    }

    // manipulation
    if (inStr(actions, TOUCH_ACTION_MANIPULATION)) {
        return TOUCH_ACTION_MANIPULATION;
    }

    return TOUCH_ACTION_AUTO;
}

function getTouchActionProps() {
    if (!NATIVE_TOUCH_ACTION) {
        return false;
    }
    var touchMap = {};
    var cssSupports = window.CSS && window.CSS.supports;
    ['auto', 'manipulation', 'pan-y', 'pan-x', 'pan-x pan-y', 'none'].forEach(function(val) {

        // If css.supports is not supported but there is native touch-action assume it supports
        // all values. This is the case for IE 10 and 11.
        touchMap[val] = cssSupports ? window.CSS.supports('touch-action', val) : true;
    });
    return touchMap;
}

/**
 * Recognizer flow explained; *
 * All recognizers have the initial state of POSSIBLE when a input session starts.
 * The definition of a input session is from the first input until the last input, with all it's movement in it. *
 * Example session for mouse-input: mousedown -> mousemove -> mouseup
 *
 * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed
 * which determines with state it should be.
 *
 * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to
 * POSSIBLE to give it another change on the next cycle.
 *
 *               Possible
 *                  |
 *            +-----+---------------+
 *            |                     |
 *      +-----+-----+               |
 *      |           |               |
 *   Failed      Cancelled          |
 *                          +-------+------+
 *                          |              |
 *                      Recognized       Began
 *                                         |
 *                                      Changed
 *                                         |
 *                                  Ended/Recognized
 */
var STATE_POSSIBLE = 1;
var STATE_BEGAN = 2;
var STATE_CHANGED = 4;
var STATE_ENDED = 8;
var STATE_RECOGNIZED = STATE_ENDED;
var STATE_CANCELLED = 16;
var STATE_FAILED = 32;

/**
 * Recognizer
 * Every recognizer needs to extend from this class.
 * @constructor
 * @param {Object} options
 */
function Recognizer(options) {
    this.options = assign({}, this.defaults, options || {});

    this.id = uniqueId();

    this.manager = null;

    // default is enable true
    this.options.enable = ifUndefined(this.options.enable, true);

    this.state = STATE_POSSIBLE;

    this.simultaneous = {};
    this.requireFail = [];
}

Recognizer.prototype = {
    /**
     * @virtual
     * @type {Object}
     */
    defaults: {},

    /**
     * set options
     * @param {Object} options
     * @return {Recognizer}
     */
    set: function(options) {
        assign(this.options, options);

        // also update the touchAction, in case something changed about the directions/enabled state
        this.manager && this.manager.touchAction.update();
        return this;
    },

    /**
     * recognize simultaneous with an other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    recognizeWith: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) {
            return this;
        }

        var simultaneous = this.simultaneous;
        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        if (!simultaneous[otherRecognizer.id]) {
            simultaneous[otherRecognizer.id] = otherRecognizer;
            otherRecognizer.recognizeWith(this);
        }
        return this;
    },

    /**
     * drop the simultaneous link. it doesnt remove the link on the other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    dropRecognizeWith: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) {
            return this;
        }

        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        delete this.simultaneous[otherRecognizer.id];
        return this;
    },

    /**
     * recognizer can only run when an other is failing
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    requireFailure: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) {
            return this;
        }

        var requireFail = this.requireFail;
        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        if (inArray(requireFail, otherRecognizer) === -1) {
            requireFail.push(otherRecognizer);
            otherRecognizer.requireFailure(this);
        }
        return this;
    },

    /**
     * drop the requireFailure link. it does not remove the link on the other recognizer.
     * @param {Recognizer} otherRecognizer
     * @returns {Recognizer} this
     */
    dropRequireFailure: function(otherRecognizer) {
        if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) {
            return this;
        }

        otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this);
        var index = inArray(this.requireFail, otherRecognizer);
        if (index > -1) {
            this.requireFail.splice(index, 1);
        }
        return this;
    },

    /**
     * has require failures boolean
     * @returns {boolean}
     */
    hasRequireFailures: function() {
        return this.requireFail.length > 0;
    },

    /**
     * if the recognizer can recognize simultaneous with an other recognizer
     * @param {Recognizer} otherRecognizer
     * @returns {Boolean}
     */
    canRecognizeWith: function(otherRecognizer) {
        return !!this.simultaneous[otherRecognizer.id];
    },

    /**
     * You should use `tryEmit` instead of `emit` directly to check
     * that all the needed recognizers has failed before emitting.
     * @param {Object} input
     */
    emit: function(input) {
        var self = this;
        var state = this.state;

        function emit(event) {
            self.manager.emit(event, input);
        }

        // 'panstart' and 'panmove'
        if (state < STATE_ENDED) {
            emit(self.options.event + stateStr(state));
        }

        emit(self.options.event); // simple 'eventName' events

        if (input.additionalEvent) { // additional event(panleft, panright, pinchin, pinchout...)
            emit(input.additionalEvent);
        }

        // panend and pancancel
        if (state >= STATE_ENDED) {
            emit(self.options.event + stateStr(state));
        }
    },

    /**
     * Check that all the require failure recognizers has failed,
     * if true, it emits a gesture event,
     * otherwise, setup the state to FAILED.
     * @param {Object} input
     */
    tryEmit: function(input) {
        if (this.canEmit()) {
            return this.emit(input);
        }
        // it's failing anyway
        this.state = STATE_FAILED;
    },

    /**
     * can we emit?
     * @returns {boolean}
     */
    canEmit: function() {
        var i = 0;
        while (i < this.requireFail.length) {
            if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) {
                return false;
            }
            i++;
        }
        return true;
    },

    /**
     * update the recognizer
     * @param {Object} inputData
     */
    recognize: function(inputData) {
        // make a new copy of the inputData
        // so we can change the inputData without messing up the other recognizers
        var inputDataClone = assign({}, inputData);

        // is is enabled and allow recognizing?
        if (!boolOrFn(this.options.enable, [this, inputDataClone])) {
            this.reset();
            this.state = STATE_FAILED;
            return;
        }

        // reset when we've reached the end
        if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) {
            this.state = STATE_POSSIBLE;
        }

        this.state = this.process(inputDataClone);

        // the recognizer has recognized a gesture
        // so trigger an event
        if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) {
            this.tryEmit(inputDataClone);
        }
    },

    /**
     * return the state of the recognizer
     * the actual recognizing happens in this method
     * @virtual
     * @param {Object} inputData
     * @returns {Const} STATE
     */
    process: function(inputData) { }, // jshint ignore:line

    /**
     * return the preferred touch-action
     * @virtual
     * @returns {Array}
     */
    getTouchAction: function() { },

    /**
     * called when the gesture isn't allowed to recognize
     * like when another is being recognized or it is disabled
     * @virtual
     */
    reset: function() { }
};

/**
 * get a usable string, used as event postfix
 * @param {Const} state
 * @returns {String} state
 */
function stateStr(state) {
    if (state & STATE_CANCELLED) {
        return 'cancel';
    } else if (state & STATE_ENDED) {
        return 'end';
    } else if (state & STATE_CHANGED) {
        return 'move';
    } else if (state & STATE_BEGAN) {
        return 'start';
    }
    return '';
}

/**
 * direction cons to string
 * @param {Const} direction
 * @returns {String}
 */
function directionStr(direction) {
    if (direction == DIRECTION_DOWN) {
        return 'down';
    } else if (direction == DIRECTION_UP) {
        return 'up';
    } else if (direction == DIRECTION_LEFT) {
        return 'left';
    } else if (direction == DIRECTION_RIGHT) {
        return 'right';
    }
    return '';
}

/**
 * get a recognizer by name if it is bound to a manager
 * @param {Recognizer|String} otherRecognizer
 * @param {Recognizer} recognizer
 * @returns {Recognizer}
 */
function getRecognizerByNameIfManager(otherRecognizer, recognizer) {
    var manager = recognizer.manager;
    if (manager) {
        return manager.get(otherRecognizer);
    }
    return otherRecognizer;
}

/**
 * This recognizer is just used as a base for the simple attribute recognizers.
 * @constructor
 * @extends Recognizer
 */
function AttrRecognizer() {
    Recognizer.apply(this, arguments);
}

inherit(AttrRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof AttrRecognizer
     */
    defaults: {
        /**
         * @type {Number}
         * @default 1
         */
        pointers: 1
    },

    /**
     * Used to check if it the recognizer receives valid input, like input.distance > 10.
     * @memberof AttrRecognizer
     * @param {Object} input
     * @returns {Boolean} recognized
     */
    attrTest: function(input) {
        var optionPointers = this.options.pointers;
        return optionPointers === 0 || input.pointers.length === optionPointers;
    },

    /**
     * Process the input and return the state for the recognizer
     * @memberof AttrRecognizer
     * @param {Object} input
     * @returns {*} State
     */
    process: function(input) {
        var state = this.state;
        var eventType = input.eventType;

        var isRecognized = state & (STATE_BEGAN | STATE_CHANGED);
        var isValid = this.attrTest(input);

        // on cancel input and we've recognized before, return STATE_CANCELLED
        if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) {
            return state | STATE_CANCELLED;
        } else if (isRecognized || isValid) {
            if (eventType & INPUT_END) {
                return state | STATE_ENDED;
            } else if (!(state & STATE_BEGAN)) {
                return STATE_BEGAN;
            }
            return state | STATE_CHANGED;
        }
        return STATE_FAILED;
    }
});

/**
 * Pan
 * Recognized when the pointer is down and moved in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */
function PanRecognizer() {
    AttrRecognizer.apply(this, arguments);

    this.pX = null;
    this.pY = null;
}

inherit(PanRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof PanRecognizer
     */
    defaults: {
        event: 'pan',
        threshold: 10,
        pointers: 1,
        direction: DIRECTION_ALL
    },

    getTouchAction: function() {
        var direction = this.options.direction;
        var actions = [];
        if (direction & DIRECTION_HORIZONTAL) {
            actions.push(TOUCH_ACTION_PAN_Y);
        }
        if (direction & DIRECTION_VERTICAL) {
            actions.push(TOUCH_ACTION_PAN_X);
        }
        return actions;
    },

    directionTest: function(input) {
        var options = this.options;
        var hasMoved = true;
        var distance = input.distance;
        var direction = input.direction;
        var x = input.deltaX;
        var y = input.deltaY;

        // lock to axis?
        if (!(direction & options.direction)) {
            if (options.direction & DIRECTION_HORIZONTAL) {
                direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT;
                hasMoved = x != this.pX;
                distance = Math.abs(input.deltaX);
            } else {
                direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN;
                hasMoved = y != this.pY;
                distance = Math.abs(input.deltaY);
            }
        }
        input.direction = direction;
        return hasMoved && distance > options.threshold && direction & options.direction;
    },

    attrTest: function(input) {
        return AttrRecognizer.prototype.attrTest.call(this, input) &&
            (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input)));
    },

    emit: function(input) {

        this.pX = input.deltaX;
        this.pY = input.deltaY;

        var direction = directionStr(input.direction);

        if (direction) {
            input.additionalEvent = this.options.event + direction;
        }
        this._super.emit.call(this, input);
    }
});

/**
 * Pinch
 * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out).
 * @constructor
 * @extends AttrRecognizer
 */
function PinchRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(PinchRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof PinchRecognizer
     */
    defaults: {
        event: 'pinch',
        threshold: 0,
        pointers: 2
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_NONE];
    },

    attrTest: function(input) {
        return this._super.attrTest.call(this, input) &&
            (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN);
    },

    emit: function(input) {
        if (input.scale !== 1) {
            var inOut = input.scale < 1 ? 'in' : 'out';
            input.additionalEvent = this.options.event + inOut;
        }
        this._super.emit.call(this, input);
    }
});

/**
 * Press
 * Recognized when the pointer is down for x ms without any movement.
 * @constructor
 * @extends Recognizer
 */
function PressRecognizer() {
    Recognizer.apply(this, arguments);

    this._timer = null;
    this._input = null;
}

inherit(PressRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof PressRecognizer
     */
    defaults: {
        event: 'press',
        pointers: 1,
        time: 251, // minimal time of the pointer to be pressed
        threshold: 9 // a minimal movement is ok, but keep it low
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_AUTO];
    },

    process: function(input) {
        var options = this.options;
        var validPointers = input.pointers.length === options.pointers;
        var validMovement = input.distance < options.threshold;
        var validTime = input.deltaTime > options.time;

        this._input = input;

        // we only allow little movement
        // and we've reached an end event, so a tap is possible
        if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) {
            this.reset();
        } else if (input.eventType & INPUT_START) {
            this.reset();
            this._timer = setTimeoutContext(function() {
                this.state = STATE_RECOGNIZED;
                this.tryEmit();
            }, options.time, this);
        } else if (input.eventType & INPUT_END) {
            return STATE_RECOGNIZED;
        }
        return STATE_FAILED;
    },

    reset: function() {
        clearTimeout(this._timer);
    },

    emit: function(input) {
        if (this.state !== STATE_RECOGNIZED) {
            return;
        }

        if (input && (input.eventType & INPUT_END)) {
            this.manager.emit(this.options.event + 'up', input);
        } else {
            this._input.timeStamp = now();
            this.manager.emit(this.options.event, this._input);
        }
    }
});

/**
 * Rotate
 * Recognized when two or more pointer are moving in a circular motion.
 * @constructor
 * @extends AttrRecognizer
 */
function RotateRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(RotateRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof RotateRecognizer
     */
    defaults: {
        event: 'rotate',
        threshold: 0,
        pointers: 2
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_NONE];
    },

    attrTest: function(input) {
        return this._super.attrTest.call(this, input) &&
            (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN);
    }
});

/**
 * Swipe
 * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction.
 * @constructor
 * @extends AttrRecognizer
 */
function SwipeRecognizer() {
    AttrRecognizer.apply(this, arguments);
}

inherit(SwipeRecognizer, AttrRecognizer, {
    /**
     * @namespace
     * @memberof SwipeRecognizer
     */
    defaults: {
        event: 'swipe',
        threshold: 10,
        velocity: 0.3,
        direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL,
        pointers: 1
    },

    getTouchAction: function() {
        return PanRecognizer.prototype.getTouchAction.call(this);
    },

    attrTest: function(input) {
        var direction = this.options.direction;
        var velocity;

        if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) {
            velocity = input.overallVelocity;
        } else if (direction & DIRECTION_HORIZONTAL) {
            velocity = input.overallVelocityX;
        } else if (direction & DIRECTION_VERTICAL) {
            velocity = input.overallVelocityY;
        }

        return this._super.attrTest.call(this, input) &&
            direction & input.offsetDirection &&
            input.distance > this.options.threshold &&
            input.maxPointers == this.options.pointers &&
            abs(velocity) > this.options.velocity && input.eventType & INPUT_END;
    },

    emit: function(input) {
        var direction = directionStr(input.offsetDirection);
        if (direction) {
            this.manager.emit(this.options.event + direction, input);
        }

        this.manager.emit(this.options.event, input);
    }
});

/**
 * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur
 * between the given interval and position. The delay option can be used to recognize multi-taps without firing
 * a single tap.
 *
 * The eventData from the emitted event contains the property `tapCount`, which contains the amount of
 * multi-taps being recognized.
 * @constructor
 * @extends Recognizer
 */
function TapRecognizer() {
    Recognizer.apply(this, arguments);

    // previous time and center,
    // used for tap counting
    this.pTime = false;
    this.pCenter = false;

    this._timer = null;
    this._input = null;
    this.count = 0;
}

inherit(TapRecognizer, Recognizer, {
    /**
     * @namespace
     * @memberof PinchRecognizer
     */
    defaults: {
        event: 'tap',
        pointers: 1,
        taps: 1,
        interval: 300, // max time between the multi-tap taps
        time: 250, // max time of the pointer to be down (like finger on the screen)
        threshold: 9, // a minimal movement is ok, but keep it low
        posThreshold: 10 // a multi-tap can be a bit off the initial position
    },

    getTouchAction: function() {
        return [TOUCH_ACTION_MANIPULATION];
    },

    process: function(input) {
        var options = this.options;

        var validPointers = input.pointers.length === options.pointers;
        var validMovement = input.distance < options.threshold;
        var validTouchTime = input.deltaTime < options.time;

        this.reset();

        if ((input.eventType & INPUT_START) && (this.count === 0)) {
            return this.failTimeout();
        }

        // we only allow little movement
        // and we've reached an end event, so a tap is possible
        if (validMovement && validTouchTime && validPointers) {
            if (input.eventType != INPUT_END) {
                return this.failTimeout();
            }

            var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true;
            var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold;

            this.pTime = input.timeStamp;
            this.pCenter = input.center;

            if (!validMultiTap || !validInterval) {
                this.count = 1;
            } else {
                this.count += 1;
            }

            this._input = input;

            // if tap count matches we have recognized it,
            // else it has began recognizing...
            var tapCount = this.count % options.taps;
            if (tapCount === 0) {
                // no failing requirements, immediately trigger the tap event
                // or wait as long as the multitap interval to trigger
                if (!this.hasRequireFailures()) {
                    return STATE_RECOGNIZED;
                } else {
                    this._timer = setTimeoutContext(function() {
                        this.state = STATE_RECOGNIZED;
                        this.tryEmit();
                    }, options.interval, this);
                    return STATE_BEGAN;
                }
            }
        }
        return STATE_FAILED;
    },

    failTimeout: function() {
        this._timer = setTimeoutContext(function() {
            this.state = STATE_FAILED;
        }, this.options.interval, this);
        return STATE_FAILED;
    },

    reset: function() {
        clearTimeout(this._timer);
    },

    emit: function() {
        if (this.state == STATE_RECOGNIZED) {
            this._input.tapCount = this.count;
            this.manager.emit(this.options.event, this._input);
        }
    }
});

/**
 * Simple way to create a manager with a default set of recognizers.
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */
function Hammer(element, options) {
    options = options || {};
    options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset);
    return new Manager(element, options);
}

/**
 * @const {string}
 */
Hammer.VERSION = '2.0.7';

/**
 * default settings
 * @namespace
 */
Hammer.defaults = {
    /**
     * set if DOM events are being triggered.
     * But this is slower and unused by simple implementations, so disabled by default.
     * @type {Boolean}
     * @default false
     */
    domEvents: false,

    /**
     * The value for the touchAction property/fallback.
     * When set to `compute` it will magically set the correct value based on the added recognizers.
     * @type {String}
     * @default compute
     */
    touchAction: TOUCH_ACTION_COMPUTE,

    /**
     * @type {Boolean}
     * @default true
     */
    enable: true,

    /**
     * EXPERIMENTAL FEATURE -- can be removed/changed
     * Change the parent input target element.
     * If Null, then it is being set the to main element.
     * @type {Null|EventTarget}
     * @default null
     */
    inputTarget: null,

    /**
     * force an input class
     * @type {Null|Function}
     * @default null
     */
    inputClass: null,

    /**
     * Default recognizer setup when calling `Hammer()`
     * When creating a new Manager these will be skipped.
     * @type {Array}
     */
    preset: [
        // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...]
        [RotateRecognizer, {enable: false}],
        [PinchRecognizer, {enable: false}, ['rotate']],
        [SwipeRecognizer, {direction: DIRECTION_HORIZONTAL}],
        [PanRecognizer, {direction: DIRECTION_HORIZONTAL}, ['swipe']],
        [TapRecognizer],
        [TapRecognizer, {event: 'doubletap', taps: 2}, ['tap']],
        [PressRecognizer]
    ],

    /**
     * Some CSS properties can be used to improve the working of Hammer.
     * Add them to this method and they will be set when creating a new Manager.
     * @namespace
     */
    cssProps: {
        /**
         * Disables text selection to improve the dragging gesture. Mainly for desktop browsers.
         * @type {String}
         * @default 'none'
         */
        userSelect: 'none',

        /**
         * Disable the Windows Phone grippers when pressing an element.
         * @type {String}
         * @default 'none'
         */
        touchSelect: 'none',

        /**
         * Disables the default callout shown when you touch and hold a touch target.
         * On iOS, when you touch and hold a touch target such as a link, Safari displays
         * a callout containing information about the link. This property allows you to disable that callout.
         * @type {String}
         * @default 'none'
         */
        touchCallout: 'none',

        /**
         * Specifies whether zooming is enabled. Used by IE10>
         * @type {String}
         * @default 'none'
         */
        contentZooming: 'none',

        /**
         * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers.
         * @type {String}
         * @default 'none'
         */
        userDrag: 'none',

        /**
         * Overrides the highlight color shown when the user taps a link or a JavaScript
         * clickable element in iOS. This property obeys the alpha value, if specified.
         * @type {String}
         * @default 'rgba(0,0,0,0)'
         */
        tapHighlightColor: 'rgba(0,0,0,0)'
    }
};

var STOP = 1;
var FORCED_STOP = 2;

/**
 * Manager
 * @param {HTMLElement} element
 * @param {Object} [options]
 * @constructor
 */
function Manager(element, options) {
    this.options = assign({}, Hammer.defaults, options || {});

    this.options.inputTarget = this.options.inputTarget || element;

    this.handlers = {};
    this.session = {};
    this.recognizers = [];
    this.oldCssProps = {};

    this.element = element;
    this.input = createInputInstance(this);
    this.touchAction = new TouchAction(this, this.options.touchAction);

    toggleCssProps(this, true);

    each(this.options.recognizers, function(item) {
        var recognizer = this.add(new (item[0])(item[1]));
        item[2] && recognizer.recognizeWith(item[2]);
        item[3] && recognizer.requireFailure(item[3]);
    }, this);
}

Manager.prototype = {
    /**
     * set options
     * @param {Object} options
     * @returns {Manager}
     */
    set: function(options) {
        assign(this.options, options);

        // Options that need a little more setup
        if (options.touchAction) {
            this.touchAction.update();
        }
        if (options.inputTarget) {
            // Clean up existing event listeners and reinitialize
            this.input.destroy();
            this.input.target = options.inputTarget;
            this.input.init();
        }
        return this;
    },

    /**
     * stop recognizing for this session.
     * This session will be discarded, when a new [input]start event is fired.
     * When forced, the recognizer cycle is stopped immediately.
     * @param {Boolean} [force]
     */
    stop: function(force) {
        this.session.stopped = force ? FORCED_STOP : STOP;
    },

    /**
     * run the recognizers!
     * called by the inputHandler function on every movement of the pointers (touches)
     * it walks through all the recognizers and tries to detect the gesture that is being made
     * @param {Object} inputData
     */
    recognize: function(inputData) {
        var session = this.session;
        if (session.stopped) {
            return;
        }

        // run the touch-action polyfill
        this.touchAction.preventDefaults(inputData);

        var recognizer;
        var recognizers = this.recognizers;

        // this holds the recognizer that is being recognized.
        // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED
        // if no recognizer is detecting a thing, it is set to `null`
        var curRecognizer = session.curRecognizer;

        // reset when the last recognizer is recognized
        // or when we're in a new session
        if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) {
            curRecognizer = session.curRecognizer = null;
        }

        var i = 0;
        while (i < recognizers.length) {
            recognizer = recognizers[i];

            // find out if we are allowed try to recognize the input for this one.
            // 1.   allow if the session is NOT forced stopped (see the .stop() method)
            // 2.   allow if we still haven't recognized a gesture in this session, or the this recognizer is the one
            //      that is being recognized.
            // 3.   allow if the recognizer is allowed to run simultaneous with the current recognized recognizer.
            //      this can be setup with the `recognizeWith()` method on the recognizer.
            if (session.stopped !== FORCED_STOP && ( // 1
                    !curRecognizer || recognizer == curRecognizer || // 2
                    recognizer.canRecognizeWith(curRecognizer))) { // 3
                recognizer.recognize(inputData);
            } else {
                recognizer.reset();
            }

            // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the
            // current active recognizer. but only if we don't already have an active recognizer
            if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) {
                curRecognizer = session.curRecognizer = recognizer;
            }
            i++;
        }
    },

    /**
     * get a recognizer by its event name.
     * @param {Recognizer|String} recognizer
     * @returns {Recognizer|Null}
     */
    get: function(recognizer) {
        if (recognizer instanceof Recognizer) {
            return recognizer;
        }

        var recognizers = this.recognizers;
        for (var i = 0; i < recognizers.length; i++) {
            if (recognizers[i].options.event == recognizer) {
                return recognizers[i];
            }
        }
        return null;
    },

    /**
     * add a recognizer to the manager
     * existing recognizers with the same event name will be removed
     * @param {Recognizer} recognizer
     * @returns {Recognizer|Manager}
     */
    add: function(recognizer) {
        if (invokeArrayArg(recognizer, 'add', this)) {
            return this;
        }

        // remove existing
        var existing = this.get(recognizer.options.event);
        if (existing) {
            this.remove(existing);
        }

        this.recognizers.push(recognizer);
        recognizer.manager = this;

        this.touchAction.update();
        return recognizer;
    },

    /**
     * remove a recognizer by name or instance
     * @param {Recognizer|String} recognizer
     * @returns {Manager}
     */
    remove: function(recognizer) {
        if (invokeArrayArg(recognizer, 'remove', this)) {
            return this;
        }

        recognizer = this.get(recognizer);

        // let's make sure this recognizer exists
        if (recognizer) {
            var recognizers = this.recognizers;
            var index = inArray(recognizers, recognizer);

            if (index !== -1) {
                recognizers.splice(index, 1);
                this.touchAction.update();
            }
        }

        return this;
    },

    /**
     * bind event
     * @param {String} events
     * @param {Function} handler
     * @returns {EventEmitter} this
     */
    on: function(events, handler) {
        if (events === undefined) {
            return;
        }
        if (handler === undefined) {
            return;
        }

        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            handlers[event] = handlers[event] || [];
            handlers[event].push(handler);
        });
        return this;
    },

    /**
     * unbind event, leave emit blank to remove all handlers
     * @param {String} events
     * @param {Function} [handler]
     * @returns {EventEmitter} this
     */
    off: function(events, handler) {
        if (events === undefined) {
            return;
        }

        var handlers = this.handlers;
        each(splitStr(events), function(event) {
            if (!handler) {
                delete handlers[event];
            } else {
                handlers[event] && handlers[event].splice(inArray(handlers[event], handler), 1);
            }
        });
        return this;
    },

    /**
     * emit event to the listeners
     * @param {String} event
     * @param {Object} data
     */
    emit: function(event, data) {
        // we also want to trigger dom events
        if (this.options.domEvents) {
            triggerDomEvent(event, data);
        }

        // no handlers, so skip it all
        var handlers = this.handlers[event] && this.handlers[event].slice();
        if (!handlers || !handlers.length) {
            return;
        }

        data.type = event;
        data.preventDefault = function() {
            data.srcEvent.preventDefault();
        };

        var i = 0;
        while (i < handlers.length) {
            handlers[i](data);
            i++;
        }
    },

    /**
     * destroy the manager and unbinds all events
     * it doesn't unbind dom events, that is the user own responsibility
     */
    destroy: function() {
        this.element && toggleCssProps(this, false);

        this.handlers = {};
        this.session = {};
        this.input.destroy();
        this.element = null;
    }
};

/**
 * add/remove the css properties as defined in manager.options.cssProps
 * @param {Manager} manager
 * @param {Boolean} add
 */
function toggleCssProps(manager, add) {
    var element = manager.element;
    if (!element.style) {
        return;
    }
    var prop;
    each(manager.options.cssProps, function(value, name) {
        prop = prefixed(element.style, name);
        if (add) {
            manager.oldCssProps[prop] = element.style[prop];
            element.style[prop] = value;
        } else {
            element.style[prop] = manager.oldCssProps[prop] || '';
        }
    });
    if (!add) {
        manager.oldCssProps = {};
    }
}

/**
 * trigger dom event
 * @param {String} event
 * @param {Object} data
 */
function triggerDomEvent(event, data) {
    var gestureEvent = document.createEvent('Event');
    gestureEvent.initEvent(event, true, true);
    gestureEvent.gesture = data;
    data.target.dispatchEvent(gestureEvent);
}

assign(Hammer, {
    INPUT_START: INPUT_START,
    INPUT_MOVE: INPUT_MOVE,
    INPUT_END: INPUT_END,
    INPUT_CANCEL: INPUT_CANCEL,

    STATE_POSSIBLE: STATE_POSSIBLE,
    STATE_BEGAN: STATE_BEGAN,
    STATE_CHANGED: STATE_CHANGED,
    STATE_ENDED: STATE_ENDED,
    STATE_RECOGNIZED: STATE_RECOGNIZED,
    STATE_CANCELLED: STATE_CANCELLED,
    STATE_FAILED: STATE_FAILED,

    DIRECTION_NONE: DIRECTION_NONE,
    DIRECTION_LEFT: DIRECTION_LEFT,
    DIRECTION_RIGHT: DIRECTION_RIGHT,
    DIRECTION_UP: DIRECTION_UP,
    DIRECTION_DOWN: DIRECTION_DOWN,
    DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL,
    DIRECTION_VERTICAL: DIRECTION_VERTICAL,
    DIRECTION_ALL: DIRECTION_ALL,

    Manager: Manager,
    Input: Input,
    TouchAction: TouchAction,

    TouchInput: TouchInput,
    MouseInput: MouseInput,
    PointerEventInput: PointerEventInput,
    TouchMouseInput: TouchMouseInput,
    SingleTouchInput: SingleTouchInput,

    Recognizer: Recognizer,
    AttrRecognizer: AttrRecognizer,
    Tap: TapRecognizer,
    Pan: PanRecognizer,
    Swipe: SwipeRecognizer,
    Pinch: PinchRecognizer,
    Rotate: RotateRecognizer,
    Press: PressRecognizer,

    on: addEventListeners,
    off: removeEventListeners,
    each: each,
    merge: merge,
    extend: extend,
    assign: assign,
    inherit: inherit,
    bindFn: bindFn,
    prefixed: prefixed
});

// this prevents errors when Hammer is loaded in the presence of an AMD
//  style loader but by script tag, not by the loader.
var freeGlobal = (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {})); // jshint ignore:line
freeGlobal.Hammer = Hammer;

if (typeof define === 'function' && define.amd) {
    define(function() {
        return Hammer;
    });
} else if (typeof module != 'undefined' && module.exports) {
    module.exports = Hammer;
} else {
    window[exportName] = Hammer;
}

})(window, document, 'Hammer');

},{}],"jquery-mousewheel":[function(require,module,exports){
/*!
 * jQuery Mousewheel 3.1.13
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: '3.1.12',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
            // Clean up the data we added to the element
            $.removeData(this, 'mousewheel-line-height');
            $.removeData(this, 'mousewheel-page-height');
        },

        getLineHeight: function(elem) {
            var $elem = $(elem),
                $parent = $elem['offsetParent' in $.fn ? 'offsetParent' : 'parent']();
            if (!$parent.length) {
                $parent = $('body');
            }
            return parseInt($parent.css('fontSize'), 10) || parseInt($elem.css('fontSize'), 10) || 16;
        },

        getPageHeight: function(elem) {
            return $(elem).height();
        },

        settings: {
            adjustOldDeltas: true, // see shouldAdjustOldDeltas() below
            normalizeOffset: true  // calls getBoundingClientRect for each event
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0,
            offsetX    = 0,
            offsetY    = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );

        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Normalise offsetX and offsetY properties
        if ( special.settings.normalizeOffset && this.getBoundingClientRect ) {
            var boundingRect = this.getBoundingClientRect();
            offsetX = event.clientX - boundingRect.left;
            offsetY = event.clientY - boundingRect.top;
        }

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        event.offsetX = offsetX;
        event.offsetY = offsetY;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
    }

}));

},{}],"jquery":[function(require,module,exports){
/*!
 * jQuery JavaScript Library v2.2.4
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2016-05-20T17:23Z
 */

(function( global, factory ) {

	if ( typeof module === "object" && typeof module.exports === "object" ) {
		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket #14549 for more info.
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}

// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

// Support: Firefox 18+
// Can't be in strict mode, several libs including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
//"use strict";
var arr = [];

var document = window.document;

var slice = arr.slice;

var concat = arr.concat;

var push = arr.push;

var indexOf = arr.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var support = {};



var
	version = "2.2.4",

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	},

	// Support: Android<4.1
	// Make sure we trim BOM and NBSP
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

	// Matches dashed string for camelizing
	rmsPrefix = /^-ms-/,
	rdashAlpha = /-([\da-z])/gi,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn = jQuery.prototype = {

	// The current version of jQuery being used
	jquery: version,

	constructor: jQuery,

	// Start with an empty selector
	selector: "",

	// The default length of a jQuery object is 0
	length: 0,

	toArray: function() {
		return slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {
		return num != null ?

			// Return just the one element from the set
			( num < 0 ? this[ num + this.length ] : this[ num ] ) :

			// Return all the elements in a clean array
			slice.call( this );
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;
		ret.context = this.context;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	each: function( callback ) {
		return jQuery.each( this, callback );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map( this, function( elem, i ) {
			return callback.call( elem, i, elem );
		} ) );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i < 0 ? len : 0 );
		return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
	},

	end: function() {
		return this.prevObject || this.constructor();
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: arr.sort,
	splice: arr.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// Skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
		target = {};
	}

	// Extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i < length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = jQuery.isArray( copy ) ) ) ) {

					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && jQuery.isArray( src ) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject( src ) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	isFunction: function( obj ) {
		return jQuery.type( obj ) === "function";
	},

	isArray: Array.isArray,

	isWindow: function( obj ) {
		return obj != null && obj === obj.window;
	},

	isNumeric: function( obj ) {

		// parseFloat NaNs numeric-cast false positives (null|true|false|"")
		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
		// subtraction forces infinities to NaN
		// adding 1 corrects loss of precision from parseFloat (#15100)
		var realStringObj = obj && obj.toString();
		return !jQuery.isArray( obj ) && ( realStringObj - parseFloat( realStringObj ) + 1 ) >= 0;
	},

	isPlainObject: function( obj ) {
		var key;

		// Not plain objects:
		// - Any object or value whose internal [[Class]] property is not "[object Object]"
		// - DOM nodes
		// - window
		if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
			return false;
		}

		// Not own constructor property must be Object
		if ( obj.constructor &&
				!hasOwn.call( obj, "constructor" ) &&
				!hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) {
			return false;
		}

		// Own properties are enumerated firstly, so to speed up,
		// if last one is own, then all properties are own
		for ( key in obj ) {}

		return key === undefined || hasOwn.call( obj, key );
	},

	isEmptyObject: function( obj ) {
		var name;
		for ( name in obj ) {
			return false;
		}
		return true;
	},

	type: function( obj ) {
		if ( obj == null ) {
			return obj + "";
		}

		// Support: Android<4.0, iOS<6 (functionish RegExp)
		return typeof obj === "object" || typeof obj === "function" ?
			class2type[ toString.call( obj ) ] || "object" :
			typeof obj;
	},

	// Evaluates a script in a global context
	globalEval: function( code ) {
		var script,
			indirect = eval;

		code = jQuery.trim( code );

		if ( code ) {

			// If the code includes a valid, prologue position
			// strict mode pragma, execute code by injecting a
			// script tag into the document.
			if ( code.indexOf( "use strict" ) === 1 ) {
				script = document.createElement( "script" );
				script.text = code;
				document.head.appendChild( script ).parentNode.removeChild( script );
			} else {

				// Otherwise, avoid the DOM node creation, insertion
				// and removal by using an indirect global eval

				indirect( code );
			}
		}
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Support: IE9-11+
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	nodeName: function( elem, name ) {
		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i < length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},

	// Support: Android<4.1
	trim: function( text ) {
		return text == null ?
			"" :
			( text + "" ).replace( rtrim, "" );
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
					[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		return arr == null ? -1 : indexOf.call( arr, elem, i );
	},

	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		for ( ; j < len; j++ ) {
			first[ i++ ] = second[ j ];
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		var tmp, args, proxy;

		if ( typeof context === "string" ) {
			tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		args = slice.call( arguments, 2 );
		proxy = function() {
			return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
		};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || jQuery.guid++;

		return proxy;
	},

	now: Date.now,

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

// JSHint would error on this code due to the Symbol not being defined in ES5.
// Defining this global in .jshintrc would create a danger of using the global
// unguarded in another place, it seems safer to just disable JSHint for these
// three lines.
/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
	jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
/* jshint ignore: end */

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );

function isArrayLike( obj ) {

	// Support: iOS 8.2 (not reproducible in simulator)
	// `in` check used to prevent JIT error (gh-2145)
	// hasOwn isn't used here due to false negatives
	// regarding Nodelist length in IE
	var length = !!obj && "length" in obj && obj.length,
		type = jQuery.type( obj );

	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.2.1
 * http://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2015-10-17
 */
(function( window ) {

var i,
	support,
	Expr,
	getText,
	isXML,
	tokenize,
	compile,
	select,
	outermostContext,
	sortInput,
	hasDuplicate,

	// Local document vars
	setDocument,
	document,
	docElem,
	documentIsHTML,
	rbuggyQSA,
	rbuggyMatches,
	matches,
	contains,

	// Instance-specific data
	expando = "sizzle" + 1 * new Date(),
	preferredDoc = window.document,
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	// General-purpose constants
	MAX_NEGATIVE = 1 << 31,

	// Instance methods
	hasOwn = ({}).hasOwnProperty,
	arr = [],
	pop = arr.pop,
	push_native = arr.push,
	push = arr.push,
	slice = arr.slice,
	// Use a stripped-down indexOf as it's faster than native
	// http://jsperf.com/thor-indexof-vs-for/5
	indexOf = function( list, elem ) {
		var i = 0,
			len = list.length;
		for ( ; i < len; i++ ) {
			if ( list[i] === elem ) {
				return i;
			}
		}
		return -1;
	},

	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",

	// Regular expressions

	// http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",

	// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +
		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
		"*\\]",

	pseudos = ":(" + identifier + ")(?:\\((" +
		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
		// 3. anything else (capture 2)
		".*" +
		")\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rwhitespace = new RegExp( whitespace + "+", "g" ),
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),

	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),

	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		"ID": new RegExp( "^#(" + identifier + ")" ),
		"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
		"TAG": new RegExp( "^(" + identifier + "|[*])" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	rnative = /^[^{]+\{\s*\[native \w/,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rsibling = /[+~]/,
	rescape = /'|\\/g,

	// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
	funescape = function( _, escaped, escapedWhitespace ) {
		var high = "0x" + escaped - 0x10000;
		// NaN means non-codepoint
		// Support: Firefox<24
		// Workaround erroneous numeric interpretation of +"0x"
		return high !== high || escapedWhitespace ?
			escaped :
			high < 0 ?
				// BMP codepoint
				String.fromCharCode( high + 0x10000 ) :
				// Supplemental Plane codepoint (surrogate pair)
				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
	},

	// Used for iframes
	// See setDocument()
	// Removing the function wrapper causes a "Permission Denied"
	// error in IE
	unloadHandler = function() {
		setDocument();
	};

// Optimize for push.apply( _, NodeList )
try {
	push.apply(
		(arr = slice.call( preferredDoc.childNodes )),
		preferredDoc.childNodes
	);
	// Support: Android<4.0
	// Detect silently failing push.apply
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = { apply: arr.length ?

		// Leverage slice if possible
		function( target, els ) {
			push_native.apply( target, slice.call(els) );
		} :

		// Support: IE<9
		// Otherwise append directly
		function( target, els ) {
			var j = target.length,
				i = 0;
			// Can't trust NodeList.length
			while ( (target[j++] = els[i++]) ) {}
			target.length = j - 1;
		}
	};
}

function Sizzle( selector, context, results, seed ) {
	var m, i, elem, nid, nidselect, match, groups, newSelector,
		newContext = context && context.ownerDocument,

		// nodeType defaults to 9, since context defaults to document
		nodeType = context ? context.nodeType : 9;

	results = results || [];

	// Return early from calls with invalid selector or context
	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	// Try to shortcut find operations (as opposed to filters) in HTML documents
	if ( !seed ) {

		if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
			setDocument( context );
		}
		context = context || document;

		if ( documentIsHTML ) {

			// If the selector is sufficiently simple, try using a "get*By*" DOM method
			// (excepting DocumentFragment context, where the methods don't exist)
			if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {

				// ID selector
				if ( (m = match[1]) ) {

					// Document context
					if ( nodeType === 9 ) {
						if ( (elem = context.getElementById( m )) ) {

							// Support: IE, Opera, Webkit
							// TODO: identify versions
							// getElementById can match elements by name instead of ID
							if ( elem.id === m ) {
								results.push( elem );
								return results;
							}
						} else {
							return results;
						}

					// Element context
					} else {

						// Support: IE, Opera, Webkit
						// TODO: identify versions
						// getElementById can match elements by name instead of ID
						if ( newContext && (elem = newContext.getElementById( m )) &&
							contains( context, elem ) &&
							elem.id === m ) {

							results.push( elem );
							return results;
						}
					}

				// Type selector
				} else if ( match[2] ) {
					push.apply( results, context.getElementsByTagName( selector ) );
					return results;

				// Class selector
				} else if ( (m = match[3]) && support.getElementsByClassName &&
					context.getElementsByClassName ) {

					push.apply( results, context.getElementsByClassName( m ) );
					return results;
				}
			}

			// Take advantage of querySelectorAll
			if ( support.qsa &&
				!compilerCache[ selector + " " ] &&
				(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {

				if ( nodeType !== 1 ) {
					newContext = context;
					newSelector = selector;

				// qSA looks outside Element context, which is not what we want
				// Thanks to Andrew Dupont for this workaround technique
				// Support: IE <=8
				// Exclude object elements
				} else if ( context.nodeName.toLowerCase() !== "object" ) {

					// Capture the context ID, setting it first if necessary
					if ( (nid = context.getAttribute( "id" )) ) {
						nid = nid.replace( rescape, "\\$&" );
					} else {
						context.setAttribute( "id", (nid = expando) );
					}

					// Prefix every selector in the list
					groups = tokenize( selector );
					i = groups.length;
					nidselect = ridentifier.test( nid ) ? "#" + nid : "[id='" + nid + "']";
					while ( i-- ) {
						groups[i] = nidselect + " " + toSelector( groups[i] );
					}
					newSelector = groups.join( "," );

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
						context;
				}

				if ( newSelector ) {
					try {
						push.apply( results,
							newContext.querySelectorAll( newSelector )
						);
						return results;
					} catch ( qsaError ) {
					} finally {
						if ( nid === expando ) {
							context.removeAttribute( "id" );
						}
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed );
}

/**
 * Create key-value caches of limited size
 * @returns {function(string, object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var keys = [];

	function cache( key, value ) {
		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
		if ( keys.push( key + " " ) > Expr.cacheLength ) {
			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return (cache[ key + " " ] = value);
	}
	return cache;
}

/**
 * Mark a function for special use by Sizzle
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created div and expects a boolean result
 */
function assert( fn ) {
	var div = document.createElement("div");

	try {
		return !!fn( div );
	} catch (e) {
		return false;
	} finally {
		// Remove from its parent by default
		if ( div.parentNode ) {
			div.parentNode.removeChild( div );
		}
		// release memory in IE
		div = null;
	}
}

/**
 * Adds the same handler for all of the specified attrs
 * @param {String} attrs Pipe-separated list of attributes
 * @param {Function} handler The method that will be applied
 */
function addHandle( attrs, handler ) {
	var arr = attrs.split("|"),
		i = arr.length;

	while ( i-- ) {
		Expr.attrHandle[ arr[i] ] = handler;
	}
}

/**
 * Checks document order of two siblings
 * @param {Element} a
 * @param {Element} b
 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
 */
function siblingCheck( a, b ) {
	var cur = b && a,
		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
			( ~b.sourceIndex || MAX_NEGATIVE ) -
			( ~a.sourceIndex || MAX_NEGATIVE );

	// Use IE sourceIndex if available on both nodes
	if ( diff ) {
		return diff;
	}

	// Check if b follows a
	if ( cur ) {
		while ( (cur = cur.nextSibling) ) {
			if ( cur === b ) {
				return -1;
			}
		}
	}

	return a ? 1 : -1;
}

/**
 * Returns a function to use in pseudos for input types
 * @param {String} type
 */
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for buttons
 * @param {String} type
 */
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return (name === "input" || name === "button") && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for positionals
 * @param {Function} fn
 */
function createPositionalPseudo( fn ) {
	return markFunction(function( argument ) {
		argument = +argument;
		return markFunction(function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ (j = matchIndexes[i]) ] ) {
					seed[j] = !(matches[j] = seed[j]);
				}
			}
		});
	});
}

/**
 * Checks a node for validity as a Sizzle context
 * @param {Element|Object=} context
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */
function testContext( context ) {
	return context && typeof context.getElementsByTagName !== "undefined" && context;
}

// Expose support vars for convenience
support = Sizzle.support = {};

/**
 * Detects XML nodes
 * @param {Element|Object} elem An element or a document
 * @returns {Boolean} True iff elem is a non-HTML XML node
 */
isXML = Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833)
	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [doc] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
setDocument = Sizzle.setDocument = function( node ) {
	var hasCompare, parent,
		doc = node ? node.ownerDocument || node : preferredDoc;

	// Return early if doc is invalid or already selected
	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Update global variables
	document = doc;
	docElem = document.documentElement;
	documentIsHTML = !isXML( document );

	// Support: IE 9-11, Edge
	// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
	if ( (parent = document.defaultView) && parent.top !== parent ) {
		// Support: IE 11
		if ( parent.addEventListener ) {
			parent.addEventListener( "unload", unloadHandler, false );

		// Support: IE 9 - 10 only
		} else if ( parent.attachEvent ) {
			parent.attachEvent( "onunload", unloadHandler );
		}
	}

	/* Attributes
	---------------------------------------------------------------------- */

	// Support: IE<8
	// Verify that getAttribute really returns attributes and not properties
	// (excepting IE8 booleans)
	support.attributes = assert(function( div ) {
		div.className = "i";
		return !div.getAttribute("className");
	});

	/* getElement(s)By*
	---------------------------------------------------------------------- */

	// Check if getElementsByTagName("*") returns only elements
	support.getElementsByTagName = assert(function( div ) {
		div.appendChild( document.createComment("") );
		return !div.getElementsByTagName("*").length;
	});

	// Support: IE<9
	support.getElementsByClassName = rnative.test( document.getElementsByClassName );

	// Support: IE<10
	// Check if getElementById returns elements by name
	// The broken getElementById methods don't pick up programatically-set names,
	// so use a roundabout getElementsByName test
	support.getById = assert(function( div ) {
		docElem.appendChild( div ).id = expando;
		return !document.getElementsByName || !document.getElementsByName( expando ).length;
	});

	// ID find and filter
	if ( support.getById ) {
		Expr.find["ID"] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var m = context.getElementById( id );
				return m ? [ m ] : [];
			}
		};
		Expr.filter["ID"] = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute("id") === attrId;
			};
		};
	} else {
		// Support: IE6/7
		// getElementById is not reliable as a find shortcut
		delete Expr.find["ID"];

		Expr.filter["ID"] =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== "undefined" &&
					elem.getAttributeNode("id");
				return node && node.value === attrId;
			};
		};
	}

	// Tag
	Expr.find["TAG"] = support.getElementsByTagName ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( tag );

			// DocumentFragment nodes don't have gEBTN
			} else if ( support.qsa ) {
				return context.querySelectorAll( tag );
			}
		} :

		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,
				// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( (elem = results[i++]) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Class
	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
		if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
			return context.getElementsByClassName( className );
		}
	};

	/* QSA/matchesSelector
	---------------------------------------------------------------------- */

	// QSA and matchesSelector support

	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
	rbuggyMatches = [];

	// qSa(:focus) reports false when true (Chrome 21)
	// We allow this because of a bug in IE8/9 that throws an error
	// whenever `document.activeElement` is accessed on an iframe
	// So, we allow :focus to pass through QSA all the time to avoid the IE error
	// See http://bugs.jquery.com/ticket/13378
	rbuggyQSA = [];

	if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert(function( div ) {
			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explicitly
			// setting a boolean content attribute,
			// since its presence should be enough
			// http://bugs.jquery.com/ticket/12359
			docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" +
				"<select id='" + expando + "-\r\\' msallowcapture=''>" +
				"<option selected=''></option></select>";

			// Support: IE8, Opera 11-12.16
			// Nothing should be selected when empty strings follow ^= or $= or *=
			// The test attribute must be unknown in Opera but "safe" for WinRT
			// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
			if ( div.querySelectorAll("[msallowcapture^='']").length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
			}

			// Support: IE8
			// Boolean attributes and "value" are not treated correctly
			if ( !div.querySelectorAll("[selected]").length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
			}

			// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
			if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
				rbuggyQSA.push("~=");
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here and will not see later tests
			if ( !div.querySelectorAll(":checked").length ) {
				rbuggyQSA.push(":checked");
			}

			// Support: Safari 8+, iOS 8+
			// https://bugs.webkit.org/show_bug.cgi?id=136851
			// In-page `selector#id sibing-combinator selector` fails
			if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) {
				rbuggyQSA.push(".#.+[+~]");
			}
		});

		assert(function( div ) {
			// Support: Windows 8 Native Apps
			// The type and name attributes are restricted during .innerHTML assignment
			var input = document.createElement("input");
			input.setAttribute( "type", "hidden" );
			div.appendChild( input ).setAttribute( "name", "D" );

			// Support: IE8
			// Enforce case-sensitivity of name attribute
			if ( div.querySelectorAll("[name=d]").length ) {
				rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here and will not see later tests
			if ( !div.querySelectorAll(":enabled").length ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Opera 10-11 does not throw on post-comma invalid pseudos
			div.querySelectorAll("*,:x");
			rbuggyQSA.push(",.*:");
		});
	}

	if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
		docElem.webkitMatchesSelector ||
		docElem.mozMatchesSelector ||
		docElem.oMatchesSelector ||
		docElem.msMatchesSelector) )) ) {

		assert(function( div ) {
			// Check to see if it's possible to do matchesSelector
			// on a disconnected node (IE 9)
			support.disconnectedMatch = matches.call( div, "div" );

			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( div, "[s!='']:x" );
			rbuggyMatches.push( "!=", pseudos );
		});
	}

	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );

	/* Contains
	---------------------------------------------------------------------- */
	hasCompare = rnative.test( docElem.compareDocumentPosition );

	// Element contains another
	// Purposefully self-exclusive
	// As in, an element does not contain itself
	contains = hasCompare || rnative.test( docElem.contains ) ?
		function( a, b ) {
			var adown = a.nodeType === 9 ? a.documentElement : a,
				bup = b && b.parentNode;
			return a === bup || !!( bup && bup.nodeType === 1 && (
				adown.contains ?
					adown.contains( bup ) :
					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
			));
		} :
		function( a, b ) {
			if ( b ) {
				while ( (b = b.parentNode) ) {
					if ( b === a ) {
						return true;
					}
				}
			}
			return false;
		};

	/* Sorting
	---------------------------------------------------------------------- */

	// Document order sorting
	sortOrder = hasCompare ?
	function( a, b ) {

		// Flag for duplicate removal
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		// Sort on method existence if only one input has compareDocumentPosition
		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
		if ( compare ) {
			return compare;
		}

		// Calculate position if both inputs belong to the same document
		compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
			a.compareDocumentPosition( b ) :

			// Otherwise we know they are disconnected
			1;

		// Disconnected nodes
		if ( compare & 1 ||
			(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {

			// Choose the first element that is related to our preferred document
			if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
				return -1;
			}
			if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
				return 1;
			}

			// Maintain original order
			return sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;
		}

		return compare & 4 ? -1 : 1;
	} :
	function( a, b ) {
		// Exit early if the nodes are identical
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		var cur,
			i = 0,
			aup = a.parentNode,
			bup = b.parentNode,
			ap = [ a ],
			bp = [ b ];

		// Parentless nodes are either documents or disconnected
		if ( !aup || !bup ) {
			return a === document ? -1 :
				b === document ? 1 :
				aup ? -1 :
				bup ? 1 :
				sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;

		// If the nodes are siblings, we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		}

		// Otherwise we need full lists of their ancestors for comparison
		cur = a;
		while ( (cur = cur.parentNode) ) {
			ap.unshift( cur );
		}
		cur = b;
		while ( (cur = cur.parentNode) ) {
			bp.unshift( cur );
		}

		// Walk down the tree looking for a discrepancy
		while ( ap[i] === bp[i] ) {
			i++;
		}

		return i ?
			// Do a sibling check if the nodes have a common ancestor
			siblingCheck( ap[i], bp[i] ) :

			// Otherwise nodes in our document sort first
			ap[i] === preferredDoc ? -1 :
			bp[i] === preferredDoc ? 1 :
			0;
	};

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	// Make sure that attribute selectors are quoted
	expr = expr.replace( rattributeQuotes, "='$1']" );

	if ( support.matchesSelector && documentIsHTML &&
		!compilerCache[ expr + " " ] &&
		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {

		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||
					// As well, disconnected nodes are said to be in a document
					// fragment in IE 9
					elem.document && elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch (e) {}
	}

	return Sizzle( expr, document, null, [ elem ] ).length > 0;
};

Sizzle.contains = function( context, elem ) {
	// Set document vars if needed
	if ( ( context.ownerDocument || context ) !== document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	var fn = Expr.attrHandle[ name.toLowerCase() ],
		// Don't get fooled by Object.prototype properties (jQuery #13807)
		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
			fn( elem, name, !documentIsHTML ) :
			undefined;

	return val !== undefined ?
		val :
		support.attributes || !documentIsHTML ?
			elem.getAttribute( name ) :
			(val = elem.getAttributeNode(name)) && val.specified ?
				val.value :
				null;
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Document sorting and removing duplicates
 * @param {ArrayLike} results
 */
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		j = 0,
		i = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	hasDuplicate = !support.detectDuplicates;
	sortInput = !support.sortStable && results.slice( 0 );
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		while ( (elem = results[i++]) ) {
			if ( elem === results[ i ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	// Clear input after sorting to release objects
	// See https://github.com/jquery/sizzle/pull/225
	sortInput = null;

	return results;
};

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( !nodeType ) {
		// If no nodeType, this is expected to be an array
		while ( (node = elem[i++]) ) {
			// Do not traverse comment nodes
			ret += getText( node );
		}
	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
		// Use textContent for elements
		// innerText usage removed for consistency of new lines (jQuery #11153)
		if ( typeof elem.textContent === "string" ) {
			return elem.textContent;
		} else {
			// Traverse its children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				ret += getText( elem );
			}
		}
	} else if ( nodeType === 3 || nodeType === 4 ) {
		return elem.nodeValue;
	}
	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[1] = match[1].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );

			if ( match[2] === "~=" ) {
				match[3] = " " + match[3] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {
			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[1] = match[1].toLowerCase();

			if ( match[1].slice( 0, 3 ) === "nth" ) {
				// nth-* requires argument
				if ( !match[3] ) {
					Sizzle.error( match[0] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );

			// other types prohibit arguments
			} else if ( match[3] ) {
				Sizzle.error( match[0] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var excess,
				unquoted = !match[6] && match[2];

			if ( matchExpr["CHILD"].test( match[0] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[3] ) {
				match[2] = match[4] || match[5] || "";

			// Strip excess characters from unquoted arguments
			} else if ( unquoted && rpseudo.test( unquoted ) &&
				// Get excess from tokenize (recursively)
				(excess = tokenize( unquoted, true )) &&
				// advance to the next closing parenthesis
				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {

				// excess is a negative index
				match[0] = match[0].slice( 0, excess );
				match[2] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		"TAG": function( nodeNameSelector ) {
			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
			return nodeNameSelector === "*" ?
				function() { return true; } :
				function( elem ) {
					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
				};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
				classCache( className, function( elem ) {
					return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
				});
		},

		"ATTR": function( name, operator, check ) {
			return function( elem ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check && result.indexOf( check ) === 0 :
					operator === "*=" ? check && result.indexOf( check ) > -1 :
					operator === "$=" ? check && result.slice( -check.length ) === check :
					operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
					false;
			};
		},

		"CHILD": function( type, what, argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 && last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, context, xml ) {
					var cache, uniqueCache, outerCache, node, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType,
						diff = false;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( (node = node[ dir ]) ) {
									if ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) {

										return false;
									}
								}
								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" && !start && "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward && useCache ) {

							// Seek `elem` from a previously-cached index

							// ...in a gzip-friendly way
							node = parent;
							outerCache = node[ expando ] || (node[ expando ] = {});

							// Support: IE <9 only
							// Defend against cloned attroperties (jQuery gh-1709)
							uniqueCache = outerCache[ node.uniqueID ] ||
								(outerCache[ node.uniqueID ] = {});

							cache = uniqueCache[ type ] || [];
							nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
							diff = nodeIndex && cache[ 2 ];
							node = nodeIndex && parent.childNodes[ nodeIndex ];

							while ( (node = ++nodeIndex && node && node[ dir ] ||

								// Fallback to seeking `elem` from the start
								(diff = nodeIndex = 0) || start.pop()) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 && ++diff && node === elem ) {
									uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						} else {
							// Use previously-cached element index if available
							if ( useCache ) {
								// ...in a gzip-friendly way
								node = elem;
								outerCache = node[ expando ] || (node[ expando ] = {});

								// Support: IE <9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[ node.uniqueID ] ||
									(outerCache[ node.uniqueID ] = {});

								cache = uniqueCache[ type ] || [];
								nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
								diff = nodeIndex;
							}

							// xml :nth-child(...)
							// or :nth-last-child(...) or :nth(-last)?-of-type(...)
							if ( diff === false ) {
								// Use the same loop as above to seek `elem` from the start
								while ( (node = ++nodeIndex && node && node[ dir ] ||
									(diff = nodeIndex = 0) || start.pop()) ) {

									if ( ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) &&
										++diff ) {

										// Cache the index of each encountered element
										if ( useCache ) {
											outerCache = node[ expando ] || (node[ expando ] = {});

											// Support: IE <9 only
											// Defend against cloned attroperties (jQuery gh-1709)
											uniqueCache = outerCache[ node.uniqueID ] ||
												(outerCache[ node.uniqueID ] = {});

											uniqueCache[ type ] = [ dirruns, diff ];
										}

										if ( node === elem ) {
											break;
										}
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 && diff / first >= 0 );
					}
				};
		},

		"PSEUDO": function( pseudo, argument ) {
			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction(function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf( seed, matched[i] );
							seed[ idx ] = !( matches[ idx ] = matched[i] );
						}
					}) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {
		// Potentially complex pseudos
		"not": markFunction(function( selector ) {
			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction(function( seed, matches, context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( (elem = unmatched[i]) ) {
							seed[i] = !(matches[i] = elem);
						}
					}
				}) :
				function( elem, context, xml ) {
					input[0] = elem;
					matcher( input, null, xml, results );
					// Don't keep the element (issue #299)
					input[0] = null;
					return !results.pop();
				};
		}),

		"has": markFunction(function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		}),

		"contains": markFunction(function( text ) {
			text = text.replace( runescape, funescape );
			return function( elem ) {
				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
			};
		}),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// http://www.w3.org/TR/selectors/#lang-pseudo
		"lang": markFunction( function( lang ) {
			// lang value must be a valid identifier
			if ( !ridentifier.test(lang || "") ) {
				Sizzle.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( (elemLang = documentIsHTML ?
						elem.lang :
						elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
				return false;
			};
		}),

		// Miscellaneous
		"target": function( elem ) {
			var hash = window.location && window.location.hash;
			return hash && hash.slice( 1 ) === elem.id;
		},

		"root": function( elem ) {
			return elem === docElem;
		},

		"focus": function( elem ) {
			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
		},

		// Boolean properties
		"enabled": function( elem ) {
			return elem.disabled === false;
		},

		"disabled": function( elem ) {
			return elem.disabled === true;
		},

		"checked": function( elem ) {
			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
		},

		"selected": function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		"empty": function( elem ) {
			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
			//   but not by others (comment: 8; processing instruction: 7; etc.)
			// nodeType < 6 works because attributes (2) do not appear as children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeType < 6 ) {
					return false;
				}
			}
			return true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos["empty"]( elem );
		},

		// Element/input types
		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && elem.type === "button" || name === "button";
		},

		"text": function( elem ) {
			var attr;
			return elem.nodeName.toLowerCase() === "input" &&
				elem.type === "text" &&

				// Support: IE<8
				// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
		},

		// Position-in-collection
		"first": createPositionalPseudo(function() {
			return [ 0 ];
		}),

		"last": createPositionalPseudo(function( matchIndexes, length ) {
			return [ length - 1 ];
		}),

		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		}),

		"even": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 0;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"odd": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 1;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		})
	}
};

Expr.pseudos["nth"] = Expr.pseudos["eq"];

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();

tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || (match = rcomma.exec( soFar )) ) {
			if ( match ) {
				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[0].length ) || soFar;
			}
			groups.push( (tokens = []) );
		}

		matched = false;

		// Combinators
		if ( (match = rcombinators.exec( soFar )) ) {
			matched = match.shift();
			tokens.push({
				value: matched,
				// Cast descendant combinators to space
				type: match[0].replace( rtrim, " " )
			});
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
				(match = preFilters[ type ]( match ))) ) {
				matched = match.shift();
				tokens.push({
					value: matched,
					type: type,
					matches: match
				});
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :
			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
};

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i < len; i++ ) {
		selector += tokens[i].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		checkNonElements = base && dir === "parentNode",
		doneName = done++;

	return combinator.first ?
		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( (elem = elem[ dir ]) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var oldCache, uniqueCache, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
			if ( xml ) {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || (elem[ expando ] = {});

						// Support: IE <9 only
						// Defend against cloned attroperties (jQuery gh-1709)
						uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});

						if ( (oldCache = uniqueCache[ dir ]) &&
							oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {

							// Assign to newCache so results back-propagate to previous elements
							return (newCache[ 2 ] = oldCache[ 2 ]);
						} else {
							// Reuse newcache so results back-propagate to previous elements
							uniqueCache[ dir ] = newCache;

							// A match means we're done; a fail means we have to keep checking
							if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
								return true;
							}
						}
					}
				}
			}
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[i]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[0];
}

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		Sizzle( selector, contexts[i], results );
	}
	return results;
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( (elem = unmatched[i]) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction(function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?
				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( (elem = temp[i]) ) {
					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {
					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( (elem = matcherOut[i]) ) {
							// Restore matcherIn since elem is not yet a final match
							temp.push( (matcherIn[i] = elem) );
						}
					}
					postFinder( null, (matcherOut = []), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( (elem = matcherOut[i]) &&
						(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {

						seed[temp] = !(results[temp] = elem);
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	});
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[0].type ],
		implicitRelative = leadingRelative || Expr.relative[" "],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				(checkContext = context).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );
			// Avoid hanging onto element (issue #299)
			checkContext = null;
			return ret;
		} ];

	for ( ; i < len; i++ ) {
		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
		} else {
			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {
				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[j].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && toSelector(
						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
						tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
					).replace( rtrim, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
					j < len && toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, outermost ) {
			var elem, j, matcher,
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				setMatched = [],
				contextBackup = outermostContext,
				// We must always have either seed elements or outermost context
				elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
				len = elems.length;

			if ( outermost ) {
				outermostContext = context === document || context || outermost;
			}

			// Add elements passing elementMatchers directly to results
			// Support: IE<9, Safari
			// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
			for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;
					if ( !context && elem.ownerDocument !== document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context || document, xml) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {
					// They will have gone through all possible matchers
					if ( (elem = !matcher && elem) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( (matcher = setMatchers[j++]) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {
					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !(unmatched[i] || setMatched[i]) ) {
								setMatched[i] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {
		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[i] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
};

/**
 * A low-level selection function that works with Sizzle's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with Sizzle.compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
select = Sizzle.select = function( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" && selector,
		match = !seed && tokenize( (selector = compiled.selector || selector) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[0] = match[0].slice( 0 );
		if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
				support.getById && context.nodeType === 9 && documentIsHTML &&
				Expr.relative[ tokens[1].type ] ) {

			context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[i];

			// Abort if we hit a combinator
			if ( Expr.relative[ (type = token.type) ] ) {
				break;
			}
			if ( (find = Expr.find[ type ]) ) {
				// Search, expanding context for leading sibling combinators
				if ( (seed = find(
					token.matches[0].replace( runescape, funescape ),
					rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
				)) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length && toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
	);
	return results;
};

// One-time assignments

// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;

// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;

// Initialize against the default document
setDocument();

// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
	// Should return 1, but returns 4 (following)
	return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});

// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
	div.innerHTML = "<a href='#'></a>";
	return div.firstChild.getAttribute("href") === "#" ;
}) ) {
	addHandle( "type|href|height|width", function( elem, name, isXML ) {
		if ( !isXML ) {
			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
		}
	});
}

// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
	div.innerHTML = "<input/>";
	div.firstChild.setAttribute( "value", "" );
	return div.firstChild.getAttribute( "value" ) === "";
}) ) {
	addHandle( "value", function( elem, name, isXML ) {
		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
			return elem.defaultValue;
		}
	});
}

// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
	return div.getAttribute("disabled") == null;
}) ) {
	addHandle( booleans, function( elem, name, isXML ) {
		var val;
		if ( !isXML ) {
			return elem[ name ] === true ? name.toLowerCase() :
					(val = elem.getAttributeNode( name )) && val.specified ?
					val.value :
				null;
		}
	});
}

return Sizzle;

})( window );



jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;



var dir = function( elem, dir, until ) {
	var matched = [],
		truncate = until !== undefined;

	while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
		if ( elem.nodeType === 1 ) {
			if ( truncate && jQuery( elem ).is( until ) ) {
				break;
			}
			matched.push( elem );
		}
	}
	return matched;
};


var siblings = function( n, elem ) {
	var matched = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType === 1 && n !== elem ) {
			matched.push( n );
		}
	}

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;

var rsingleTag = ( /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/ );



var risSimple = /^.[^:#\[\.,]*$/;

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			/* jshint -W018 */
			return !!qualifier.call( elem, i, elem ) !== not;
		} );

	}

	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		} );

	}

	if ( typeof qualifier === "string" ) {
		if ( risSimple.test( qualifier ) ) {
			return jQuery.filter( qualifier, elements, not );
		}

		qualifier = jQuery.filter( qualifier, elements );
	}

	return jQuery.grep( elements, function( elem ) {
		return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
	} );
}

jQuery.filter = function( expr, elems, not ) {
	var elem = elems[ 0 ];

	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	return elems.length === 1 && elem.nodeType === 1 ?
		jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
		jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
			return elem.nodeType === 1;
		} ) );
};

jQuery.fn.extend( {
	find: function( selector ) {
		var i,
			len = this.length,
			ret = [],
			self = this;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter( function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			} ) );
		}

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		// Needed because $( selector, context ) becomes $( context ).find( selector )
		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
		ret.selector = this.selector ? this.selector + " " + selector : selector;
		return ret;
	},
	filter: function( selector ) {
		return this.pushStack( winnow( this, selector || [], false ) );
	},
	not: function( selector ) {
		return this.pushStack( winnow( this, selector || [], true ) );
	},
	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	}
} );


// Initialize a jQuery object


// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	// Strict HTML recognition (#11290: must start with <)
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector[ 0 ] === "<" &&
				selector[ selector.length - 1 ] === ">" &&
				selector.length >= 3 ) {

				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( jQuery.isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					// Support: Blackberry 4.6
					// gEBID returns nodes no longer in the document (#6963)
					if ( elem && elem.parentNode ) {

						// Inject the element directly into the jQuery object
						this.length = 1;
						this[ 0 ] = elem;
					}

					this.context = document;
					this.selector = selector;
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this.context = this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return root.ready !== undefined ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );
		}

		if ( selector.selector !== undefined ) {
			this.selector = selector.selector;
			this.context = selector.context;
		}

		return jQuery.makeArray( selector, this );
	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );


var rparentsprev = /^(?:parents|prev(?:Until|All))/,

	// Methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend( {
	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter( function() {
			var i = 0;
			for ( ; i < l; i++ ) {
				if ( jQuery.contains( this, targets[ i ] ) ) {
					return true;
				}
			}
		} );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
				jQuery( selectors, context || this.context ) :
				0;

		for ( ; i < l; i++ ) {
			for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {

				// Always skip document fragments
				if ( cur.nodeType < 11 && ( pos ?
					pos.index( cur ) > -1 :

					// Don't pass non-elements to Sizzle
					cur.nodeType === 1 &&
						jQuery.find.matchesSelector( cur, selectors ) ) ) {

					matched.push( cur );
					break;
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
	},

	// Determine the position of an element within the set
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// Index in selector
		if ( typeof elem === "string" ) {
			return indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		return this.pushStack(
			jQuery.uniqueSort(
				jQuery.merge( this.get(), jQuery( selector, context ) )
			)
		);
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	}
} );

function sibling( cur, dir ) {
	while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
	return cur;
}

jQuery.each( {
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return siblings( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return siblings( elem.firstChild );
	},
	contents: function( elem ) {
		return elem.contentDocument || jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length > 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.uniqueSort( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
} );
var rnotwhite = ( /\S+/g );



// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
	var object = {};
	jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	} );
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		createOptions( options ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,

		// Last fire value for non-forgettable lists
		memory,

		// Flag to know if list was already fired
		fired,

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

		// Queue of execution data for repeatable lists
		queue = [],

		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,

		// Fire callbacks
		fire = function() {

			// Enforce single-firing
			locked = options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			fired = firing = true;
			for ( ; queue.length; firingIndex = -1 ) {
				memory = queue.shift();
				while ( ++firingIndex < list.length ) {

					// Run callback and check for early termination
					if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
						options.stopOnFalse ) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if ( !options.memory ) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if ( locked ) {

				// Keep an empty list if we have data for future add calls
				if ( memory ) {
					list = [];

				// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},

		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {

					// If we have memory from a past run, we should fire after adding
					if ( memory && !firing ) {
						firingIndex = list.length - 1;
						queue.push( memory );
					}

					( function add( args ) {
						jQuery.each( args, function( _, arg ) {
							if ( jQuery.isFunction( arg ) ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {

								// Inspect recursively
								add( arg );
							}
						} );
					} )( arguments );

					if ( memory && !firing ) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function() {
				jQuery.each( arguments, function( _, arg ) {
					var index;
					while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
						list.splice( index, 1 );

						// Handle firing indexes
						if ( index <= firingIndex ) {
							firingIndex--;
						}
					}
				} );
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ?
					jQuery.inArray( fn, list ) > -1 :
					list.length > 0;
			},

			// Remove all callbacks from the list
			empty: function() {
				if ( list ) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function() {
				locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function() {
				locked = queue = [];
				if ( !memory ) {
					list = memory = "";
				}
				return this;
			},
			locked: function() {
				return !!locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( !locked ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					queue.push( args );
					if ( !firing ) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};


jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

				// action, add listener, listener list, final state
				[ "resolve", "done", jQuery.Callbacks( "once memory" ), "resolved" ],
				[ "reject", "fail", jQuery.Callbacks( "once memory" ), "rejected" ],
				[ "notify", "progress", jQuery.Callbacks( "memory" ) ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				then: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;
					return jQuery.Deferred( function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {
							var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];

							// deferred[ done | fail | progress ] for forwarding actions to newDefer
							deferred[ tuple[ 1 ] ]( function() {
								var returned = fn && fn.apply( this, arguments );
								if ( returned && jQuery.isFunction( returned.promise ) ) {
									returned.promise()
										.progress( newDefer.notify )
										.done( newDefer.resolve )
										.fail( newDefer.reject );
								} else {
									newDefer[ tuple[ 0 ] + "With" ](
										this === promise ? newDefer.promise() : this,
										fn ? [ returned ] : arguments
									);
								}
							} );
						} );
						fns = null;
					} ).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Keep pipe for back-compat
		promise.pipe = promise.then;

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 3 ];

			// promise[ done | fail | progress ] = list.add
			promise[ tuple[ 1 ] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add( function() {

					// state = [ resolved | rejected ]
					state = stateString;

				// [ reject_list | resolve_list ].disable; progress_list.lock
				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
			}

			// deferred[ resolve | reject | notify ]
			deferred[ tuple[ 0 ] ] = function() {
				deferred[ tuple[ 0 ] + "With" ]( this === deferred ? promise : this, arguments );
				return this;
			};
			deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
		} );

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( subordinate /* , ..., subordinateN */ ) {
		var i = 0,
			resolveValues = slice.call( arguments ),
			length = resolveValues.length,

			// the count of uncompleted subordinates
			remaining = length !== 1 ||
				( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,

			// the master Deferred.
			// If resolveValues consist of only a single Deferred, just use that.
			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),

			// Update function for both resolve and progress values
			updateFunc = function( i, contexts, values ) {
				return function( value ) {
					contexts[ i ] = this;
					values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
					if ( values === progressValues ) {
						deferred.notifyWith( contexts, values );
					} else if ( !( --remaining ) ) {
						deferred.resolveWith( contexts, values );
					}
				};
			},

			progressValues, progressContexts, resolveContexts;

		// Add listeners to Deferred subordinates; treat others as resolved
		if ( length > 1 ) {
			progressValues = new Array( length );
			progressContexts = new Array( length );
			resolveContexts = new Array( length );
			for ( ; i < length; i++ ) {
				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
					resolveValues[ i ].promise()
						.progress( updateFunc( i, progressContexts, progressValues ) )
						.done( updateFunc( i, resolveContexts, resolveValues ) )
						.fail( deferred.reject );
				} else {
					--remaining;
				}
			}
		}

		// If we're not waiting on anything, resolve the master
		if ( !remaining ) {
			deferred.resolveWith( resolveContexts, resolveValues );
		}

		return deferred.promise();
	}
} );


// The deferred used on DOM ready
var readyList;

jQuery.fn.ready = function( fn ) {

	// Add the callback
	jQuery.ready.promise().done( fn );

	return this;
};

jQuery.extend( {

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Hold (or release) the ready event
	holdReady: function( hold ) {
		if ( hold ) {
			jQuery.readyWait++;
		} else {
			jQuery.ready( true );
		}
	},

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true && --jQuery.readyWait > 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );

		// Trigger any bound ready events
		if ( jQuery.fn.triggerHandler ) {
			jQuery( document ).triggerHandler( "ready" );
			jQuery( document ).off( "ready" );
		}
	}
} );

/**
 * The ready event handler and self cleanup method
 */
function completed() {
	document.removeEventListener( "DOMContentLoaded", completed );
	window.removeEventListener( "load", completed );
	jQuery.ready();
}

jQuery.ready.promise = function( obj ) {
	if ( !readyList ) {

		readyList = jQuery.Deferred();

		// Catch cases where $(document).ready() is called
		// after the browser event has already occurred.
		// Support: IE9-10 only
		// Older IE sometimes signals "interactive" too soon
		if ( document.readyState === "complete" ||
			( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {

			// Handle it asynchronously to allow scripts the opportunity to delay ready
			window.setTimeout( jQuery.ready );

		} else {

			// Use the handy event callback
			document.addEventListener( "DOMContentLoaded", completed );

			// A fallback to window.onload, that will always work
			window.addEventListener( "load", completed );
		}
	}
	return readyList.promise( obj );
};

// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();




// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,
		len = elems.length,
		bulk = key == null;

	// Sets many values
	if ( jQuery.type( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			access( elems, fn, i, key[ i ], true, emptyGet, raw );
		}

	// Sets one value
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !jQuery.isFunction( value ) ) {
			raw = true;
		}

		if ( bulk ) {

			// Bulk operations run against the entire set
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			} else {
				bulk = fn;
				fn = function( elem, key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {
			for ( ; i < len; i++ ) {
				fn(
					elems[ i ], key, raw ?
					value :
					value.call( elems[ i ], i, fn( elems[ i ], key ) )
				);
			}
		}
	}

	return chainable ?
		elems :

		// Gets
		bulk ?
			fn.call( elems ) :
			len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {

	// Accepts only:
	//  - Node
	//    - Node.ELEMENT_NODE
	//    - Node.DOCUMENT_NODE
	//  - Object
	//    - Any
	/* jshint -W018 */
	return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};




function Data() {
	this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

Data.prototype = {

	register: function( owner, initial ) {
		var value = initial || {};

		// If it is a node unlikely to be stringify-ed or looped over
		// use plain assignment
		if ( owner.nodeType ) {
			owner[ this.expando ] = value;

		// Otherwise secure it in a non-enumerable, non-writable property
		// configurability must be true to allow the property to be
		// deleted with the delete operator
		} else {
			Object.defineProperty( owner, this.expando, {
				value: value,
				writable: true,
				configurable: true
			} );
		}
		return owner[ this.expando ];
	},
	cache: function( owner ) {

		// We can accept data for non-element nodes in modern browsers,
		// but we should not, see #8335.
		// Always return an empty object.
		if ( !acceptData( owner ) ) {
			return {};
		}

		// Check if the owner object already has a cache
		var value = owner[ this.expando ];

		// If not, create one
		if ( !value ) {
			value = {};

			// We can accept data for non-element nodes in modern browsers,
			// but we should not, see #8335.
			// Always return an empty object.
			if ( acceptData( owner ) ) {

				// If it is a node unlikely to be stringify-ed or looped over
				// use plain assignment
				if ( owner.nodeType ) {
					owner[ this.expando ] = value;

				// Otherwise secure it in a non-enumerable property
				// configurable must be true to allow the property to be
				// deleted when data is removed
				} else {
					Object.defineProperty( owner, this.expando, {
						value: value,
						configurable: true
					} );
				}
			}
		}

		return value;
	},
	set: function( owner, data, value ) {
		var prop,
			cache = this.cache( owner );

		// Handle: [ owner, key, value ] args
		if ( typeof data === "string" ) {
			cache[ data ] = value;

		// Handle: [ owner, { properties } ] args
		} else {

			// Copy the properties one-by-one to the cache object
			for ( prop in data ) {
				cache[ prop ] = data[ prop ];
			}
		}
		return cache;
	},
	get: function( owner, key ) {
		return key === undefined ?
			this.cache( owner ) :
			owner[ this.expando ] && owner[ this.expando ][ key ];
	},
	access: function( owner, key, value ) {
		var stored;

		// In cases where either:
		//
		//   1. No key was specified
		//   2. A string key was specified, but no value provided
		//
		// Take the "read" path and allow the get method to determine
		// which value to return, respectively either:
		//
		//   1. The entire cache object
		//   2. The data stored at the key
		//
		if ( key === undefined ||
				( ( key && typeof key === "string" ) && value === undefined ) ) {

			stored = this.get( owner, key );

			return stored !== undefined ?
				stored : this.get( owner, jQuery.camelCase( key ) );
		}

		// When the key is not a string, or both a key and value
		// are specified, set or extend (existing objects) with either:
		//
		//   1. An object of properties
		//   2. A key and value
		//
		this.set( owner, key, value );

		// Since the "set" path can have two possible entry points
		// return the expected data based on which path was taken[*]
		return value !== undefined ? value : key;
	},
	remove: function( owner, key ) {
		var i, name, camel,
			cache = owner[ this.expando ];

		if ( cache === undefined ) {
			return;
		}

		if ( key === undefined ) {
			this.register( owner );

		} else {

			// Support array or space separated string of keys
			if ( jQuery.isArray( key ) ) {

				// If "name" is an array of keys...
				// When data is initially created, via ("key", "val") signature,
				// keys will be converted to camelCase.
				// Since there is no way to tell _how_ a key was added, remove
				// both plain key and camelCase key. #12786
				// This will only penalize the array argument path.
				name = key.concat( key.map( jQuery.camelCase ) );
			} else {
				camel = jQuery.camelCase( key );

				// Try the string as a key before any manipulation
				if ( key in cache ) {
					name = [ key, camel ];
				} else {

					// If a key with the spaces exists, use it.
					// Otherwise, create an array by matching non-whitespace
					name = camel;
					name = name in cache ?
						[ name ] : ( name.match( rnotwhite ) || [] );
				}
			}

			i = name.length;

			while ( i-- ) {
				delete cache[ name[ i ] ];
			}
		}

		// Remove the expando if there's no more data
		if ( key === undefined || jQuery.isEmptyObject( cache ) ) {

			// Support: Chrome <= 35-45+
			// Webkit & Blink performance suffers when deleting properties
			// from DOM nodes, so set to undefined instead
			// https://code.google.com/p/chromium/issues/detail?id=378607
			if ( owner.nodeType ) {
				owner[ this.expando ] = undefined;
			} else {
				delete owner[ this.expando ];
			}
		}
	},
	hasData: function( owner ) {
		var cache = owner[ this.expando ];
		return cache !== undefined && !jQuery.isEmptyObject( cache );
	}
};
var dataPriv = new Data();

var dataUser = new Data();



//	Implementation Summary
//
//	1. Enforce API surface and semantic compatibility with 1.9.x branch
//	2. Improve the module's maintainability by reducing the storage
//		paths to a single mechanism.
//	3. Use the same single mechanism to support "private" and "user" data.
//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
//	5. Avoid exposing implementation details on user objects (eg. expando properties)
//	6. Provide a clear path for implementation upgrade to WeakMap in 2014

var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /[A-Z]/g;

function dataAttr( elem, key, data ) {
	var name;

	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {
		name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = data === "true" ? true :
					data === "false" ? false :
					data === "null" ? null :

					// Only convert to a number if it doesn't change the string
					+data + "" === data ? +data :
					rbrace.test( data ) ? jQuery.parseJSON( data ) :
					data;
			} catch ( e ) {}

			// Make sure we set the data so it isn't changed later
			dataUser.set( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}

jQuery.extend( {
	hasData: function( elem ) {
		return dataUser.hasData( elem ) || dataPriv.hasData( elem );
	},

	data: function( elem, name, data ) {
		return dataUser.access( elem, name, data );
	},

	removeData: function( elem, name ) {
		dataUser.remove( elem, name );
	},

	// TODO: Now that all calls to _data and _removeData have been replaced
	// with direct calls to dataPriv methods, these can be deprecated.
	_data: function( elem, name, data ) {
		return dataPriv.access( elem, name, data );
	},

	_removeData: function( elem, name ) {
		dataPriv.remove( elem, name );
	}
} );

jQuery.fn.extend( {
	data: function( key, value ) {
		var i, name, data,
			elem = this[ 0 ],
			attrs = elem && elem.attributes;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = dataUser.get( elem );

				if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
					i = attrs.length;
					while ( i-- ) {

						// Support: IE11+
						// The attrs elements can be null (#14894)
						if ( attrs[ i ] ) {
							name = attrs[ i ].name;
							if ( name.indexOf( "data-" ) === 0 ) {
								name = jQuery.camelCase( name.slice( 5 ) );
								dataAttr( elem, name, data[ name ] );
							}
						}
					}
					dataPriv.set( elem, "hasDataAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each( function() {
				dataUser.set( this, key );
			} );
		}

		return access( this, function( value ) {
			var data, camelKey;

			// The calling jQuery object (element matches) is not empty
			// (and therefore has an element appears at this[ 0 ]) and the
			// `value` parameter was not undefined. An empty jQuery object
			// will result in `undefined` for elem = this[ 0 ] which will
			// throw an exception if an attempt to read a data cache is made.
			if ( elem && value === undefined ) {

				// Attempt to get data from the cache
				// with the key as-is
				data = dataUser.get( elem, key ) ||

					// Try to find dashed key if it exists (gh-2779)
					// This is for 2.2.x only
					dataUser.get( elem, key.replace( rmultiDash, "-$&" ).toLowerCase() );

				if ( data !== undefined ) {
					return data;
				}

				camelKey = jQuery.camelCase( key );

				// Attempt to get data from the cache
				// with the key camelized
				data = dataUser.get( elem, camelKey );
				if ( data !== undefined ) {
					return data;
				}

				// Attempt to "discover" the data in
				// HTML5 custom data-* attrs
				data = dataAttr( elem, camelKey, undefined );
				if ( data !== undefined ) {
					return data;
				}

				// We tried really hard, but the data doesn't exist.
				return;
			}

			// Set the data...
			camelKey = jQuery.camelCase( key );
			this.each( function() {

				// First, attempt to store a copy or reference of any
				// data that might've been store with a camelCased key.
				var data = dataUser.get( this, camelKey );

				// For HTML5 data-* attribute interop, we have to
				// store property names with dashes in a camelCase form.
				// This might not apply to all properties...*
				dataUser.set( this, camelKey, value );

				// *... In the case of properties that might _actually_
				// have dashes, we need to also store a copy of that
				// unchanged property.
				if ( key.indexOf( "-" ) > -1 && data !== undefined ) {
					dataUser.set( this, key, value );
				}
			} );
		}, null, value, arguments.length > 1, null, true );
	},

	removeData: function( key ) {
		return this.each( function() {
			dataUser.remove( this, key );
		} );
	}
} );


jQuery.extend( {
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = dataPriv.get( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || jQuery.isArray( data ) ) {
					queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// Clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength && hooks ) {
			hooks.empty.fire();
		}
	},

	// Not public - generate a queueHooks object, or return the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
			empty: jQuery.Callbacks( "once memory" ).add( function() {
				dataPriv.remove( elem, [ type + "queue", key ] );
			} )
		} );
	}
} );

jQuery.fn.extend( {
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length < setter ) {
			return jQuery.queue( this[ 0 ], type );
		}

		return data === undefined ?
			this :
			this.each( function() {
				var queue = jQuery.queue( this, type, data );

				// Ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			} );
	},
	dequeue: function( type ) {
		return this.each( function() {
			jQuery.dequeue( this, type );
		} );
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},

	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while ( i-- ) {
			tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;

var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );


var cssExpand = [ "Top", "Right", "Bottom", "Left" ];

var isHidden = function( elem, el ) {

		// isHidden might be called from jQuery#filter function;
		// in that case, element will be second argument
		elem = el || elem;
		return jQuery.css( elem, "display" ) === "none" ||
			!jQuery.contains( elem.ownerDocument, elem );
	};



function adjustCSS( elem, prop, valueParts, tween ) {
	var adjusted,
		scale = 1,
		maxIterations = 20,
		currentValue = tween ?
			function() { return tween.cur(); } :
			function() { return jQuery.css( elem, prop, "" ); },
		initial = currentValue(),
		unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

		// Starting value computation is required for potential unit mismatches
		initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
			rcssNum.exec( jQuery.css( elem, prop ) );

	if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {

		// Trust units reported by jQuery.css
		unit = unit || initialInUnit[ 3 ];

		// Make sure we update the tween properties later on
		valueParts = valueParts || [];

		// Iteratively approximate from a nonzero starting point
		initialInUnit = +initial || 1;

		do {

			// If previous iteration zeroed out, double until we get *something*.
			// Use string for doubling so we don't accidentally see scale as unchanged below
			scale = scale || ".5";

			// Adjust and apply
			initialInUnit = initialInUnit / scale;
			jQuery.style( elem, prop, initialInUnit + unit );

		// Update scale, tolerating zero or NaN from tween.cur()
		// Break the loop if scale is unchanged or perfect, or if we've just had enough.
		} while (
			scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
		);
	}

	if ( valueParts ) {
		initialInUnit = +initialInUnit || +initial || 0;

		// Apply relative offset (+=/-=) if specified
		adjusted = valueParts[ 1 ] ?
			initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
			+valueParts[ 2 ];
		if ( tween ) {
			tween.unit = unit;
			tween.start = initialInUnit;
			tween.end = adjusted;
		}
	}
	return adjusted;
}
var rcheckableType = ( /^(?:checkbox|radio)$/i );

var rtagName = ( /<([\w:-]+)/ );

var rscriptType = ( /^$|\/(?:java|ecma)script/i );



// We have to close these tags to support XHTML (#13200)
var wrapMap = {

	// Support: IE9
	option: [ 1, "<select multiple='multiple'>", "</select>" ],

	// XHTML parsers do not magically insert elements in the
	// same way that tag soup parsers do. So we cannot shorten
	// this by omitting <tbody> or other required elements.
	thead: [ 1, "<table>", "</table>" ],
	col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
	tr: [ 2, "<table><tbody>", "</tbody></table>" ],
	td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

	_default: [ 0, "", "" ]
};

// Support: IE9
wrapMap.optgroup = wrapMap.option;

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;


function getAll( context, tag ) {

	// Support: IE9-11+
	// Use typeof to avoid zero-argument method invocation on host objects (#15151)
	var ret = typeof context.getElementsByTagName !== "undefined" ?
			context.getElementsByTagName( tag || "*" ) :
			typeof context.querySelectorAll !== "undefined" ?
				context.querySelectorAll( tag || "*" ) :
			[];

	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
		jQuery.merge( [ context ], ret ) :
		ret;
}


// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		dataPriv.set(
			elems[ i ],
			"globalEval",
			!refElements || dataPriv.get( refElements[ i ], "globalEval" )
		);
	}
}


var rhtml = /<|&#?\w+;/;

function buildFragment( elems, context, scripts, selection, ignored ) {
	var elem, tmp, tag, wrap, contains, j,
		fragment = context.createDocumentFragment(),
		nodes = [],
		i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		elem = elems[ i ];

		if ( elem || elem === 0 ) {

			// Add nodes directly
			if ( jQuery.type( elem ) === "object" ) {

				// Support: Android<4.1, PhantomJS<2
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

			// Convert non-html into a text node
			} else if ( !rhtml.test( elem ) ) {
				nodes.push( context.createTextNode( elem ) );

			// Convert html into DOM nodes
			} else {
				tmp = tmp || fragment.appendChild( context.createElement( "div" ) );

				// Deserialize a standard representation
				tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
				wrap = wrapMap[ tag ] || wrapMap._default;
				tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];

				// Descend through wrappers to the right content
				j = wrap[ 0 ];
				while ( j-- ) {
					tmp = tmp.lastChild;
				}

				// Support: Android<4.1, PhantomJS<2
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, tmp.childNodes );

				// Remember the top-level container
				tmp = fragment.firstChild;

				// Ensure the created nodes are orphaned (#12392)
				tmp.textContent = "";
			}
		}
	}

	// Remove wrapper from fragment
	fragment.textContent = "";

	i = 0;
	while ( ( elem = nodes[ i++ ] ) ) {

		// Skip elements already in the context collection (trac-4087)
		if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
			if ( ignored ) {
				ignored.push( elem );
			}
			continue;
		}

		contains = jQuery.contains( elem.ownerDocument, elem );

		// Append to fragment
		tmp = getAll( fragment.appendChild( elem ), "script" );

		// Preserve script evaluation history
		if ( contains ) {
			setGlobalEval( tmp );
		}

		// Capture executables
		if ( scripts ) {
			j = 0;
			while ( ( elem = tmp[ j++ ] ) ) {
				if ( rscriptType.test( elem.type || "" ) ) {
					scripts.push( elem );
				}
			}
		}
	}

	return fragment;
}


( function() {
	var fragment = document.createDocumentFragment(),
		div = fragment.appendChild( document.createElement( "div" ) ),
		input = document.createElement( "input" );

	// Support: Android 4.0-4.3, Safari<=5.1
	// Check state lost if the name is set (#11217)
	// Support: Windows Web Apps (WWA)
	// `name` and `type` must use .setAttribute for WWA (#14901)
	input.setAttribute( "type", "radio" );
	input.setAttribute( "checked", "checked" );
	input.setAttribute( "name", "t" );

	div.appendChild( input );

	// Support: Safari<=5.1, Android<4.2
	// Older WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE<=11+
	// Make sure textarea (and checkbox) defaultValue is properly cloned
	div.innerHTML = "<textarea>x</textarea>";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();


var
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
	rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

// Support: IE9
// See #13393 for more info
function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

function on( elem, types, selector, data, fn, one ) {
	var origFn, type;

	// Types can be a map of types/handlers
	if ( typeof types === "object" ) {

		// ( types-Object, selector, data )
		if ( typeof selector !== "string" ) {

			// ( types-Object, data )
			data = data || selector;
			selector = undefined;
		}
		for ( type in types ) {
			on( elem, type, selector, data, types[ type ], one );
		}
		return elem;
	}

	if ( data == null && fn == null ) {

		// ( types, fn )
		fn = selector;
		data = selector = undefined;
	} else if ( fn == null ) {
		if ( typeof selector === "string" ) {

			// ( types, selector, fn )
			fn = data;
			data = undefined;
		} else {

			// ( types, data, fn )
			fn = data;
			data = selector;
			selector = undefined;
		}
	}
	if ( fn === false ) {
		fn = returnFalse;
	} else if ( !fn ) {
		return elem;
	}

	if ( one === 1 ) {
		origFn = fn;
		fn = function( event ) {

			// Can use an empty set, since event contains the info
			jQuery().off( event );
			return origFn.apply( this, arguments );
		};

		// Use same guid so caller can remove using origFn
		fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
	}
	return elem.each( function() {
		jQuery.event.add( this, types, fn, data, selector );
	} );
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	global: {},

	add: function( elem, types, handler, data, selector ) {

		var handleObjIn, eventHandle, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.get( elem );

		// Don't attach events to noData or text/comment nodes (but allow plain objects)
		if ( !elemData ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		if ( !( events = elemData.events ) ) {
			events = elemData.events = {};
		}
		if ( !( eventHandle = elemData.handle ) ) {
			eventHandle = elemData.handle = function( e ) {

				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
					jQuery.event.dispatch.apply( elem, arguments ) : undefined;
			};
		}

		// Handle multiple events separated by a space
		types = ( types || "" ).match( rnotwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// There *must* be a type, no attaching namespace-only handlers
			if ( !type ) {
				continue;
			}

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend( {
				type: type,
				origType: origType,
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join( "." )
			}, handleObjIn );

			// Init the event handler queue if we're the first
			if ( !( handlers = events[ type ] ) ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener if the special events handler returns false
				if ( !special.setup ||
					special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var j, origCount, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );

		if ( !elemData || !( events = elemData.events ) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = ( types || "" ).match( rnotwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector ? special.delegateType : special.bindType ) || type;
			handlers = events[ type ] || [];
			tmp = tmp[ 2 ] &&
				new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );

			// Remove matching events
			origCount = j = handlers.length;
			while ( j-- ) {
				handleObj = handlers[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					( !handler || handler.guid === handleObj.guid ) &&
					( !tmp || tmp.test( handleObj.namespace ) ) &&
					( !selector || selector === handleObj.selector ||
						selector === "**" && handleObj.selector ) ) {
					handlers.splice( j, 1 );

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount && !handlers.length ) {
				if ( !special.teardown ||
					special.teardown.call( elem, namespaces, elemData.handle ) === false ) {

					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove data and the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			dataPriv.remove( elem, "handle events" );
		}
	},

	dispatch: function( event ) {

		// Make a writable jQuery.Event from the native event object
		event = jQuery.event.fix( event );

		var i, j, ret, matched, handleObj,
			handlerQueue = [],
			args = slice.call( arguments ),
			handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[ 0 ] = event;
		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

			j = 0;
			while ( ( handleObj = matched.handlers[ j++ ] ) &&
				!event.isImmediatePropagationStopped() ) {

				// Triggered event must either 1) have no namespace, or 2) have namespace(s)
				// a subset or equal to those in the bound event (both can have no namespace).
				if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
						handleObj.handler ).apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( ( event.result = ret ) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var i, matches, sel, handleObj,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Support (at least): Chrome, IE9
		// Find delegate handlers
		// Black-hole SVG <use> instance trees (#13180)
		//
		// Support: Firefox<=42+
		// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
		if ( delegateCount && cur.nodeType &&
			( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {

			for ( ; cur !== this; cur = cur.parentNode || this ) {

				// Don't check non-elements (#13208)
				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
					matches = [];
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matches[ sel ] === undefined ) {
							matches[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) > -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matches[ sel ] ) {
							matches.push( handleObj );
						}
					}
					if ( matches.length ) {
						handlerQueue.push( { elem: cur, handlers: matches } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		if ( delegateCount < handlers.length ) {
			handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	// Includes some event props shared by KeyEvent and MouseEvent
	props: ( "altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " +
		"metaKey relatedTarget shiftKey target timeStamp view which" ).split( " " ),

	fixHooks: {},

	keyHooks: {
		props: "char charCode key keyCode".split( " " ),
		filter: function( event, original ) {

			// Add which for key events
			if ( event.which == null ) {
				event.which = original.charCode != null ? original.charCode : original.keyCode;
			}

			return event;
		}
	},

	mouseHooks: {
		props: ( "button buttons clientX clientY offsetX offsetY pageX pageY " +
			"screenX screenY toElement" ).split( " " ),
		filter: function( event, original ) {
			var eventDoc, doc, body,
				button = original.button;

			// Calculate pageX/Y if missing and clientX/Y available
			if ( event.pageX == null && original.clientX != null ) {
				eventDoc = event.target.ownerDocument || document;
				doc = eventDoc.documentElement;
				body = eventDoc.body;

				event.pageX = original.clientX +
					( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
					( doc && doc.clientLeft || body && body.clientLeft || 0 );
				event.pageY = original.clientY +
					( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) -
					( doc && doc.clientTop  || body && body.clientTop  || 0 );
			}

			// Add which for click: 1 === left; 2 === middle; 3 === right
			// Note: button is not normalized, so don't use it
			if ( !event.which && button !== undefined ) {
				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
			}

			return event;
		}
	},

	fix: function( event ) {
		if ( event[ jQuery.expando ] ) {
			return event;
		}

		// Create a writable copy of the event object and normalize some properties
		var i, prop, copy,
			type = event.type,
			originalEvent = event,
			fixHook = this.fixHooks[ type ];

		if ( !fixHook ) {
			this.fixHooks[ type ] = fixHook =
				rmouseEvent.test( type ) ? this.mouseHooks :
				rkeyEvent.test( type ) ? this.keyHooks :
				{};
		}
		copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;

		event = new jQuery.Event( originalEvent );

		i = copy.length;
		while ( i-- ) {
			prop = copy[ i ];
			event[ prop ] = originalEvent[ prop ];
		}

		// Support: Cordova 2.5 (WebKit) (#13255)
		// All events should have a target; Cordova deviceready doesn't
		if ( !event.target ) {
			event.target = document;
		}

		// Support: Safari 6.0+, Chrome<28
		// Target should not be a text node (#504, #13143)
		if ( event.target.nodeType === 3 ) {
			event.target = event.target.parentNode;
		}

		return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		focus: {

			// Fire native event if possible so blur/focus sequence is correct
			trigger: function() {
				if ( this !== safeActiveElement() && this.focus ) {
					this.focus();
					return false;
				}
			},
			delegateType: "focusin"
		},
		blur: {
			trigger: function() {
				if ( this === safeActiveElement() && this.blur ) {
					this.blur();
					return false;
				}
			},
			delegateType: "focusout"
		},
		click: {

			// For checkbox, fire native event so checked state will be right
			trigger: function() {
				if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
					this.click();
					return false;
				}
			},

			// For cross-browser consistency, don't fire native .click() on links
			_default: function( event ) {
				return jQuery.nodeName( event.target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined && event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	}
};

jQuery.removeEvent = function( elem, type, handle ) {

	// This "if" is needed for plain objects
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle );
	}
};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&

				// Support: Android<4.0
				src.returnValue === false ?
			returnTrue :
			returnFalse;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,
	isSimulated: false,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e && !this.isSimulated ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://code.google.com/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

jQuery.fn.extend( {
	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	}
} );


var
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,

	// Support: IE 10-11, Edge 10240+
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;

// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
	return jQuery.nodeName( elem, "table" ) &&
		jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?

		elem.getElementsByTagName( "tbody" )[ 0 ] ||
			elem.appendChild( elem.ownerDocument.createElement( "tbody" ) ) :
		elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	var match = rscriptTypeMasked.exec( elem.type );

	if ( match ) {
		elem.type = match[ 1 ];
	} else {
		elem.removeAttribute( "type" );
	}

	return elem;
}

function cloneCopyEvent( src, dest ) {
	var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.access( src );
		pdataCur = dataPriv.set( dest, pdataOld );
		events = pdataOld.events;

		if ( events ) {
			delete pdataCur.handle;
			pdataCur.events = {};

			for ( type in events ) {
				for ( i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type, events[ type ][ i ] );
				}
			}
		}
	}

	// 2. Copy user data
	if ( dataUser.hasData( src ) ) {
		udataOld = dataUser.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		dataUser.set( dest, udataCur );
	}
}

// Fix IE bugs, see support tests
function fixInput( src, dest ) {
	var nodeName = dest.nodeName.toLowerCase();

	// Fails to persist the checked state of a cloned checkbox or radio button.
	if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Fails to return the selected option to the default selected state when cloning options
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = concat.apply( [], args );

	var fragment, first, scripts, hasScripts, node, doc,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		isFunction = jQuery.isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( isFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( isFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (#8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android<4.1, PhantomJS<2
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!dataPriv.access( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl ) {
								jQuery._evalUrl( node.src );
							}
						} else {
							jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
						}
					}
				}
			}
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		nodes = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = nodes[ i ] ) != null; i++ ) {
		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html.replace( rxhtmlTag, "<$1></$2>" );
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = jQuery.contains( elem.ownerDocument, elem );

		// Fix IE cloning issues
		if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
				!jQuery.isXMLDoc( elem ) ) {

			// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			for ( i = 0, l = srcElements.length; i < l; i++ ) {
				fixInput( srcElements[ i ], destElements[ i ] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0, l = srcElements.length; i < l; i++ ) {
					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems ) {
		var data, elem, type,
			special = jQuery.event.special,
			i = 0;

		for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
			if ( acceptData( elem ) ) {
				if ( ( data = elem[ dataPriv.expando ] ) ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Support: Chrome <= 35-45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataPriv.expando ] = undefined;
				}
				if ( elem[ dataUser.expando ] ) {

					// Support: Chrome <= 35-45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataUser.expando ] = undefined;
				}
			}
		}
	}
} );

jQuery.fn.extend( {

	// Keep domManip exposed until 3.0 (gh-2225)
	domManip: domManip,

	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().each( function() {
					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
						this.textContent = value;
					}
				} );
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {
			if ( elem.nodeType === 1 ) {

				// Prevent memory leaks
				jQuery.cleanData( getAll( elem, false ) );

				// Remove any remaining nodes
				elem.textContent = "";
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined && elem.nodeType === 1 ) {
				return elem.innerHTML;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i < l; i++ ) {
						elem = this[ i ] || {};

						// Remove element nodes and prevent memory leaks
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1,
			i = 0;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Support: QtWebKit
			// .get() because push.apply(_, arraylike) throws
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );


var iframe,
	elemdisplay = {

		// Support: Firefox
		// We have to pre-define these values for FF (#10227)
		HTML: "block",
		BODY: "block"
	};

/**
 * Retrieve the actual display of a element
 * @param {String} name nodeName of the element
 * @param {Object} doc Document object
 */

// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
	var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),

		display = jQuery.css( elem[ 0 ], "display" );

	// We don't have any data stored on the element,
	// so use "detach" method as fast way to get rid of the element
	elem.detach();

	return display;
}

/**
 * Try to determine the default display value of an element
 * @param {String} nodeName
 */
function defaultDisplay( nodeName ) {
	var doc = document,
		display = elemdisplay[ nodeName ];

	if ( !display ) {
		display = actualDisplay( nodeName, doc );

		// If the simple way fails, read from inside an iframe
		if ( display === "none" || !display ) {

			// Use the already-created iframe if possible
			iframe = ( iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" ) )
				.appendTo( doc.documentElement );

			// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
			doc = iframe[ 0 ].contentDocument;

			// Support: IE
			doc.write();
			doc.close();

			display = actualDisplay( nodeName, doc );
			iframe.detach();
		}

		// Store the correct default display
		elemdisplay[ nodeName ] = display;
	}

	return display;
}
var rmargin = ( /^margin/ );

var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var getStyles = function( elem ) {

		// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};

var swap = function( elem, options, callback, args ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.apply( elem, args || [] );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};


var documentElement = document.documentElement;



( function() {
	var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE9-11+
	// Style of cloned element affects source element cloned (#8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
		"padding:0;margin-top:1px;position:absolute";
	container.appendChild( div );

	// Executing both pixelPosition & boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {
		div.style.cssText =

			// Support: Firefox<29, Android 2.3
			// Vendor-prefix box-sizing
			"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;" +
			"position:relative;display:block;" +
			"margin:auto;border:1px;padding:1px;" +
			"top:1%;width:50%";
		div.innerHTML = "";
		documentElement.appendChild( container );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";
		reliableMarginLeftVal = divStyle.marginLeft === "2px";
		boxSizingReliableVal = divStyle.width === "4px";

		// Support: Android 4.0 - 4.3 only
		// Some styles come back with percentage values, even though they shouldn't
		div.style.marginRight = "50%";
		pixelMarginRightVal = divStyle.marginRight === "4px";

		documentElement.removeChild( container );
	}

	jQuery.extend( support, {
		pixelPosition: function() {

			// This test is executed only once but we still do memoizing
			// since we can use the boxSizingReliable pre-computing.
			// No need to check if the test was already performed, though.
			computeStyleTests();
			return pixelPositionVal;
		},
		boxSizingReliable: function() {
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return boxSizingReliableVal;
		},
		pixelMarginRight: function() {

			// Support: Android 4.0-4.3
			// We're checking for boxSizingReliableVal here instead of pixelMarginRightVal
			// since that compresses better and they're computed together anyway.
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return pixelMarginRightVal;
		},
		reliableMarginLeft: function() {

			// Support: IE <=8 only, Android 4.0 - 4.3 only, Firefox <=3 - 37
			if ( boxSizingReliableVal == null ) {
				computeStyleTests();
			}
			return reliableMarginLeftVal;
		},
		reliableMarginRight: function() {

			// Support: Android 2.3
			// Check if div with explicit width and no margin-right incorrectly
			// gets computed margin-right based on width of container. (#3333)
			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
			// This support function is only executed once so no memoizing is needed.
			var ret,
				marginDiv = div.appendChild( document.createElement( "div" ) );

			// Reset CSS: box-sizing; display; margin; border; padding
			marginDiv.style.cssText = div.style.cssText =

				// Support: Android 2.3
				// Vendor-prefix box-sizing
				"-webkit-box-sizing:content-box;box-sizing:content-box;" +
				"display:block;margin:0;border:0;padding:0";
			marginDiv.style.marginRight = marginDiv.style.width = "0";
			div.style.width = "1px";
			documentElement.appendChild( container );

			ret = !parseFloat( window.getComputedStyle( marginDiv ).marginRight );

			documentElement.removeChild( container );
			div.removeChild( marginDiv );

			return ret;
		}
	} );
} )();


function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,
		style = elem.style;

	computed = computed || getStyles( elem );
	ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;

	// Support: Opera 12.1x only
	// Fall back to style even without computed
	// computed is undefined for elems on document fragments
	if ( ( ret === "" || ret === undefined ) && !jQuery.contains( elem.ownerDocument, elem ) ) {
		ret = jQuery.style( elem, name );
	}

	// Support: IE9
	// getPropertyValue is only needed for .css('filter') (#12537)
	if ( computed ) {

		// A tribute to the "awesome hack by Dean Edwards"
		// Android Browser returns percentage for some values,
		// but width seems to be reliably pixels.
		// This is against the CSSOM draft spec:
		// http://dev.w3.org/csswg/cssom/#resolved-values
		if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {

			// Remember the original values
			width = style.width;
			minWidth = style.minWidth;
			maxWidth = style.maxWidth;

			// Put in the new values to get a computed value out
			style.minWidth = style.maxWidth = style.width = ret;
			ret = computed.width;

			// Revert the changed values
			style.width = width;
			style.minWidth = minWidth;
			style.maxWidth = maxWidth;
		}
	}

	return ret !== undefined ?

		// Support: IE9-11+
		// IE returns zIndex value as an integer.
		ret + "" :
		ret;
}


function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,

	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	},

	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style;

// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {

	// Shortcut for names that are not vendor prefixed
	if ( name in emptyStyle ) {
		return name;
	}

	// Check for vendor prefixed names
	var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

function setPositiveNumber( elem, value, subtract ) {

	// Any relative (+/-) values have already been
	// normalized at this point
	var matches = rcssNum.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
		value;
}

function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
	var i = extra === ( isBorderBox ? "border" : "content" ) ?

		// If we already have the right measurement, avoid augmentation
		4 :

		// Otherwise initialize for horizontal or vertical properties
		name === "width" ? 1 : 0,

		val = 0;

	for ( ; i < 4; i += 2 ) {

		// Both box models exclude margin, so add it if we want it
		if ( extra === "margin" ) {
			val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
		}

		if ( isBorderBox ) {

			// border-box includes padding, so remove it if we want content
			if ( extra === "content" ) {
				val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// At this point, extra isn't border nor margin, so remove border
			if ( extra !== "margin" ) {
				val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		} else {

			// At this point, extra isn't content, so add padding
			val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// At this point, extra isn't content nor padding, so add border
			if ( extra !== "padding" ) {
				val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	return val;
}

function getWidthOrHeight( elem, name, extra ) {

	// Start with offset property, which is equivalent to the border-box value
	var valueIsBorderBox = true,
		val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
		styles = getStyles( elem ),
		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

	// Some non-html elements return undefined for offsetWidth, so check for null/undefined
	// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
	// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
	if ( val <= 0 || val == null ) {

		// Fall back to computed then uncomputed css if necessary
		val = curCSS( elem, name, styles );
		if ( val < 0 || val == null ) {
			val = elem.style[ name ];
		}

		// Computed unit is not pixels. Stop here and return.
		if ( rnumnonpx.test( val ) ) {
			return val;
		}

		// Check for style in case a browser which returns unreliable values
		// for getComputedStyle silently falls back to the reliable elem.style
		valueIsBorderBox = isBorderBox &&
			( support.boxSizingReliable() || val === elem.style[ name ] );

		// Normalize "", auto, and prepare for extra
		val = parseFloat( val ) || 0;
	}

	// Use the active box-sizing model to add/subtract irrelevant styles
	return ( val +
		augmentWidthOrHeight(
			elem,
			name,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles
		)
	) + "px";
}

function showHide( elements, show ) {
	var display, elem, hidden,
		values = [],
		index = 0,
		length = elements.length;

	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		values[ index ] = dataPriv.get( elem, "olddisplay" );
		display = elem.style.display;
		if ( show ) {

			// Reset the inline display of this element to learn if it is
			// being hidden by cascaded rules or not
			if ( !values[ index ] && display === "none" ) {
				elem.style.display = "";
			}

			// Set elements which have been overridden with display: none
			// in a stylesheet to whatever the default browser style is
			// for such an element
			if ( elem.style.display === "" && isHidden( elem ) ) {
				values[ index ] = dataPriv.access(
					elem,
					"olddisplay",
					defaultDisplay( elem.nodeName )
				);
			}
		} else {
			hidden = isHidden( elem );

			if ( display !== "none" || !hidden ) {
				dataPriv.set(
					elem,
					"olddisplay",
					hidden ? display : jQuery.css( elem, "display" )
				);
			}
		}
	}

	// Set the display of most of the elements in a second loop
	// to avoid the constant reflow
	for ( index = 0; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}
		if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
			elem.style.display = show ? values[ index ] || "" : "none";
		}
	}

	return elements;
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		"animationIterationCount": true,
		"columnCount": true,
		"fillOpacity": true,
		"flexGrow": true,
		"flexShrink": true,
		"fontWeight": true,
		"lineHeight": true,
		"opacity": true,
		"order": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		"float": "cssFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = jQuery.camelCase( name ),
			style = elem.style;

		name = jQuery.cssProps[ origName ] ||
			( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );

		// Gets hook for the prefixed version, then unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (#7345)
			if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug #9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set (#7116)
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			if ( type === "number" ) {
				value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// Support: IE9-11+
			// background-* props affect original clone's values
			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				style[ name ] = value;
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks &&
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var val, num, hooks,
			origName = jQuery.camelCase( name );

		// Make sure that we're working with the right name
		name = jQuery.cssProps[ origName ] ||
			( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );

		// Try prefixed name followed by the unprefixed name
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		// Convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Make numeric if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}
		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
					elem.offsetWidth === 0 ?
						swap( elem, cssShow, function() {
							return getWidthOrHeight( elem, name, extra );
						} ) :
						getWidthOrHeight( elem, name, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = extra && getStyles( elem ),
				subtract = extra && augmentWidthOrHeight(
					elem,
					name,
					extra,
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
					styles
				);

			// Convert to pixels if value adjustment is needed
			if ( subtract && ( matches = rcssNum.exec( value ) ) &&
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ name ] = value;
				value = jQuery.css( elem, name );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
				elem.getBoundingClientRect().left -
					swap( elem, { marginLeft: 0 }, function() {
						return elem.getBoundingClientRect().left;
					} )
				) + "px";
		}
	}
);

// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
	function( elem, computed ) {
		if ( computed ) {
			return swap( elem, { "display": "inline-block" },
				curCSS, [ elem, "marginRight" ] );
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( !rmargin.test( prefix ) ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( jQuery.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	},
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		if ( typeof state === "boolean" ) {
			return state ? this.show() : this.hide();
		}

		return this.each( function() {
			if ( isHidden( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		} );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// Passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails.
			// Simple values such as "10px" are parsed to Float;
			// complex values such as "rotate(1rad)" are returned as-is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// Use step hook for back compat.
			// Use cssHook if its there.
			// Use .style if available and use plain properties where available.
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 &&
				( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
					jQuery.cssHooks[ tween.prop ] ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back Compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, timerId,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = jQuery.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		i = 0,
		attrs = { height: type };

	// If we include width, step value is 1 to do all cssExpand values,
	// otherwise step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i < 4 ; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index < length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// We're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	/* jshint validthis: true */
	var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType && isHidden( elem ),
		dataShow = dataPriv.get( elem, "fxshow" );

	// Handle queue: false promises
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// Ensure the complete handler is called before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// Height/width overflow pass
	if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {

		// Make sure that nothing sneaks out
		// Record all 3 overflow attributes because IE9-10 do not
		// change the overflow attribute when overflowX and
		// overflowY are set to the same value
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Set display property to inline-block for height/width
		// animations on inline elements that are having width/height animated
		display = jQuery.css( elem, "display" );

		// Test default display if display is currently "none"
		checkDisplay = display === "none" ?
			dataPriv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;

		if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
			style.display = "inline-block";
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		anim.always( function() {
			style.overflow = opts.overflow[ 0 ];
			style.overflowX = opts.overflow[ 1 ];
			style.overflowY = opts.overflow[ 2 ];
		} );
	}

	// show/hide pass
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.exec( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// If there is dataShow left over from a stopped hide or show
				// and we are going to proceed with show, we should pretend to be hidden
				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
					hidden = true;
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );

		// Any non-fx value stops us from restoring the original display value
		} else {
			display = undefined;
		}
	}

	if ( !jQuery.isEmptyObject( orig ) ) {
		if ( dataShow ) {
			if ( "hidden" in dataShow ) {
				hidden = dataShow.hidden;
			}
		} else {
			dataShow = dataPriv.access( elem, "fxshow", {} );
		}

		// Store state if its toggle - enables .stop().toggle() to "reverse"
		if ( toggle ) {
			dataShow.hidden = !hidden;
		}
		if ( hidden ) {
			jQuery( elem ).show();
		} else {
			anim.done( function() {
				jQuery( elem ).hide();
			} );
		}
		anim.done( function() {
			var prop;

			dataPriv.remove( elem, "fxshow" );
			for ( prop in orig ) {
				jQuery.style( elem, prop, orig[ prop ] );
			}
		} );
		for ( prop in orig ) {
			tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );

			if ( !( prop in dataShow ) ) {
				dataShow[ prop ] = tween.start;
				if ( hidden ) {
					tween.end = tween.start;
					tween.start = prop === "width" || prop === "height" ? 1 : 0;
				}
			}
		}

	// If this is a noop like .hide().hide(), restore an overwritten display value
	} else if ( ( display === "none" ? defaultDisplay( elem.nodeName ) : display ) === "inline" ) {
		style.display = display;
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = jQuery.camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( jQuery.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// Not quite $.extend, this won't overwrite existing keys.
			// Reusing 'index' because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// Don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length ; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			if ( percent < 1 && length ) {
				return remaining;
			} else {
				deferred.resolveWith( elem, [ animation ] );
				return false;
			}
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
						animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// If we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length ; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// Resolve when we played the last frame; otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length ; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( jQuery.isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					jQuery.proxy( result.stop, result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( jQuery.isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	// attach callbacks from options
	return animation.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );
}

jQuery.Animation = jQuery.extend( Animation, {
	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnotwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length ; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			jQuery.isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
	};

	opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ?
		opt.duration : opt.duration in jQuery.fx.speeds ?
			jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;

	// Normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( jQuery.isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// Show any hidden elements after setting opacity to 0
		return this.filter( isHidden ).css( "opacity", 0 ).show()

			// Animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || dataPriv.get( this, "finish" ) ) {
					anim.stop( true );
				}
			};
			doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue && type !== false ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = dataPriv.get( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &&
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// Start the next in the queue if the last step wasn't forced.
			// Timers currently will call their complete callbacks, which
			// will dequeue but only if they were gotoEnd.
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = dataPriv.get( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// Enable finishing flag on private data
			data.finish = true;

			// Empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// Look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// Look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// Turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		i = 0,
		timers = jQuery.timers;

	fxNow = jQuery.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];

		// Checks the timer has not already been removed
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	if ( timer() ) {
		jQuery.fx.start();
	} else {
		jQuery.timers.pop();
	}
};

jQuery.fx.interval = 13;
jQuery.fx.start = function() {
	if ( !timerId ) {
		timerId = window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
	}
};

jQuery.fx.stop = function() {
	window.clearInterval( timerId );

	timerId = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
// http://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var input = document.createElement( "input" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	input.type = "checkbox";

	// Support: iOS<=5.1, Android<=4.2+
	// Default value for a checkbox should be "on"
	support.checkOn = input.value !== "";

	// Support: IE<=11+
	// Must access selectedIndex to make default options select
	support.optSelected = opt.selected;

	// Support: Android<=2.3
	// Options inside disabled selects are incorrectly marked as disabled
	select.disabled = true;
	support.optDisabled = !opt.disabled;

	// Support: IE<=11+
	// An input loses its value after becoming a radio
	input = document.createElement( "input" );
	input.value = "t";
	input.type = "radio";
	support.radioValue = input.value === "t";
} )();


var boolHook,
	attrHandle = jQuery.expr.attrHandle;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// All attributes are lowercase
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			name = name.toLowerCase();
			hooks = jQuery.attrHooks[ name ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" &&
					jQuery.nodeName( elem, "input" ) ) {
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name, propName,
			i = 0,
			attrNames = value && value.match( rnotwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				propName = jQuery.propFix[ name ] || name;

				// Boolean attributes get special treatment (#10870)
				if ( jQuery.expr.match.bool.test( name ) ) {

					// Set corresponding property to false
					elem[ propName ] = false;
				}

				elem.removeAttribute( name );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			elem.setAttribute( name, name );
		}
		return name;
	}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = function( elem, name, isXML ) {
		var ret, handle;
		if ( !isXML ) {

			// Avoid an infinite loop by temporarily removing this function from the getter
			handle = attrHandle[ name ];
			attrHandle[ name ] = ret;
			ret = getter( elem, name, isXML ) != null ?
				name.toLowerCase() :
				null;
			attrHandle[ name ] = handle;
		}
		return ret;
	};
} );




var rfocusable = /^(?:input|select|textarea|button)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		return this.each( function() {
			delete this[ jQuery.propFix[ name ] || name ];
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				// Use proper attribute retrieval(#12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				return tabindex ?
					parseInt( tabindex, 10 ) :
					rfocusable.test( elem.nodeName ) ||
						rclickable.test( elem.nodeName ) && elem.href ?
							0 :
							-1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {
			var parent = elem.parentNode;
			if ( parent && parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		},
		set: function( elem ) {
			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );




var rclass = /[\t\r\n\f]/g;

function getClass( elem ) {
	return elem.getAttribute && elem.getAttribute( "class" ) || "";
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( typeof value === "string" && value ) {
			classes = value.match( rnotwhite ) || [];

			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );
				cur = elem.nodeType === 1 &&
					( " " + curValue + " " ).replace( rclass, " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {
						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
							cur += clazz + " ";
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = jQuery.trim( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		if ( typeof value === "string" && value ) {
			classes = value.match( rnotwhite ) || [];

			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );

				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 &&
					( " " + curValue + " " ).replace( rclass, " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {

						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = jQuery.trim( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value;

		if ( typeof stateVal === "boolean" && type === "string" ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		return this.each( function() {
			var className, i, self, classNames;

			if ( type === "string" ) {

				// Toggle individual class names
				i = 0;
				self = jQuery( this );
				classNames = value.match( rnotwhite ) || [];

				while ( ( className = classNames[ i++ ] ) ) {

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// Store className if set
					dataPriv.set( this, "__className__", className );
				}

				// If the element has a class name or if we're passed `false`,
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				if ( this.setAttribute ) {
					this.setAttribute( "class",
						className || value === false ?
						"" :
						dataPriv.get( this, "__className__" ) || ""
					);
				}
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &&
				( " " + getClass( elem ) + " " ).replace( rclass, " " )
					.indexOf( className ) > -1
			) {
				return true;
			}
		}

		return false;
	}
} );




var rreturn = /\r/g,
	rspaces = /[\x20\t\r\n\f]+/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks &&
					"get" in hooks &&
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				return typeof ret === "string" ?

					// Handle most common string cases
					ret.replace( rreturn, "" ) :

					// Handle cases where value is null/undef or number
					ret == null ? "" : ret;
			}

			return;
		}

		isFunction = jQuery.isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";

			} else if ( typeof val === "number" ) {
				val += "";

			} else if ( jQuery.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {

				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE10-11+
					// option.text throws exceptions (#14686, #14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
			}
		},
		select: {
			get: function( elem ) {
				var value, option,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one" || index < 0,
					values = one ? null : [],
					max = one ? index + 1 : options.length,
					i = index < 0 ?
						max :
						one ? index : 0;

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// IE8-9 doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&

							// Don't return options that are disabled or in a disabled optgroup
							( support.optDisabled ?
								!option.disabled : option.getAttribute( "disabled" ) === null ) &&
							( !option.parentNode.disabled ||
								!jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];
					if ( option.selected =
						jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
					) {
						optionSet = true;
					}
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( jQuery.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




// Return jQuery for attributes-only inclusion


var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;

jQuery.extend( jQuery.event, {

	trigger: function( event, data, elem, onlyHandlers ) {

		var i, cur, tmp, bubbleType, ontype, handle, special,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) > -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {

			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
				dataPriv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( ( !special._default ||
				special._default.apply( eventPath.pop(), data ) === false ) &&
				acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name name as the event.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;
					elem[ type ]();
					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	// Piggyback on a donor event to simulate a different one
	// Used only for `focus(in | out)` events
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true
			}
		);

		jQuery.event.trigger( e, null, elem );
	}

} );

jQuery.fn.extend( {

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


jQuery.each( ( "blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu" ).split( " " ),
	function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};
} );

jQuery.fn.extend( {
	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );




support.focusin = "onfocusin" in window;


// Support: Firefox
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome, Safari
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://code.google.com/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
	jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler on the document while someone wants focusin/focusout
		var handler = function( event ) {
			jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
		};

		jQuery.event.special[ fix ] = {
			setup: function() {
				var doc = this.ownerDocument || this,
					attaches = dataPriv.access( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this,
					attaches = dataPriv.access( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					dataPriv.remove( doc, fix );

				} else {
					dataPriv.access( doc, fix, attaches );
				}
			}
		};
	} );
}
var location = window.location;

var nonce = jQuery.now();

var rquery = ( /\?/ );



// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
	return JSON.parse( data + "" );
};


// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE9
	try {
		xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
	} catch ( e ) {
		xml = undefined;
	}

	if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
		jQuery.error( "Invalid XML: " + data );
	}
	return xml;
};


var
	rhash = /#.*$/,
	rts = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Anchor tag for parsing the document origin
	originAnchor = document.createElement( "a" );
	originAnchor.href = location.href;

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];

		if ( jQuery.isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType[ 0 ] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &&
				!seekingTransport && !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev && isSuccess && s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

		// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s.throws ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: location.href,
		type: "GET",
		isLocal: rlocalProtocol.test( location.protocol ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": jQuery.parseJSON,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var transport,

			// URL without anti-cache param
			cacheURL,

			// Response headers
			responseHeadersString,
			responseHeaders,

			// timeout handle
			timeoutTimer,

			// Url cleanup var
			urlAnchor,

			// To know if global events are to be dispatched
			fireGlobals,

			// Loop variable
			i,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &&
				( callbackContext.nodeType || callbackContext.jquery ) ?
					jQuery( callbackContext ) :
					jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// The jqXHR state
			state = 0,

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( state === 2 ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match == null ? null : match;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return state === 2 ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					var lname = name.toLowerCase();
					if ( !state ) {
						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( !state ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( state < 2 ) {
							for ( code in map ) {

								// Lazy-add the new callback in a way that preserves old ones
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						} else {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR ).complete = completeDeferred.add;
		jqXHR.success = jqXHR.done;
		jqXHR.error = jqXHR.fail;

		// Remove hash character (#7531: and string promotion)
		// Add protocol if not provided (prefilters might expect it)
		// Handle falsy url in the settings object (#10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || location.href ) + "" ).replace( rhash, "" )
			.replace( rprotocol, location.protocol + "//" );

		// Alias method option to type as per ticket #12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];

		// A cross-domain request is in order when the origin doesn't match the current origin.
		if ( s.crossDomain == null ) {
			urlAnchor = document.createElement( "a" );

			// Support: IE8-11+
			// IE throws exception if url is malformed, e.g. http://example.com:80x/
			try {
				urlAnchor.href = s.url;

				// Support: IE8-11+
				// Anchor's host property isn't correctly set when s.url is relative
				urlAnchor.href = urlAnchor.href;
				s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
					urlAnchor.protocol + "//" + urlAnchor.host;
			} catch ( e ) {

				// If there is an error parsing the URL, assume it is crossDomain,
				// it can be rejected by the transport if it is invalid
				s.crossDomain = true;
			}
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( state === 2 ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
		fireGlobals = jQuery.event && s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		cacheURL = s.url;

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// If data is available, append data to url
			if ( s.data ) {
				cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );

				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add anti-cache in url if needed
			if ( s.cache === false ) {
				s.url = rts.test( cacheURL ) ?

					// If there is already a '_' parameter, set its value
					cacheURL.replace( rts, "$1_=" + nonce++ ) :

					// Otherwise add one to the end
					cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
			}
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &&
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// Aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		for ( i in { success: 1, error: 1, complete: 1 } ) {
			jqXHR[ i ]( s[ i ] );
		}

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( state === 2 ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				state = 1;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Propagate exception as error if not done
				if ( state < 2 ) {
					done( -1, e );

				// Simply rethrow otherwise
				} else {
					throw e;
				}
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Called once
			if ( state === 2 ) {
				return;
			}

			// State is "done" now
			state = 2;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status >= 200 && status < 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// Extract error from statusText and normalize for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );


jQuery._evalUrl = function( url ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (#11264)
		type: "GET",
		dataType: "script",
		async: false,
		global: false,
		"throws": true
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		var wrap;

		if ( jQuery.isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapAll( html.call( this, i ) );
			} );
		}

		if ( this[ 0 ] ) {

			// The elements to wrap the target around
			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstElementChild ) {
					elem = elem.firstElementChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var isFunction = jQuery.isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function() {
		return this.parent().each( function() {
			if ( !jQuery.nodeName( this, "body" ) ) {
				jQuery( this ).replaceWith( this.childNodes );
			}
		} ).end();
	}
} );


jQuery.expr.filters.hidden = function( elem ) {
	return !jQuery.expr.filters.visible( elem );
};
jQuery.expr.filters.visible = function( elem ) {

	// Support: Opera <= 12.12
	// Opera reports offsetWidths and offsetHeights less than zero on some elements
	// Use OR instead of AND as the element is not visible if either is true
	// See tickets #10406 and #13132
	return elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem.getClientRects().length > 0;
};




var r20 = /%20/g,
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( jQuery.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional && jQuery.type( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, value ) {

			// If value is a function, invoke it and return its value
			value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
			s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
		};

	// Set traditional to true for jQuery <= 1.3.2 behavior.
	if ( traditional === undefined ) {
		traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
	}

	// If an array was passed in, assume that it is an array of form elements.
	if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" ).replace( r20, "+" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} )
		.filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} )
		.map( function( i, elem ) {
			var val = jQuery( this ).val();

			return val == null ?
				null :
				jQuery.isArray( val ) ?
					jQuery.map( val, function( val ) {
						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
					} ) :
					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


jQuery.ajaxSettings.xhr = function() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
};

var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE9
		// #1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	xhrSupported = jQuery.ajaxSettings.xhr();

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport( function( options ) {
	var callback, errorCallback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported && !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr();

				xhr.open(
					options.type,
					options.url,
					options.async,
					options.username,
					options.password
				);

				// Apply custom fields if provided
				if ( options.xhrFields ) {
					for ( i in options.xhrFields ) {
						xhr[ i ] = options.xhrFields[ i ];
					}
				}

				// Override mime type if needed
				if ( options.mimeType && xhr.overrideMimeType ) {
					xhr.overrideMimeType( options.mimeType );
				}

				// X-Requested-With header
				// For cross-domain requests, seeing as conditions for a preflight are
				// akin to a jigsaw puzzle, we simply never set it to be sure.
				// (it can always be set on a per-request basis or even using ajaxSetup)
				// For same-domain requests, won't change header if already provided.
				if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
					headers[ "X-Requested-With" ] = "XMLHttpRequest";
				}

				// Set headers
				for ( i in headers ) {
					xhr.setRequestHeader( i, headers[ i ] );
				}

				// Callback
				callback = function( type ) {
					return function() {
						if ( callback ) {
							callback = errorCallback = xhr.onload =
								xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {

								// Support: IE9
								// On a manual native abort, IE9 throws
								// errors on any property access that is not readyState
								if ( typeof xhr.status !== "number" ) {
									complete( 0, "error" );
								} else {
									complete(

										// File: protocol always yields status 0; see #8605, #14207
										xhr.status,
										xhr.statusText
									);
								}
							} else {
								complete(
									xhrSuccessStatus[ xhr.status ] || xhr.status,
									xhr.statusText,

									// Support: IE9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									( xhr.responseType || "text" ) !== "text"  ||
									typeof xhr.responseText !== "string" ?
										{ binary: xhr.response } :
										{ text: xhr.responseText },
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				errorCallback = xhr.onerror = callback( "error" );

				// Support: IE9
				// Use onreadystatechange to replace onabort
				// to handle uncaught aborts
				if ( xhr.onabort !== undefined ) {
					xhr.onabort = errorCallback;
				} else {
					xhr.onreadystatechange = function() {

						// Check readyState before timeout as it changes
						if ( xhr.readyState === 4 ) {

							// Allow onerror to be called first,
							// but that will not handle a native abort
							// Also, save errorCallback to a variable
							// as xhr.onerror cannot be accessed
							window.setTimeout( function() {
								if ( callback ) {
									errorCallback();
								}
							} );
						}
					};
				}

				// Create the abort callback
				callback = callback( "abort" );

				try {

					// Do send the request (this may raise an exception)
					xhr.send( options.hasContent && options.data || null );
				} catch ( e ) {

					// #14683: Only rethrow if this hasn't been notified as an error yet
					if ( callback ) {
						throw e;
					}
				}
			},

			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "<script>" ).prop( {
					charset: s.scriptCharset,
					src: s.url
				} ).on(
					"load error",
					callback = function( evt ) {
						script.remove();
						callback = null;
						if ( evt ) {
							complete( evt.type === "error" ? 404 : 200, evt.type );
						}
					}
				);

				// Use native DOM manipulation to avoid our domManip AJAX trickery
				document.head.appendChild( script[ 0 ] );
			},
			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( !data || typeof data !== "string" ) {
		return null;
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}
	context = context || document;

	var parsed = rsingleTag.exec( data ),
		scripts = !keepScripts && [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts && scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


// Keep a copy of the old load method
var _load = jQuery.fn.load;

/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	if ( typeof url !== "string" && _load ) {
		return _load.apply( this, arguments );
	}

	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off > -1 ) {
		selector = jQuery.trim( url.slice( off ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( jQuery.isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback && function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.expr.filters.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};




/**
 * Gets a window from an element
 */
function getWindow( elem ) {
	return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}

jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// Set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
			( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;

		// Need to be able to calculate position if either
		// top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;

		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );

		} else {
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {
	offset: function( options ) {
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var docElem, win,
			elem = this[ 0 ],
			box = { top: 0, left: 0 },
			doc = elem && elem.ownerDocument;

		if ( !doc ) {
			return;
		}

		docElem = doc.documentElement;

		// Make sure it's not a disconnected DOM node
		if ( !jQuery.contains( docElem, elem ) ) {
			return box;
		}

		box = elem.getBoundingClientRect();
		win = getWindow( doc );
		return {
			top: box.top + win.pageYOffset - docElem.clientTop,
			left: box.left + win.pageXOffset - docElem.clientLeft
		};
	},

	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset,
			elem = this[ 0 ],
			parentOffset = { top: 0, left: 0 };

		// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
		// because it is its only offset parent
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// Assume getBoundingClientRect is there when computed position is fixed
			offset = elem.getBoundingClientRect();

		} else {

			// Get *real* offsetParent
			offsetParent = this.offsetParent();

			// Get correct offsets
			offset = this.offset();
			if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
				parentOffset = offsetParent.offset();
			}

			// Add offsetParent borders
			parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
			parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
		}

		// Subtract parent offsets and element margins
		return {
			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	// This method will return documentElement in the following cases:
	// 1) For the element inside the iframe without offsetParent, this method will return
	//    documentElement of the parent window
	// 2) For the hidden or detached element
	// 3) For body or html element, i.e. in case of the html node - it will return itself
	//
	// but those exceptions were never presented as a real life use-cases
	// and might be considered as more preferable results.
	//
	// This logic, however, is not guaranteed and can change at any point in the future
	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = "pageYOffset" === prop;

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {
			var win = getWindow( elem );

			if ( val === undefined ) {
				return win ? win[ prop ] : elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : win.pageXOffset,
					top ? val : win.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length );
	};
} );

// Support: Safari<7-8+, Chrome<37-44+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
		function( defaultExtra, funcName ) {

		// Margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( jQuery.isWindow( elem ) ) {

					// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
					// isn't a whole lot we can do. See pull request at this URL for discussion:
					// https://github.com/jquery/jquery/pull/764
					return elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable, null );
		};
	} );
} );


jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	},
	size: function() {
		return this.length;
	}
} );

jQuery.fn.andSelf = jQuery.fn.addBack;




// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( typeof define === "function" && define.amd ) {
	define( "jquery", [], function() {
		return jQuery;
	} );
}



var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep && window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
	window.jQuery = window.$ = jQuery;
}

return jQuery;
}));

},{}],"jsnlog":[function(require,module,exports){
/// <reference path="Definitions/jsnlog_interfaces.d.ts"/>
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
function JL(loggerName) {
    // If name is empty, return the root logger
    if (!loggerName) {
        return JL.__;
    }
    // Implements Array.reduce. JSNLog supports IE8+ and reduce is not supported in that browser.
    // Same interface as the standard reduce, except that 
    if (!Array.prototype.reduce) {
        Array.prototype.reduce = function (callback, initialValue) {
            var previousValue = initialValue;
            for (var i = 0; i < this.length; i++) {
                previousValue = callback(previousValue, this[i], i, this);
            }
            return previousValue;
        };
    }
    var accumulatedLoggerName = '';
    var logger = ('.' + loggerName).split('.').reduce(function (prev, curr, idx, arr) {
        // if loggername is a.b.c, than currentLogger will be set to the loggers
        // root   (prev: JL, curr: '')
        // a      (prev: JL.__, curr: 'a')
        // a.b    (prev: JL.__.__a, curr: 'b')
        // a.b.c  (prev: JL.__.__a.__a.b, curr: 'c')
        // Note that when a new logger name is encountered (such as 'a.b.c'),
        // a new logger object is created and added as a property to the parent ('a.b').
        // The root logger is added as a property of the JL object itself.
        // It is essential that the name of the property containing the child logger
        // contains the full 'path' name of the child logger ('a.b.c') instead of
        // just the bit after the last period ('c').
        // This is because the parent inherits properties from its ancestors.
        // So if the root has a child logger 'c' (stored in a property 'c' of the root logger),
        // then logger 'a.b' has that same property 'c' through inheritance.
        // The names of the logger properties start with __, so the root logger 
        // (which has name ''), has a nice property name '__'.              
        // accumulatedLoggerName evaluates false ('' is falsy) in first iteration when prev is the root logger.
        // accumulatedLoggerName will be the logger name corresponding with the logger in currentLogger.
        // Keep in mind that the currentLogger may not be defined yet, so can't get the name from
        // the currentLogger object itself. 
        if (accumulatedLoggerName) {
            accumulatedLoggerName += '.' + curr;
        }
        else {
            accumulatedLoggerName = curr;
        }
        var currentLogger = prev['__' + accumulatedLoggerName];
        // If the currentLogger (or the actual logger being sought) does not yet exist, 
        // create it now.
        if (currentLogger === undefined) {
            // Set the prototype of the Logger constructor function to the parent of the logger
            // to be created. This way, __proto of the new logger object will point at the parent.
            // When logger.level is evaluated and is not present, the JavaScript runtime will 
            // walk down the prototype chain to find the first ancestor with a level property.
            //
            // Note that prev at this point refers to the parent logger.
            JL.Logger.prototype = prev;
            currentLogger = new JL.Logger(accumulatedLoggerName);
            prev['__' + accumulatedLoggerName] = currentLogger;
        }
        return currentLogger;
    }, JL.__);
    return logger;
}
var JL;
(function (JL) {
    // Initialise requestId to empty string. If you don't do this and the user
    // does not set it via setOptions, then the JSNLog-RequestId header will
    // have value "undefined", which doesn't look good in a log.
    //
    // Note that you always want to send a requestId as part of log requests,
    // otherwise the server side component doesn't know this is a log request
    // and may create a new request id for the log request, causing confusion
    // in the log.
    JL.requestId = '';
    /**
    Copies the value of a property from one object to the other.
    This is used to copy property values as part of setOption for loggers and appenders.

    Because loggers inherit property values from their parents, it is important never to
    create a property on a logger if the intent is to inherit from the parent.

    Copying rules:
    1) if the from property is undefined (for example, not mentioned in a JSON object), the
       to property is not affected at all.
    2) if the from property is null, the to property is deleted (so the logger will inherit from
       its parent).
    3) Otherwise, the from property is copied to the to property.
    */
    function copyProperty(propertyName, from, to) {
        if (from[propertyName] === undefined) {
            return;
        }
        if (from[propertyName] === null) {
            delete to[propertyName];
            return;
        }
        to[propertyName] = from[propertyName];
    }
    /**
    Returns true if a log should go ahead.
    Does not check level.

    @param filters
        Filters that determine whether a log can go ahead.
    */
    function allow(filters) {
        // If enabled is not null or undefined, then if it is false, then return false
        // Note that undefined==null (!)
        if (!(JL.enabled == null)) {
            if (!JL.enabled) {
                return false;
            }
        }
        // If maxMessages is not null or undefined, then if it is 0, then return false.
        // Note that maxMessages contains number of messages that are still allowed to send.
        // It is decremented each time messages are sent. It can be negative when batch size > 1.
        // Note that undefined==null (!)
        if (!(JL.maxMessages == null)) {
            if (JL.maxMessages < 1) {
                return false;
            }
        }
        // If the regex contains a bug, that will throw an exception.
        // Ignore this, and pass the log item (better too much than too little).
        try {
            if (filters.userAgentRegex) {
                if (!new RegExp(filters.userAgentRegex).test(navigator.userAgent)) {
                    return false;
                }
            }
        }
        catch (e) { }
        try {
            if (filters.ipRegex && JL.clientIP) {
                if (!new RegExp(filters.ipRegex).test(JL.clientIP)) {
                    return false;
                }
            }
        }
        catch (e) { }
        return true;
    }
    /**
    Returns true if a log should go ahead, based on the message.

    @param filters
        Filters that determine whether a log can go ahead.

    @param message
        Message to be logged.
    */
    function allowMessage(filters, message) {
        // If the regex contains a bug, that will throw an exception.
        // Ignore this, and pass the log item (better too much than too little).
        try {
            if (filters.disallow) {
                if (new RegExp(filters.disallow).test(message)) {
                    return false;
                }
            }
        }
        catch (e) { }
        return true;
    }
    // If logObject is a function, the function is evaluated (without parameters)
    // and the result returned.
    // Otherwise, logObject itself is returned.
    function stringifyLogObjectFunction(logObject) {
        if (typeof logObject == "function") {
            if (logObject instanceof RegExp) {
                return logObject.toString();
            }
            else {
                return logObject();
            }
        }
        return logObject;
    }
    var StringifiedLogObject = (function () {
        // * msg - 
        //      if the logObject is a scalar (after possible function evaluation), this is set to
        //      string representing the scalar. Otherwise it is left undefined.
        // * meta -
        //      if the logObject is an object (after possible function evaluation), this is set to
        //      that object. Otherwise it is left undefined.
        // * finalString -
        //      This is set to the string representation of logObject (after possible function evaluation),
        //      regardless of whether it is an scalar or an object. An object is stringified to a JSON string.
        //      Note that you can't call this field "final", because as some point this was a reserved
        //      JavaScript keyword and using final trips up some minifiers.
        function StringifiedLogObject(msg, meta, finalString) {
            this.msg = msg;
            this.meta = meta;
            this.finalString = finalString;
        }
        return StringifiedLogObject;
    })();
    // Takes a logObject, which can be 
    // * a scalar
    // * an object
    // * a parameterless function, which returns the scalar or object to log.
    // Returns a stringifiedLogObject
    function stringifyLogObject(logObject) {
        // Note that this works if logObject is null.
        // typeof null is object.
        // JSON.stringify(null) returns "null".
        var actualLogObject = stringifyLogObjectFunction(logObject);
        var finalString;
        // Note that typeof actualLogObject should not be "function", because that has 
        // been resolved with stringifyLogObjectFunction.
        switch (typeof actualLogObject) {
            case "string":
                return new StringifiedLogObject(actualLogObject, null, actualLogObject);
            case "number":
                finalString = actualLogObject.toString();
                return new StringifiedLogObject(finalString, null, finalString);
            case "boolean":
                finalString = actualLogObject.toString();
                return new StringifiedLogObject(finalString, null, finalString);
            case "undefined":
                return new StringifiedLogObject("undefined", null, "undefined");
            case "object":
                if ((actualLogObject instanceof RegExp) ||
                    (actualLogObject instanceof String) ||
                    (actualLogObject instanceof Number) ||
                    (actualLogObject instanceof Boolean)) {
                    finalString = actualLogObject.toString();
                    return new StringifiedLogObject(finalString, null, finalString);
                }
                else {
                    return new StringifiedLogObject(null, actualLogObject, JSON.stringify(actualLogObject));
                }
            default:
                return new StringifiedLogObject("unknown", null, "unknown");
        }
    }
    function setOptions(options) {
        copyProperty("enabled", options, this);
        copyProperty("maxMessages", options, this);
        copyProperty("defaultAjaxUrl", options, this);
        copyProperty("clientIP", options, this);
        copyProperty("requestId", options, this);
        copyProperty("defaultBeforeSend", options, this);
        return this;
    }
    JL.setOptions = setOptions;
    function getAllLevel() { return -2147483648; }
    JL.getAllLevel = getAllLevel;
    function getTraceLevel() { return 1000; }
    JL.getTraceLevel = getTraceLevel;
    function getDebugLevel() { return 2000; }
    JL.getDebugLevel = getDebugLevel;
    function getInfoLevel() { return 3000; }
    JL.getInfoLevel = getInfoLevel;
    function getWarnLevel() { return 4000; }
    JL.getWarnLevel = getWarnLevel;
    function getErrorLevel() { return 5000; }
    JL.getErrorLevel = getErrorLevel;
    function getFatalLevel() { return 6000; }
    JL.getFatalLevel = getFatalLevel;
    function getOffLevel() { return 2147483647; }
    JL.getOffLevel = getOffLevel;
    function levelToString(level) {
        if (level <= 1000) {
            return "trace";
        }
        if (level <= 2000) {
            return "debug";
        }
        if (level <= 3000) {
            return "info";
        }
        if (level <= 4000) {
            return "warn";
        }
        if (level <= 5000) {
            return "error";
        }
        return "fatal";
    }
    // ---------------------
    var Exception = (function () {
        // data replaces message. It takes not just strings, but also objects and functions, just like the log function.
        // internally, the string representation is stored in the message property (inherited from Error)
        //
        // inner: inner exception. Can be null or undefined. 
        function Exception(data, inner) {
            this.inner = inner;
            this.name = "JL.Exception";
            this.message = stringifyLogObject(data).finalString;
        }
        return Exception;
    })();
    JL.Exception = Exception;
    // Derive Exception from Error (a Host object), so browsers
    // are more likely to produce a stack trace for it in their console.
    //
    // Note that instanceof against an object created with this constructor
    // will return true in these cases:
    // <object> instanceof JL.Exception);
    // <object> instanceof Error);
    Exception.prototype = new Error();
    // ---------------------
    var LogItem = (function () {
        // l: level
        // m: message
        // n: logger name
        // t (timeStamp) is number of milliseconds since 1 January 1970 00:00:00 UTC
        //
        // Keeping the property names really short, because they will be sent in the
        // JSON payload to the server.
        function LogItem(l, m, n, t) {
            this.l = l;
            this.m = m;
            this.n = n;
            this.t = t;
        }
        return LogItem;
    })();
    JL.LogItem = LogItem;
    // ---------------------
    var Appender = (function () {
        // sendLogItems takes an array of log items. It will be called when
        // the appender has items to process (such as, send to the server).
        // Note that after sendLogItems returns, the appender may truncate
        // the LogItem array, so the function has to copy the content of the array
        // in some fashion (eg. serialize) before returning.
        function Appender(appenderName, sendLogItems) {
            this.appenderName = appenderName;
            this.sendLogItems = sendLogItems;
            this.level = JL.getTraceLevel();
            // set to super high level, so if user increases level, level is unlikely to get 
            // above sendWithBufferLevel
            this.sendWithBufferLevel = 2147483647;
            this.storeInBufferLevel = -2147483648;
            this.bufferSize = 0; // buffering switch off by default
            this.batchSize = 1;
            // Holds all log items with levels higher than storeInBufferLevel 
            // but lower than level. These items may never be sent.
            this.buffer = [];
            // Holds all items that we do want to send, until we have a full
            // batch (as determined by batchSize).
            this.batchBuffer = [];
        }
        Appender.prototype.setOptions = function (options) {
            copyProperty("level", options, this);
            copyProperty("ipRegex", options, this);
            copyProperty("userAgentRegex", options, this);
            copyProperty("disallow", options, this);
            copyProperty("sendWithBufferLevel", options, this);
            copyProperty("storeInBufferLevel", options, this);
            copyProperty("bufferSize", options, this);
            copyProperty("batchSize", options, this);
            if (this.bufferSize < this.buffer.length) {
                this.buffer.length = this.bufferSize;
            }
            return this;
        };
        /**
        Called by a logger to log a log item.
        If in response to this call one or more log items need to be processed
        (eg., sent to the server), this method calls this.sendLogItems
        with an array with all items to be processed.

        Note that the name and parameters of this function must match those of the log function of
        a Winston transport object, so that users can use these transports as appenders.
        That is why there are many parameters that are not actually used by this function.

        level - string with the level ("trace", "debug", etc.) Only used by Winston transports.
        msg - human readable message. Undefined if the log item is an object. Only used by Winston transports.
        meta - log object. Always defined, because at least it contains the logger name. Only used by Winston transports.
        callback - function that is called when the log item has been logged. Only used by Winston transports.
        levelNbr - level as a number. Not used by Winston transports.
        message - log item. If the user logged an object, this is the JSON string.  Not used by Winston transports.
        loggerName: name of the logger.  Not used by Winston transports.
        */
        Appender.prototype.log = function (level, msg, meta, callback, levelNbr, message, loggerName) {
            var logItem;
            if (!allow(this)) {
                return;
            }
            if (!allowMessage(this, message)) {
                return;
            }
            if (levelNbr < this.storeInBufferLevel) {
                // Ignore the log item completely
                return;
            }
            logItem = new LogItem(levelNbr, message, loggerName, (new Date).getTime());
            if (levelNbr < this.level) {
                // Store in the hold buffer. Do not send.
                if (this.bufferSize > 0) {
                    this.buffer.push(logItem);
                    // If we exceeded max buffer size, remove oldest item
                    if (this.buffer.length > this.bufferSize) {
                        this.buffer.shift();
                    }
                }
                return;
            }
            if (levelNbr < this.sendWithBufferLevel) {
                // Want to send the item, but not the contents of the buffer
                this.batchBuffer.push(logItem);
            }
            else {
                // Want to send both the item and the contents of the buffer.
                // Send contents of buffer first, because logically they happened first.
                if (this.buffer.length) {
                    this.batchBuffer = this.batchBuffer.concat(this.buffer);
                    this.buffer.length = 0;
                }
                this.batchBuffer.push(logItem);
            }
            if (this.batchBuffer.length >= this.batchSize) {
                this.sendBatch();
                return;
            }
        };
        // Processes the batch buffer
        Appender.prototype.sendBatch = function () {
            if (this.batchBuffer.length == 0) {
                return;
            }
            if (!(JL.maxMessages == null)) {
                if (JL.maxMessages < 1) {
                    return;
                }
            }
            // If maxMessages is not null or undefined, then decrease it by the batch size.
            // This can result in a negative maxMessages.
            // Note that undefined==null (!)
            if (!(JL.maxMessages == null)) {
                JL.maxMessages -= this.batchBuffer.length;
            }
            this.sendLogItems(this.batchBuffer);
            this.batchBuffer.length = 0;
        };
        return Appender;
    })();
    JL.Appender = Appender;
    // ---------------------
    var AjaxAppender = (function (_super) {
        __extends(AjaxAppender, _super);
        function AjaxAppender(appenderName) {
            _super.call(this, appenderName, AjaxAppender.prototype.sendLogItemsAjax);
        }
        AjaxAppender.prototype.setOptions = function (options) {
            copyProperty("url", options, this);
            copyProperty("beforeSend", options, this);
            _super.prototype.setOptions.call(this, options);
            return this;
        };
        AjaxAppender.prototype.sendLogItemsAjax = function (logItems) {
            // JSON.stringify is only supported on IE8+
            // Use try-catch in case we get an exception here.
            //
            // The "r" field is now obsolete. When writing a server side component, 
            // read the HTTP header "JSNLog-RequestId"
            // to get the request id.
            //
            // The .Net server side component
            // now uses the JSNLog-RequestId HTTP Header, because this allows it to
            // detect whether the incoming request has a request id.
            // If the request id were in the json payload, it would have to read the json
            // from the stream, interfering with normal non-logging requests.
            //
            // To see what characters you can use in the HTTP header, visit:
            // http://stackoverflow.com/questions/3561381/custom-http-headers-naming-conventions/3561399#3561399
            //
            // It needs this ability, so users of NLog can set a requestId variable in NLog
            // before the server side component tries to log the client side log message
            // through an NLog logger.
            // Unlike Log4Net, NLog doesn't allow you to register an object whose ToString()
            // is only called when it tries to log something, so the requestId has to be 
            // determined right at the start of request processing.
            try {
                // Only determine the url right before you send a log request.
                // Do not set the url when constructing the appender.
                //
                // This is because the server side component sets defaultAjaxUrl
                // in a call to setOptions, AFTER the JL object and the default appender
                // have been created. 
                var ajaxUrl = "/jsnlog.logger";
                // This evaluates to true if defaultAjaxUrl is null or undefined
                if (!(JL.defaultAjaxUrl == null)) {
                    ajaxUrl = JL.defaultAjaxUrl;
                }
                if (this.url) {
                    ajaxUrl = this.url;
                }
                // Send the json to the server. 
                // Note that there is no event handling here. If the send is not
                // successful, nothing can be done about it.
                var xhr = this.getXhr(ajaxUrl);
                var json = {
                    r: JL.requestId,
                    lg: logItems
                };
                // call beforeSend callback
                // first try the callback on the appender
                // then the global defaultBeforeSend callback
                if (typeof this.beforeSend === 'function') {
                    this.beforeSend.call(this, xhr, json);
                }
                else if (typeof JL.defaultBeforeSend === 'function') {
                    JL.defaultBeforeSend.call(this, xhr, json);
                }
                var finalmsg = JSON.stringify(json);
                xhr.send(finalmsg);
            }
            catch (e) { }
        };
        // Creates the Xhr object to use to send the log request.
        // Sets out to create an Xhr object that can be used for CORS.
        // However, if there seems to be no CORS support on the browser,
        // returns a non-CORS capable Xhr.
        AjaxAppender.prototype.getXhr = function (ajaxUrl) {
            var xhr = new XMLHttpRequest();
            // Check whether this xhr is CORS capable by checking whether it has
            // withCredentials. 
            // "withCredentials" only exists on XMLHTTPRequest2 objects.
            if (!("withCredentials" in xhr)) {
                // Just found that no XMLHttpRequest2 available.
                // Check if XDomainRequest is available.
                // This only exists in IE, and is IE's way of making CORS requests.
                if (typeof XDomainRequest != "undefined") {
                    // Note that here we're not setting request headers on the XDomainRequest
                    // object. This is because this object doesn't let you do that:
                    // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
                    // This means that for IE8 and IE9, CORS logging requests do not carry request ids.
                    var xdr = new XDomainRequest();
                    xdr.open('POST', ajaxUrl);
                    return xdr;
                }
            }
            // At this point, we're going with XMLHttpRequest, whether it is CORS capable or not.
            // If it is not CORS capable, at least will handle the non-CORS requests.
            xhr.open('POST', ajaxUrl);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('JSNLog-RequestId', JL.requestId);
            return xhr;
        };
        return AjaxAppender;
    })(Appender);
    JL.AjaxAppender = AjaxAppender;
    // ---------------------
    var ConsoleAppender = (function (_super) {
        __extends(ConsoleAppender, _super);
        function ConsoleAppender(appenderName) {
            _super.call(this, appenderName, ConsoleAppender.prototype.sendLogItemsConsole);
        }
        ConsoleAppender.prototype.clog = function (logEntry) {
            console.log(logEntry);
        };
        ConsoleAppender.prototype.cerror = function (logEntry) {
            if (console.error) {
                console.error(logEntry);
            }
            else {
                this.clog(logEntry);
            }
        };
        ConsoleAppender.prototype.cwarn = function (logEntry) {
            if (console.warn) {
                console.warn(logEntry);
            }
            else {
                this.clog(logEntry);
            }
        };
        ConsoleAppender.prototype.cinfo = function (logEntry) {
            if (console.info) {
                console.info(logEntry);
            }
            else {
                this.clog(logEntry);
            }
        };
        // IE11 has a console.debug function. But its console doesn't have 
        // the option to show/hide debug messages (the same way Chrome and FF do),
        // even though it does have such buttons for Error, Warn, Info.
        //
        // For now, this means that debug messages can not be hidden on IE.
        // Live with this, seeing that it works fine on FF and Chrome, which
        // will be much more popular with developers.
        ConsoleAppender.prototype.cdebug = function (logEntry) {
            if (console.debug) {
                console.debug(logEntry);
            }
            else {
                this.cinfo(logEntry);
            }
        };
        ConsoleAppender.prototype.sendLogItemsConsole = function (logItems) {
            try {
                if (!console) {
                    return;
                }
                var i;
                for (i = 0; i < logItems.length; ++i) {
                    var li = logItems[i];
                    var msg = li.n + ": " + li.m;
                    // Only log the timestamp if we're on the server
                    // (window is undefined). On the browser, the user
                    // sees the log entry probably immediately, so in that case
                    // the timestamp is clutter.
                    if (typeof window === 'undefined') {
                        msg = new Date(li.t) + " | " + msg;
                    }
                    if (li.l <= JL.getDebugLevel()) {
                        this.cdebug(msg);
                    }
                    else if (li.l <= JL.getInfoLevel()) {
                        this.cinfo(msg);
                    }
                    else if (li.l <= JL.getWarnLevel()) {
                        this.cwarn(msg);
                    }
                    else {
                        this.cerror(msg);
                    }
                }
            }
            catch (e) {
            }
        };
        return ConsoleAppender;
    })(Appender);
    JL.ConsoleAppender = ConsoleAppender;
    // --------------------
    var Logger = (function () {
        function Logger(loggerName) {
            this.loggerName = loggerName;
            // Create seenRexes, otherwise this logger will use the seenRexes
            // of its parent via the prototype chain.
            this.seenRegexes = [];
        }
        Logger.prototype.setOptions = function (options) {
            copyProperty("level", options, this);
            copyProperty("userAgentRegex", options, this);
            copyProperty("disallow", options, this);
            copyProperty("ipRegex", options, this);
            copyProperty("appenders", options, this);
            copyProperty("onceOnly", options, this);
            // Reset seenRegexes, in case onceOnly has been changed.
            this.seenRegexes = [];
            return this;
        };
        // Turns an exception into an object that can be sent to the server.
        Logger.prototype.buildExceptionObject = function (e) {
            var excObject = {};
            if (e.stack) {
                excObject.stack = e.stack;
            }
            else {
                excObject.e = e;
            }
            if (e.message) {
                excObject.message = e.message;
            }
            if (e.name) {
                excObject.name = e.name;
            }
            if (e.data) {
                excObject.data = e.data;
            }
            if (e.inner) {
                excObject.inner = this.buildExceptionObject(e.inner);
            }
            return excObject;
        };
        // Logs a log item.
        // Parameter e contains an exception (or null or undefined).
        //
        // Reason that processing exceptions is done at this low level is that
        // 1) no need to spend the cpu cycles if the logger is switched off
        // 2) fatalException takes both a logObject and an exception, and the logObject
        //    may be a function that should only be executed if the logger is switched on.
        //
        // If an exception is passed in, the contents of logObject is attached to the exception
        // object in a new property logData.
        // The resulting exception object is than worked into a message to the server.
        //
        // If there is no exception, logObject itself is worked into the message to the server.
        Logger.prototype.log = function (level, logObject, e) {
            var i = 0;
            var compositeMessage;
            var excObject;
            // If we can't find any appenders, do nothing
            if (!this.appenders) {
                return this;
            }
            if (((level >= this.level)) && allow(this)) {
                if (e) {
                    excObject = this.buildExceptionObject(e);
                    excObject.logData = stringifyLogObjectFunction(logObject);
                }
                else {
                    excObject = logObject;
                }
                compositeMessage = stringifyLogObject(excObject);
                if (allowMessage(this, compositeMessage.finalString)) {
                    // See whether message is a duplicate
                    if (this.onceOnly) {
                        i = this.onceOnly.length - 1;
                        while (i >= 0) {
                            if (new RegExp(this.onceOnly[i]).test(compositeMessage.finalString)) {
                                if (this.seenRegexes[i]) {
                                    return this;
                                }
                                this.seenRegexes[i] = true;
                            }
                            i--;
                        }
                    }
                    // Pass message to all appenders
                    // Note that these appenders could be Winston transports
                    // https://github.com/flatiron/winston
                    //
                    // These transports do not take the logger name as a parameter.
                    // So add it to the meta information, so even Winston transports will
                    // store this info.
                    compositeMessage.meta = compositeMessage.meta || {};
                    compositeMessage.meta.loggerName = this.loggerName;
                    i = this.appenders.length - 1;
                    while (i >= 0) {
                        this.appenders[i].log(levelToString(level), compositeMessage.msg, compositeMessage.meta, function () { }, level, compositeMessage.finalString, this.loggerName);
                        i--;
                    }
                }
            }
            return this;
        };
        Logger.prototype.trace = function (logObject) { return this.log(getTraceLevel(), logObject); };
        Logger.prototype.debug = function (logObject) { return this.log(getDebugLevel(), logObject); };
        Logger.prototype.info = function (logObject) { return this.log(getInfoLevel(), logObject); };
        Logger.prototype.warn = function (logObject) { return this.log(getWarnLevel(), logObject); };
        Logger.prototype.error = function (logObject) { return this.log(getErrorLevel(), logObject); };
        Logger.prototype.fatal = function (logObject) { return this.log(getFatalLevel(), logObject); };
        Logger.prototype.fatalException = function (logObject, e) { return this.log(getFatalLevel(), logObject, e); };
        return Logger;
    })();
    JL.Logger = Logger;
    function createAjaxAppender(appenderName) {
        return new AjaxAppender(appenderName);
    }
    JL.createAjaxAppender = createAjaxAppender;
    function createConsoleAppender(appenderName) {
        return new ConsoleAppender(appenderName);
    }
    JL.createConsoleAppender = createConsoleAppender;
    // -----------------------
    // In the browser, the default appender is the AjaxAppender.
    // Under nodejs (where there is no "window"), use the ConsoleAppender instead.
    var defaultAppender = new AjaxAppender("");
    if (typeof window === 'undefined') {
        defaultAppender = new ConsoleAppender("");
    }
    // Create root logger
    //
    // Note that this is the parent of all other loggers.
    // Logger "x" will be stored at
    // JL.__.x
    // Logger "x.y" at
    // JL.__.x.y
    JL.__ = new JL.Logger("");
    JL.__.setOptions({
        level: JL.getDebugLevel(),
        appenders: [defaultAppender]
    });
})(JL || (JL = {}));
if (typeof exports !== 'undefined') {
    exports.JL = JL;
}
// Support AMD module format
var define;
if (typeof define == 'function' && define.amd) {
    define('jsnlog', [], function () {
        return JL;
    });
}
// If the __jsnlog_configure global function has been
// created, call it now. This allows you to create a global function
// setting logger options etc. inline in the page before jsnlog.js
// has been loaded.
if (typeof __jsnlog_configure == 'function') {
    __jsnlog_configure(JL);
}

},{}],"numbro/numbro":[function(require,module,exports){
/*!
 * numbro.js
 * version : 1.6.2
 * author : Företagsplatsen AB
 * license : MIT
 * http://www.foretagsplatsen.se
 */

var _ = require("underscore");

    /************************************
        Constants
    ************************************/

    var numbro,
        VERSION = '1.6.2',
    // internal storage for culture config files
        cultures = {},
    // Todo: Remove in 2.0.0
        languages = cultures,
        currentCulture = 'en-US',
        zeroFormat = null,
        defaultFormat = '0,0',
        defaultCurrencyFormat = '0$',
        // check for nodeJS
        hasModule = (typeof module !== 'undefined' && module.exports),
    // default culture
        enUS = {
            delimiters: {
                thousands: ',',
                decimal: '.'
            },
            abbreviations: {
                thousand: 'k',
                million: 'm',
                billion: 'b',
                trillion: 't'
            },
            ordinal: function(number) {
                var b = number % 10;
                return (~~(number % 100 / 10) === 1) ? 'th' :
                    (b === 1) ? 'st' :
                        (b === 2) ? 'nd' :
                            (b === 3) ? 'rd' : 'th';
            },
            currency: {
                symbol: '$',
                position: 'prefix'
            },
            defaults: {
                currencyFormat: ',0000 a'
            },
            formats: {
                fourDigits: '0000 a',
                fullWithTwoDecimals: '$ ,0.00',
                fullWithTwoDecimalsNoCurrency: ',0.00'
            }
        };

    /************************************
        Constructors
    ************************************/


    // Numbro prototype object
    function Numbro(number) {
        this._value = number;
    }

    function zeroes(count) {
        var i, ret = '';

        for (i = 0; i < count; i++) {
            ret += '0';
        }

        return ret;
    }
    /**
     * Implementation of toFixed() for numbers with exponent > 21
     *
     *
     */
    function toFixedLarge(value, precision) {
        var mantissa,
            beforeDec,
            afterDec,
            exponent,
            str;

        str = value.toString();

        mantissa = str.split('e')[0];
        exponent  = str.split('e')[1];

        beforeDec = mantissa.split('.')[0];
        afterDec = mantissa.split('.')[1] || '';

        str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
        if (precision > 0) {
            str += '.' + zeroes(precision);
        }

        return str;
    }

    /**
     * Implementation of toFixed() that treats floats more like decimals
     *
     * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
     * problems for accounting- and finance-related software.
     */
    function toFixed(value, precision, roundingFunction, optionals) {
        var power = Math.pow(10, precision),
            optionalsRegExp,
            output;

        if (value.toFixed(0).search('e') > -1) {
            // Above 1e21, toFixed returns scientific notation, which
            // is useless and unexpected
            output = toFixedLarge(value, precision);
        }
        else {
            //roundingFunction = (roundingFunction !== undefined ? roundingFunction : Math.round);
            // Multiply up by precision, round accurately, then divide and use native toFixed():
            output = (roundingFunction(value * power) / power).toFixed(precision);
        }

        if (optionals) {
            optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
            output = output.replace(optionalsRegExp, '');
        }

        return output;
    }

    /************************************
        Formatting
    ************************************/

    // determine what type of formatting we need to do
    function formatNumbro(value, format, roundingFunction) {
        var output;
        // TODO: do something with `language`

        // figure out what kind of format we are dealing with
        if (format.indexOf('$') > -1) { // currency!!!!!
            output = formatCurrency(value, format, roundingFunction);
        } else if (format.indexOf('%') > -1) { // percentage
            output = formatPercentage(value, format, roundingFunction);
        } else if (format.indexOf(':') > -1) { // time
            output = formatTime(value);
        } else { // plain ol' numbers or bytes
            output = formatNumber(value, format, roundingFunction);
        }

        // return string
        return output;
    }

    function formatCurrency(value, originalFormat, roundingFunction) {
        var format = originalFormat,
            symbolIndex = format.indexOf('$'),
            openParenIndex = format.indexOf('('),
            plusSignIndex = format.indexOf('+'),
            minusSignIndex = format.indexOf('-'),
            space = '',
            decimalSeparator = '',
            spliceIndex,
            output;

        if(format.indexOf('$') === -1){
            // Use defaults instead of the format provided
            if (cultures[currentCulture].currency.position === 'infix') {
                decimalSeparator = cultures[currentCulture].currency.symbol;
                if (cultures[currentCulture].currency.spaceSeparated) {
                    decimalSeparator = ' ' + decimalSeparator + ' ';
                }
            } else if (cultures[currentCulture].currency.spaceSeparated) {
                space = ' ';
            }
        } else {
            // check for space before or after currency
            if (format.indexOf(' $') > -1) {
                space = ' ';
                format = format.replace(' $', '');
            } else if (format.indexOf('$ ') > -1) {
                space = ' ';
                format = format.replace('$ ', '');
            } else {
                format = format.replace('$', '');
            }
        }

        // Format The Number
        output = formatNumber(value, format, roundingFunction, decimalSeparator);

        if (originalFormat.indexOf('$') === -1) {
            // Use defaults instead of the format provided
            switch (cultures[currentCulture].currency.position) {
                case 'postfix':
                    if (output.indexOf(')') > -1) {
                        output = output.split('');
                        output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                        output = output.join('');
                    } else {
                        output = output + space + cultures[currentCulture].currency.symbol;
                    }
                    break;
                case 'infix':
                    break;
                case 'prefix':
                    if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
                        output = output.split('');
                        spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;

                        output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                        output = output.join('');
                    } else {
                        output = cultures[currentCulture].currency.symbol + space + output;
                    }
                    break;
                default:
                    throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
            }
        } else {
            // position the symbol
            if (symbolIndex <= 1) {
                if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
                    output = output.split('');
                    spliceIndex = 1;
                    if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
                        // the symbol appears before the "(", "+" or "-"
                        spliceIndex = 0;
                    }
                    output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
                    output = output.join('');
                } else {
                    output = cultures[currentCulture].currency.symbol + space + output;
                }
            } else {
                if (output.indexOf(')') > -1) {
                    output = output.split('');
                    output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
                    output = output.join('');
                } else {
                    output = output + space + cultures[currentCulture].currency.symbol;
                }
            }
        }

        return output;
    }

    function formatPercentage(value, format, roundingFunction) {
        var space = '',
            output;
        value = value * 100;

        // check for space before %
        if (format.indexOf(' %') > -1) {
            space = ' ';
            format = format.replace(' %', '');
        } else {
            format = format.replace('%', '');
        }

        output = formatNumber(value, format, roundingFunction);

        if (output.indexOf(')') > -1) {
            output = output.split('');
            output.splice(-1, 0, space + '%');
            output = output.join('');
        } else {
            output = output + space + '%';
        }

        return output;
    }

    function formatTime(value) {
        var hours = Math.floor(value / 60 / 60),
            minutes = Math.floor((value - (hours * 60 * 60)) / 60),
            seconds = Math.round(value - (hours * 60 * 60) - (minutes * 60));
        return hours + ':' +
            ((minutes < 10) ? '0' + minutes : minutes) + ':' +
            ((seconds < 10) ? '0' + seconds : seconds);
    }

    function formatNumber (value, format, roundingFunction, sep) {
        var negP = false,
            signed = false,
            optDec = false,
            abbr = '',
            i,
            abbrK = false, // force abbreviation to thousands
            abbrM = false, // force abbreviation to millions
            abbrB = false, // force abbreviation to billions
            abbrT = false, // force abbreviation to trillions
            abbrForce = false, // force abbreviation
            bytes = '',
            ord = '',
            abs = Math.abs(value),
            binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
            decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            min,
            max,
            power,
            totalLength,
            length,
            minimumPrecision,
            pow,
            w,
            intPrecision,
            precision,
            prefix,
            postfix,
            thousands,
            d = '',
            forcedNeg = false,
            neg = false,
            indexOpenP,
            size,
            indexMinus,
            paren = '',
            minlen;

        // check if number is zero and a custom zero format has been set
        if (value === 0 && zeroFormat !== null) {
            return zeroFormat;
        }

        if (!isFinite(value)) {
            return '' + value;
        }

        if (format.indexOf('{') === 0) {
            var end = format.indexOf('}');
            if (end === -1) {
                throw Error('Format should also contain a "}"');
            }
            prefix = format.slice(1, end);
            format = format.slice(end + 1);
        } else {
            prefix = '';
        }

        if (format.indexOf('}') === format.length - 1) {
            var start = format.indexOf('{');
            if (start === -1) {
                throw Error('Format should also contain a "{"');
            }
            postfix = format.slice(start + 1, -1);
            format = format.slice(0, start + 1);
        } else {
            postfix = '';
        }

        // check for min length
        var info;
        if (format.indexOf('.') === -1) {
            info = format.match(/([0-9]+).*/);
        } else {
            info = format.match(/([0-9]+)\..*/);
        }
        minlen = info === null ? -1 : info[1].length;

        // see if we should use parentheses for negative number or if we should prefix with a sign
        // if both are present we default to parentheses
        if (format.indexOf('-') !== -1) {
            forcedNeg = true;
        }
        if (format.indexOf('(') > -1) {
            negP = true;
            format = format.slice(1, -1);
        } else if (format.indexOf('+') > -1) {
            signed = true;
            format = format.replace(/\+/g, '');
        }

        // see if abbreviation is wanted
        if (format.indexOf('a') > -1) {
            intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
            intPrecision = parseInt(intPrecision[0], 10);

            // check if abbreviation is specified
            abbrK = format.indexOf('aK') >= 0;
            abbrM = format.indexOf('aM') >= 0;
            abbrB = format.indexOf('aB') >= 0;
            abbrT = format.indexOf('aT') >= 0;
            abbrForce = abbrK || abbrM || abbrB || abbrT;

            // check for space before abbreviation
            if (format.indexOf(' a') > -1) {
                abbr = ' ';
                format = format.replace(' a', '');
            } else {
                format = format.replace('a', '');
            }

            totalLength = Math.floor(Math.log(abs) / Math.LN10) + 1;

            minimumPrecision = totalLength % 3;
            minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;

            if (intPrecision && abs !== 0) {

                length = Math.floor(Math.log(abs) / Math.LN10) + 1 - intPrecision;

                pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);

                abs = abs / Math.pow(10, pow);

                if (format.indexOf('.') === -1 && intPrecision > 3) {
                    format += '[.]';

                    size = length === 0 ? 0 : 3 * ~~(length / 3) - length;
                    size = size < 0 ? size + 3 : size;

                    for (i = 0; i < size; i++) {
                        format += '0';
                    }
                }
            }

            if (Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1 !== intPrecision) {
                if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
                    // trillion
                    abbr = abbr + cultures[currentCulture].abbreviations.trillion;
                    value = value / Math.pow(10, 12);
                } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
                    // billion
                    abbr = abbr + cultures[currentCulture].abbreviations.billion;
                    value = value / Math.pow(10, 9);
                } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
                    // million
                    abbr = abbr + cultures[currentCulture].abbreviations.million;
                    value = value / Math.pow(10, 6);
                } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
                    // thousand
                    abbr = abbr + cultures[currentCulture].abbreviations.thousand;
                    value = value / Math.pow(10, 3);
                }
            }
        }

        // see if we are formatting binary bytes
        if (format.indexOf('b') > -1) {
            // check for space before
            if (format.indexOf(' b') > -1) {
                bytes = ' ';
                format = format.replace(' b', '');
            } else {
                format = format.replace('b', '');
            }

            for (power = 0; power <= binarySuffixes.length; power++) {
                min = Math.pow(1024, power);
                max = Math.pow(1024, power + 1);

                if (value >= min && value < max) {
                    bytes = bytes + binarySuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }

        // see if we are formatting decimal bytes
        if (format.indexOf('d') > -1) {
            // check for space before
            if (format.indexOf(' d') > -1) {
                bytes = ' ';
                format = format.replace(' d', '');
            } else {
                format = format.replace('d', '');
            }

            for (power = 0; power <= decimalSuffixes.length; power++) {
                min = Math.pow(1000, power);
                max = Math.pow(1000, power + 1);

                if (value >= min && value < max) {
                    bytes = bytes + decimalSuffixes[power];
                    if (min > 0) {
                        value = value / min;
                    }
                    break;
                }
            }
        }

        // see if ordinal is wanted
        if (format.indexOf('o') > -1) {
            // check for space before
            if (format.indexOf(' o') > -1) {
                ord = ' ';
                format = format.replace(' o', '');
            } else {
                format = format.replace('o', '');
            }

            if (cultures[currentCulture].ordinal) {
                ord = ord + cultures[currentCulture].ordinal(value);
            }
        }

        if (format.indexOf('[.]') > -1) {
            optDec = true;
            format = format.replace('[.]', '.');
        }

        w = value.toString().split('.')[0];
        precision = format.split('.')[1];
        thousands = format.indexOf(',');

        if (precision) {
            if (precision.indexOf('*') !== -1) {
                d = toFixed(value, value.toString().split('.')[1].length, roundingFunction);
            } else {
                if (precision.indexOf('[') > -1) {
                    precision = precision.replace(']', '');
                    precision = precision.split('[');
                    d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction,
                        precision[1].length);
                } else {
                    d = toFixed(value, precision.length, roundingFunction);
                }
            }

            w = d.split('.')[0];

            if (d.split('.')[1].length) {
                var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
                d = p + d.split('.')[1];
            } else {
                d = '';
            }

            if (optDec && Number(d.slice(1)) === 0) {
                d = '';
            }
        } else {
            w = toFixed(value, null, roundingFunction);
        }

        // format number
        if (w.indexOf('-') > -1) {
            w = w.slice(1);
            neg = true;
        }

        if (w.length < minlen) {
            w = new Array(minlen - w.length + 1).join('0') + w;
        }

        if (thousands > -1) {
            w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
                cultures[currentCulture].delimiters.thousands);
        }

        if (format.indexOf('.') === 0) {
            w = '';
        }

        indexOpenP = format.indexOf('(');
        indexMinus = format.indexOf('-');

        if (indexOpenP < indexMinus) {
            paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
        } else {
            paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
        }

        return prefix +
            paren + ((!neg && signed && value !== 0) ? '+' : '') +
            w + d +
            ((ord) ? ord : '') +
            ((abbr && !sep) ? abbr : '') +
            ((bytes) ? bytes : '') +
            ((negP && neg) ? ')' : '') +
            postfix;
    }

    /************************************
        Top Level Functions
    ************************************/

    numbro = function(input) {
        if (numbro.isNumbro(input)) {
            input = input.value();
        } else if (input === 0 || typeof input === 'undefined') {
            input = 0;
        } else if (!Number(input)) {
            input = numbro.fn.unformat(input);
        }

        return new Numbro(Number(input));
    };

    // version number
    numbro.version = VERSION;

    // compare numbro object
    numbro.isNumbro = function(obj) {
        return obj instanceof Numbro;
    };

    /**
     * This function allow the user to set a new language with a fallback if
     * the language does not exist. If no fallback language is provided,
     * it fallbacks to english.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `setCulture` should be used instead.
     */
    numbro.setLanguage = function(newLanguage, fallbackLanguage) {
        console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
        var key = newLanguage,
            prefix = newLanguage.split('-')[0],
            matchingLanguage = null;
        if (!languages[key]) {
            Object.keys(languages).forEach(function(language) {
                if (!matchingLanguage && language.split('-')[0] === prefix) {
                    matchingLanguage = language;
                }
            });
            key = matchingLanguage || fallbackLanguage || 'en-US';
        }
        chooseCulture(key);
    };

    /**
     * This function allow the user to set a new culture with a fallback if
     * the culture does not exist. If no fallback culture is provided,
     * it fallbacks to "en-US".
     */
    numbro.setCulture = function(newCulture, fallbackCulture) {
        var key = newCulture,
            suffix = newCulture.split('-')[1],
            matchingCulture = null;
        if (!cultures[key]) {
            if (suffix) {
                Object.keys(cultures).forEach(function(language) {
                    if (!matchingCulture && language.split('-')[1] === suffix) {
                        matchingCulture = language;
                    }
                });
            }

            key = matchingCulture || fallbackCulture || 'en-US';
        }
        chooseCulture(key);
    };

    /**
     * This function will load languages and then set the global language.  If
     * no arguments are passed in, it will simply return the current global
     * language key.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.language = function(key, values) {
        console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');

        if (!key) {
            return currentCulture;
        }

        if (key && !values) {
            if (!languages[key]) {
                throw new Error('Unknown language : ' + key);
            }
            chooseCulture(key);
        }

        if (values || !languages[key]) {
            setCulture(key, values);
        }

        return numbro;
    };

    /**
     * This function will load cultures and then set the global culture.  If
     * no arguments are passed in, it will simply return the current global
     * culture code.
     */
    numbro.culture = function(code, values) {
        if (!code) {
            return currentCulture;
        }

        if (code && !values) {
            if (!cultures[code]) {
                throw new Error('Unknown culture : ' + code);
            }
            chooseCulture(code);
        }

        if (values || !cultures[code]) {
            setCulture(code, values);
        }

        return numbro;
    };

    /**
     * This function provides access to the loaded language data.  If
     * no arguments are passed in, it will simply return the current
     * global language object.
     *
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `culture` should be used instead.
     */
    numbro.languageData = function(key) {
        console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');

        if (!key) {
            return languages[currentCulture];
        }

        if (!languages[key]) {
            throw new Error('Unknown language : ' + key);
        }

        return languages[key];
    };

    /**
     * This function provides access to the loaded culture data.  If
     * no arguments are passed in, it will simply return the current
     * global culture object.
     */
    numbro.cultureData = function(code) {
        if (!code) {
            return cultures[currentCulture];
        }

        if (!cultures[code]) {
            throw new Error('Unknown culture : ' + code);
        }

        return cultures[code];
    };

    numbro.culture('en-US', enUS);

    /**
     * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
     * `cultures` should be used instead.
     */
    numbro.languages = function() {
        console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');

        return languages;
    };

    numbro.cultures = function() {
        return cultures;
    };

    numbro.zeroFormat = function(format) {
        zeroFormat = typeof(format) === 'string' ? format : null;
    };

    numbro.defaultFormat = function(format) {
        defaultFormat = typeof(format) === 'string' ? format : '0.0';
    };

    numbro.defaultCurrencyFormat = function (format) {
        defaultCurrencyFormat = typeof(format) === 'string' ? format : '0$';
    };

    numbro.validate = function(val, culture) {

        var _decimalSep,
            _thousandSep,
            _currSymbol,
            _valArray,
            _abbrObj,
            _thousandRegEx,
            cultureData,
            temp;

        //coerce val to string
        if (typeof val !== 'string') {
            val += '';
            if (console.warn) {
                console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
            }
        }

        //trim whitespaces from either sides
        val = val.trim();

        //if val is just digits return true
        if ( !! val.match(/^\d+$/)) {
            return true;
        }

        //if val is empty return false
        if (val === '') {
            return false;
        }

        //get the decimal and thousands separator from numbro.cultureData
        try {
            //check if the culture is understood by numbro. if not, default it to current culture
            cultureData = numbro.cultureData(culture);
        } catch (e) {
            cultureData = numbro.cultureData(numbro.culture());
        }

        //setup the delimiters and currency symbol based on culture
        _currSymbol = cultureData.currency.symbol;
        _abbrObj = cultureData.abbreviations;
        _decimalSep = cultureData.delimiters.decimal;
        if (cultureData.delimiters.thousands === '.') {
            _thousandSep = '\\.';
        } else {
            _thousandSep = cultureData.delimiters.thousands;
        }

        // validating currency symbol
        temp = val.match(/^[^\d]+/);
        if (temp !== null) {
            val = val.substr(1);
            if (temp[0] !== _currSymbol) {
                return false;
            }
        }

        //validating abbreviation symbol
        temp = val.match(/[^\d]+$/);
        if (temp !== null) {
            val = val.slice(0, -1);
            if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
                    temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
                return false;
            }
        }

        _thousandRegEx = new RegExp(_thousandSep + '{2}');

        if (!val.match(/[^\d.,]/g)) {
            _valArray = val.split(_decimalSep);
            if (_valArray.length > 2) {
                return false;
            } else {
                if (_valArray.length < 2) {
                    return ( !! _valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
                } else {
                    if (_valArray[0].length === 1) {
                        return ( !! _valArray[0].match(/^\d+$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !! _valArray[1].match(/^\d+$/));
                    } else {
                        return ( !! _valArray[0].match(/^\d+.*\d$/) &&
                            !_valArray[0].match(_thousandRegEx) &&
                            !! _valArray[1].match(/^\d+$/));
                    }
                }
            }
        }

        return false;
    };

    /************************************
        Helpers
    ************************************/

    function setCulture(code, values) {
        cultures[code] = values;
    }

    function chooseCulture(code) {
        currentCulture = code;
        var defaults = cultures[code].defaults;
        if (defaults && defaults.format) {
            numbro.defaultFormat(defaults.format);
        }
        if (defaults && defaults.currencyFormat) {
            numbro.defaultCurrencyFormat(defaults.currencyFormat);
        }
    }

    function format(input, formatString, language, roundingFunction) {
        if (_.isString(language) && language !== numbro.culture()) {
            numbro.setCulture(language);
        }
        return formatNumbro(
            Number(input),
            _.isString(formatString)        ? formatString        : defaultFormat,
            _.isUndefined(roundingFunction) ? Math.round          : roundingFunction);
    }

    module.exports = {"format": format};

},{"underscore":"underscore"}],"proj4/lib/Point":[function(require,module,exports){
var mgrs = require('mgrs');

function Point(x, y, z) {
  if (!(this instanceof Point)) {
    return new Point(x, y, z);
  }
  if (Array.isArray(x)) {
    this.x = x[0];
    this.y = x[1];
    this.z = x[2] || 0.0;
  } else if(typeof x === 'object') {
    this.x = x.x;
    this.y = x.y;
    this.z = x.z || 0.0;
  } else if (typeof x === 'string' && typeof y === 'undefined') {
    var coords = x.split(',');
    this.x = parseFloat(coords[0], 10);
    this.y = parseFloat(coords[1], 10);
    this.z = parseFloat(coords[2], 10) || 0.0;
  } else {
    this.x = x;
    this.y = y;
    this.z = z || 0.0;
  }
  console.warn('proj4.Point will be removed in version 3, use proj4.toPoint');
}

Point.fromMGRS = function(mgrsStr) {
  return new Point(mgrs.toPoint(mgrsStr));
};
Point.prototype.toMGRS = function(accuracy) {
  return mgrs.forward([this.x, this.y], accuracy);
};
module.exports = Point;

},{"mgrs":"proj4/node_modules/mgrs/mgrs"}],"proj4/lib/Proj":[function(require,module,exports){
var parseCode = require("./parseCode");
var extend = require('./extend');
var projections = require('./projections');
var deriveConstants = require('./deriveConstants');

function Projection(srsCode,callback) {
  if (!(this instanceof Projection)) {
    return new Projection(srsCode);
  }
  callback = callback || function(error){
    if(error){
      throw error;
    }
  };
  var json = parseCode(srsCode);
  if(typeof json !== 'object'){
    callback(srsCode);
    return;
  }
  var modifiedJSON = deriveConstants(json);
  var ourProj = Projection.projections.get(modifiedJSON.projName);
  if(ourProj){
    extend(this, modifiedJSON);
    extend(this, ourProj);
    this.init();
    callback(null, this);
  }else{
    callback(srsCode);
  }
}
Projection.projections = projections;
Projection.projections.start();
module.exports = Projection;

},{"./deriveConstants":"proj4/lib/deriveConstants","./extend":"proj4/lib/extend","./parseCode":"proj4/lib/parseCode","./projections":"proj4/lib/projections"}],"proj4/lib/adjust_axis":[function(require,module,exports){
module.exports = function(crs, denorm, point) {
  var xin = point.x,
    yin = point.y,
    zin = point.z || 0.0;
  var v, t, i;
  for (i = 0; i < 3; i++) {
    if (denorm && i === 2 && point.z === undefined) {
      continue;
    }
    if (i === 0) {
      v = xin;
      t = 'x';
    }
    else if (i === 1) {
      v = yin;
      t = 'y';
    }
    else {
      v = zin;
      t = 'z';
    }
    switch (crs.axis[i]) {
    case 'e':
      point[t] = v;
      break;
    case 'w':
      point[t] = -v;
      break;
    case 'n':
      point[t] = v;
      break;
    case 's':
      point[t] = -v;
      break;
    case 'u':
      if (point[t] !== undefined) {
        point.z = v;
      }
      break;
    case 'd':
      if (point[t] !== undefined) {
        point.z = -v;
      }
      break;
    default:
      //console.log("ERROR: unknow axis ("+crs.axis[i]+") - check definition of "+crs.projName);
      return null;
    }
  }
  return point;
};

},{}],"proj4/lib/common/adjust_lat":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var sign = require('./sign');

module.exports = function(x) {
  return (Math.abs(x) < HALF_PI) ? x : (x - (sign(x) * Math.PI));
};
},{"./sign":"proj4/lib/common/sign"}],"proj4/lib/common/adjust_lon":[function(require,module,exports){
var TWO_PI = Math.PI * 2;
// SPI is slightly greater than Math.PI, so values that exceed the -180..180
// degree range by a tiny amount don't get wrapped. This prevents points that
// have drifted from their original location along the 180th meridian (due to
// floating point error) from changing their sign.
var SPI = 3.14159265359;
var sign = require('./sign');

module.exports = function(x) {
  return (Math.abs(x) <= SPI) ? x : (x - (sign(x) * TWO_PI));
};
},{"./sign":"proj4/lib/common/sign"}],"proj4/lib/common/asinz":[function(require,module,exports){
module.exports = function(x) {
  if (Math.abs(x) > 1) {
    x = (x > 1) ? 1 : -1;
  }
  return Math.asin(x);
};
},{}],"proj4/lib/common/e0fn":[function(require,module,exports){
module.exports = function(x) {
  return (1 - 0.25 * x * (1 + x / 16 * (3 + 1.25 * x)));
};
},{}],"proj4/lib/common/e1fn":[function(require,module,exports){
module.exports = function(x) {
  return (0.375 * x * (1 + 0.25 * x * (1 + 0.46875 * x)));
};
},{}],"proj4/lib/common/e2fn":[function(require,module,exports){
module.exports = function(x) {
  return (0.05859375 * x * x * (1 + 0.75 * x));
};
},{}],"proj4/lib/common/e3fn":[function(require,module,exports){
module.exports = function(x) {
  return (x * x * x * (35 / 3072));
};
},{}],"proj4/lib/common/gN":[function(require,module,exports){
module.exports = function(a, e, sinphi) {
  var temp = e * sinphi;
  return a / Math.sqrt(1 - temp * temp);
};
},{}],"proj4/lib/common/imlfn":[function(require,module,exports){
module.exports = function(ml, e0, e1, e2, e3) {
  var phi;
  var dphi;

  phi = ml / e0;
  for (var i = 0; i < 15; i++) {
    dphi = (ml - (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi))) / (e0 - 2 * e1 * Math.cos(2 * phi) + 4 * e2 * Math.cos(4 * phi) - 6 * e3 * Math.cos(6 * phi));
    phi += dphi;
    if (Math.abs(dphi) <= 0.0000000001) {
      return phi;
    }
  }

  //..reportError("IMLFN-CONV:Latitude failed to converge after 15 iterations");
  return NaN;
};
},{}],"proj4/lib/common/iqsfnz":[function(require,module,exports){
var HALF_PI = Math.PI/2;

module.exports = function(eccent, q) {
  var temp = 1 - (1 - eccent * eccent) / (2 * eccent) * Math.log((1 - eccent) / (1 + eccent));
  if (Math.abs(Math.abs(q) - temp) < 1.0E-6) {
    if (q < 0) {
      return (-1 * HALF_PI);
    }
    else {
      return HALF_PI;
    }
  }
  //var phi = 0.5* q/(1-eccent*eccent);
  var phi = Math.asin(0.5 * q);
  var dphi;
  var sin_phi;
  var cos_phi;
  var con;
  for (var i = 0; i < 30; i++) {
    sin_phi = Math.sin(phi);
    cos_phi = Math.cos(phi);
    con = eccent * sin_phi;
    dphi = Math.pow(1 - con * con, 2) / (2 * cos_phi) * (q / (1 - eccent * eccent) - sin_phi / (1 - con * con) + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
    phi += dphi;
    if (Math.abs(dphi) <= 0.0000000001) {
      return phi;
    }
  }

  //console.log("IQSFN-CONV:Latitude failed to converge after 30 iterations");
  return NaN;
};
},{}],"proj4/lib/common/mlfn":[function(require,module,exports){
module.exports = function(e0, e1, e2, e3, phi) {
  return (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi));
};
},{}],"proj4/lib/common/msfnz":[function(require,module,exports){
module.exports = function(eccent, sinphi, cosphi) {
  var con = eccent * sinphi;
  return cosphi / (Math.sqrt(1 - con * con));
};
},{}],"proj4/lib/common/phi2z":[function(require,module,exports){
var HALF_PI = Math.PI/2;
module.exports = function(eccent, ts) {
  var eccnth = 0.5 * eccent;
  var con, dphi;
  var phi = HALF_PI - 2 * Math.atan(ts);
  for (var i = 0; i <= 15; i++) {
    con = eccent * Math.sin(phi);
    dphi = HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi;
    phi += dphi;
    if (Math.abs(dphi) <= 0.0000000001) {
      return phi;
    }
  }
  //console.log("phi2z has NoConvergence");
  return -9999;
};
},{}],"proj4/lib/common/pj_enfn":[function(require,module,exports){
var C00 = 1;
var C02 = 0.25;
var C04 = 0.046875;
var C06 = 0.01953125;
var C08 = 0.01068115234375;
var C22 = 0.75;
var C44 = 0.46875;
var C46 = 0.01302083333333333333;
var C48 = 0.00712076822916666666;
var C66 = 0.36458333333333333333;
var C68 = 0.00569661458333333333;
var C88 = 0.3076171875;

module.exports = function(es) {
  var en = [];
  en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
  en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
  var t = es * es;
  en[2] = t * (C44 - es * (C46 + es * C48));
  t *= es;
  en[3] = t * (C66 - es * C68);
  en[4] = t * es * C88;
  return en;
};
},{}],"proj4/lib/common/pj_inv_mlfn":[function(require,module,exports){
var pj_mlfn = require("./pj_mlfn");
var EPSLN = 1.0e-10;
var MAX_ITER = 20;
module.exports = function(arg, es, en) {
  var k = 1 / (1 - es);
  var phi = arg;
  for (var i = MAX_ITER; i; --i) { /* rarely goes over 2 iterations */
    var s = Math.sin(phi);
    var t = 1 - es * s * s;
    //t = this.pj_mlfn(phi, s, Math.cos(phi), en) - arg;
    //phi -= t * (t * Math.sqrt(t)) * k;
    t = (pj_mlfn(phi, s, Math.cos(phi), en) - arg) * (t * Math.sqrt(t)) * k;
    phi -= t;
    if (Math.abs(t) < EPSLN) {
      return phi;
    }
  }
  //..reportError("cass:pj_inv_mlfn: Convergence error");
  return phi;
};
},{"./pj_mlfn":"proj4/lib/common/pj_mlfn"}],"proj4/lib/common/pj_mlfn":[function(require,module,exports){
module.exports = function(phi, sphi, cphi, en) {
  cphi *= sphi;
  sphi *= sphi;
  return (en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4]))));
};
},{}],"proj4/lib/common/qsfnz":[function(require,module,exports){
module.exports = function(eccent, sinphi) {
  var con;
  if (eccent > 1.0e-7) {
    con = eccent * sinphi;
    return ((1 - eccent * eccent) * (sinphi / (1 - con * con) - (0.5 / eccent) * Math.log((1 - con) / (1 + con))));
  }
  else {
    return (2 * sinphi);
  }
};
},{}],"proj4/lib/common/sign":[function(require,module,exports){
module.exports = function(x) {
  return x<0 ? -1 : 1;
};
},{}],"proj4/lib/common/srat":[function(require,module,exports){
module.exports = function(esinp, exp) {
  return (Math.pow((1 - esinp) / (1 + esinp), exp));
};
},{}],"proj4/lib/common/toPoint":[function(require,module,exports){
module.exports = function (array){
  var out = {
    x: array[0],
    y: array[1]
  };
  if (array.length>2) {
    out.z = array[2];
  }
  if (array.length>3) {
    out.m = array[3];
  }
  return out;
};
},{}],"proj4/lib/common/tsfnz":[function(require,module,exports){
var HALF_PI = Math.PI/2;

module.exports = function(eccent, phi, sinphi) {
  var con = eccent * sinphi;
  var com = 0.5 * eccent;
  con = Math.pow(((1 - con) / (1 + con)), com);
  return (Math.tan(0.5 * (HALF_PI - phi)) / con);
};
},{}],"proj4/lib/constants/Datum":[function(require,module,exports){
exports.wgs84 = {
  towgs84: "0,0,0",
  ellipse: "WGS84",
  datumName: "WGS84"
};
exports.ch1903 = {
  towgs84: "674.374,15.056,405.346",
  ellipse: "bessel",
  datumName: "swiss"
};
exports.ggrs87 = {
  towgs84: "-199.87,74.79,246.62",
  ellipse: "GRS80",
  datumName: "Greek_Geodetic_Reference_System_1987"
};
exports.nad83 = {
  towgs84: "0,0,0",
  ellipse: "GRS80",
  datumName: "North_American_Datum_1983"
};
exports.nad27 = {
  nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
  ellipse: "clrk66",
  datumName: "North_American_Datum_1927"
};
exports.potsdam = {
  towgs84: "606.0,23.0,413.0",
  ellipse: "bessel",
  datumName: "Potsdam Rauenberg 1950 DHDN"
};
exports.carthage = {
  towgs84: "-263.0,6.0,431.0",
  ellipse: "clark80",
  datumName: "Carthage 1934 Tunisia"
};
exports.hermannskogel = {
  towgs84: "653.0,-212.0,449.0",
  ellipse: "bessel",
  datumName: "Hermannskogel"
};
exports.ire65 = {
  towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
  ellipse: "mod_airy",
  datumName: "Ireland 1965"
};
exports.rassadiran = {
  towgs84: "-133.63,-157.5,-158.62",
  ellipse: "intl",
  datumName: "Rassadiran"
};
exports.nzgd49 = {
  towgs84: "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",
  ellipse: "intl",
  datumName: "New Zealand Geodetic Datum 1949"
};
exports.osgb36 = {
  towgs84: "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",
  ellipse: "airy",
  datumName: "Airy 1830"
};
exports.s_jtsk = {
  towgs84: "589,76,480",
  ellipse: 'bessel',
  datumName: 'S-JTSK (Ferro)'
};
exports.beduaram = {
  towgs84: '-106,-87,188',
  ellipse: 'clrk80',
  datumName: 'Beduaram'
};
exports.gunung_segara = {
  towgs84: '-403,684,41',
  ellipse: 'bessel',
  datumName: 'Gunung Segara Jakarta'
};
exports.rnb72 = {
  towgs84: "106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1",
  ellipse: "intl",
  datumName: "Reseau National Belge 1972"
};
},{}],"proj4/lib/constants/Ellipsoid":[function(require,module,exports){
exports.MERIT = {
  a: 6378137.0,
  rf: 298.257,
  ellipseName: "MERIT 1983"
};
exports.SGS85 = {
  a: 6378136.0,
  rf: 298.257,
  ellipseName: "Soviet Geodetic System 85"
};
exports.GRS80 = {
  a: 6378137.0,
  rf: 298.257222101,
  ellipseName: "GRS 1980(IUGG, 1980)"
};
exports.IAU76 = {
  a: 6378140.0,
  rf: 298.257,
  ellipseName: "IAU 1976"
};
exports.airy = {
  a: 6377563.396,
  b: 6356256.910,
  ellipseName: "Airy 1830"
};
exports.APL4 = {
  a: 6378137,
  rf: 298.25,
  ellipseName: "Appl. Physics. 1965"
};
exports.NWL9D = {
  a: 6378145.0,
  rf: 298.25,
  ellipseName: "Naval Weapons Lab., 1965"
};
exports.mod_airy = {
  a: 6377340.189,
  b: 6356034.446,
  ellipseName: "Modified Airy"
};
exports.andrae = {
  a: 6377104.43,
  rf: 300.0,
  ellipseName: "Andrae 1876 (Den., Iclnd.)"
};
exports.aust_SA = {
  a: 6378160.0,
  rf: 298.25,
  ellipseName: "Australian Natl & S. Amer. 1969"
};
exports.GRS67 = {
  a: 6378160.0,
  rf: 298.2471674270,
  ellipseName: "GRS 67(IUGG 1967)"
};
exports.bessel = {
  a: 6377397.155,
  rf: 299.1528128,
  ellipseName: "Bessel 1841"
};
exports.bess_nam = {
  a: 6377483.865,
  rf: 299.1528128,
  ellipseName: "Bessel 1841 (Namibia)"
};
exports.clrk66 = {
  a: 6378206.4,
  b: 6356583.8,
  ellipseName: "Clarke 1866"
};
exports.clrk80 = {
  a: 6378249.145,
  rf: 293.4663,
  ellipseName: "Clarke 1880 mod."
};
exports.clrk58 = {
  a: 6378293.645208759,
  rf: 294.2606763692654,
  ellipseName: "Clarke 1858"
};
exports.CPM = {
  a: 6375738.7,
  rf: 334.29,
  ellipseName: "Comm. des Poids et Mesures 1799"
};
exports.delmbr = {
  a: 6376428.0,
  rf: 311.5,
  ellipseName: "Delambre 1810 (Belgium)"
};
exports.engelis = {
  a: 6378136.05,
  rf: 298.2566,
  ellipseName: "Engelis 1985"
};
exports.evrst30 = {
  a: 6377276.345,
  rf: 300.8017,
  ellipseName: "Everest 1830"
};
exports.evrst48 = {
  a: 6377304.063,
  rf: 300.8017,
  ellipseName: "Everest 1948"
};
exports.evrst56 = {
  a: 6377301.243,
  rf: 300.8017,
  ellipseName: "Everest 1956"
};
exports.evrst69 = {
  a: 6377295.664,
  rf: 300.8017,
  ellipseName: "Everest 1969"
};
exports.evrstSS = {
  a: 6377298.556,
  rf: 300.8017,
  ellipseName: "Everest (Sabah & Sarawak)"
};
exports.fschr60 = {
  a: 6378166.0,
  rf: 298.3,
  ellipseName: "Fischer (Mercury Datum) 1960"
};
exports.fschr60m = {
  a: 6378155.0,
  rf: 298.3,
  ellipseName: "Fischer 1960"
};
exports.fschr68 = {
  a: 6378150.0,
  rf: 298.3,
  ellipseName: "Fischer 1968"
};
exports.helmert = {
  a: 6378200.0,
  rf: 298.3,
  ellipseName: "Helmert 1906"
};
exports.hough = {
  a: 6378270.0,
  rf: 297.0,
  ellipseName: "Hough"
};
exports.intl = {
  a: 6378388.0,
  rf: 297.0,
  ellipseName: "International 1909 (Hayford)"
};
exports.kaula = {
  a: 6378163.0,
  rf: 298.24,
  ellipseName: "Kaula 1961"
};
exports.lerch = {
  a: 6378139.0,
  rf: 298.257,
  ellipseName: "Lerch 1979"
};
exports.mprts = {
  a: 6397300.0,
  rf: 191.0,
  ellipseName: "Maupertius 1738"
};
exports.new_intl = {
  a: 6378157.5,
  b: 6356772.2,
  ellipseName: "New International 1967"
};
exports.plessis = {
  a: 6376523.0,
  rf: 6355863.0,
  ellipseName: "Plessis 1817 (France)"
};
exports.krass = {
  a: 6378245.0,
  rf: 298.3,
  ellipseName: "Krassovsky, 1942"
};
exports.SEasia = {
  a: 6378155.0,
  b: 6356773.3205,
  ellipseName: "Southeast Asia"
};
exports.walbeck = {
  a: 6376896.0,
  b: 6355834.8467,
  ellipseName: "Walbeck"
};
exports.WGS60 = {
  a: 6378165.0,
  rf: 298.3,
  ellipseName: "WGS 60"
};
exports.WGS66 = {
  a: 6378145.0,
  rf: 298.25,
  ellipseName: "WGS 66"
};
exports.WGS7 = {
  a: 6378135.0,
  rf: 298.26,
  ellipseName: "WGS 72"
};
exports.WGS84 = {
  a: 6378137.0,
  rf: 298.257223563,
  ellipseName: "WGS 84"
};
exports.sphere = {
  a: 6370997.0,
  b: 6370997.0,
  ellipseName: "Normal Sphere (r=6370997)"
};
},{}],"proj4/lib/constants/PrimeMeridian":[function(require,module,exports){
exports.greenwich = 0.0; //"0dE",
exports.lisbon = -9.131906111111; //"9d07'54.862\"W",
exports.paris = 2.337229166667; //"2d20'14.025\"E",
exports.bogota = -74.080916666667; //"74d04'51.3\"W",
exports.madrid = -3.687938888889; //"3d41'16.58\"W",
exports.rome = 12.452333333333; //"12d27'8.4\"E",
exports.bern = 7.439583333333; //"7d26'22.5\"E",
exports.jakarta = 106.807719444444; //"106d48'27.79\"E",
exports.ferro = -17.666666666667; //"17d40'W",
exports.brussels = 4.367975; //"4d22'4.71\"E",
exports.stockholm = 18.058277777778; //"18d3'29.8\"E",
exports.athens = 23.7163375; //"23d42'58.815\"E",
exports.oslo = 10.722916666667; //"10d43'22.5\"E"
},{}],"proj4/lib/constants/units":[function(require,module,exports){
exports.ft = {to_meter: 0.3048};
exports['us-ft'] = {to_meter: 1200 / 3937};

},{}],"proj4/lib/core":[function(require,module,exports){
var proj = require('./Proj');
var transform = require('./transform');
var wgs84 = proj('WGS84');

function transformer(from, to, coords) {
  var transformedArray;
  if (Array.isArray(coords)) {
    transformedArray = transform(from, to, coords);
    if (coords.length === 3) {
      return [transformedArray.x, transformedArray.y, transformedArray.z];
    }
    else {
      return [transformedArray.x, transformedArray.y];
    }
  }
  else {
    return transform(from, to, coords);
  }
}

function checkProj(item) {
  if (item instanceof proj) {
    return item;
  }
  if (item.oProj) {
    return item.oProj;
  }
  return proj(item);
}
function proj4(fromProj, toProj, coord) {
  fromProj = checkProj(fromProj);
  var single = false;
  var obj;
  if (typeof toProj === 'undefined') {
    toProj = fromProj;
    fromProj = wgs84;
    single = true;
  }
  else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
    coord = toProj;
    toProj = fromProj;
    fromProj = wgs84;
    single = true;
  }
  toProj = checkProj(toProj);
  if (coord) {
    return transformer(fromProj, toProj, coord);
  }
  else {
    obj = {
      forward: function(coords) {
        return transformer(fromProj, toProj, coords);
      },
      inverse: function(coords) {
        return transformer(toProj, fromProj, coords);
      }
    };
    if (single) {
      obj.oProj = toProj;
    }
    return obj;
  }
}
module.exports = proj4;
},{"./Proj":"proj4/lib/Proj","./transform":"proj4/lib/transform"}],"proj4/lib/datum":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_WGS84 = 4; // WGS84 or equivalent
var PJD_NODATUM = 5; // WGS84 or equivalent
var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
var AD_C = 1.0026000;
var COS_67P5 = 0.38268343236508977;
var datum = function(proj) {
  if (!(this instanceof datum)) {
    return new datum(proj);
  }
  this.datum_type = PJD_WGS84; //default setting
  if (!proj) {
    return;
  }
  if (proj.datumCode && proj.datumCode === 'none') {
    this.datum_type = PJD_NODATUM;
  }

  if (proj.datum_params) {
    this.datum_params = proj.datum_params.map(parseFloat);
    if (this.datum_params[0] !== 0 || this.datum_params[1] !== 0 || this.datum_params[2] !== 0) {
      this.datum_type = PJD_3PARAM;
    }
    if (this.datum_params.length > 3) {
      if (this.datum_params[3] !== 0 || this.datum_params[4] !== 0 || this.datum_params[5] !== 0 || this.datum_params[6] !== 0) {
        this.datum_type = PJD_7PARAM;
        this.datum_params[3] *= SEC_TO_RAD;
        this.datum_params[4] *= SEC_TO_RAD;
        this.datum_params[5] *= SEC_TO_RAD;
        this.datum_params[6] = (this.datum_params[6] / 1000000.0) + 1.0;
      }
    }
  }

  // DGR 2011-03-21 : nadgrids support
  this.datum_type = proj.grids ? PJD_GRIDSHIFT : this.datum_type;

  this.a = proj.a; //datum object also uses these values
  this.b = proj.b;
  this.es = proj.es;
  this.ep2 = proj.ep2;
  if (this.datum_type === PJD_GRIDSHIFT) {
    this.grids = proj.grids;
  }
};
datum.prototype = {


  /****************************************************************/
  // cs_compare_datums()
  //   Returns TRUE if the two datums match, otherwise FALSE.
  compare_datums: function(dest) {
    if (this.datum_type !== dest.datum_type) {
      return false; // false, datums are not equal
    }
    else if (this.a !== dest.a || Math.abs(this.es - dest.es) > 0.000000000050) {
      // the tolerence for es is to ensure that GRS80 and WGS84
      // are considered identical
      return false;
    }
    else if (this.datum_type === PJD_3PARAM) {
      return (this.datum_params[0] === dest.datum_params[0] && this.datum_params[1] === dest.datum_params[1] && this.datum_params[2] === dest.datum_params[2]);
    }
    else if (this.datum_type === PJD_7PARAM) {
      return (this.datum_params[0] === dest.datum_params[0] && this.datum_params[1] === dest.datum_params[1] && this.datum_params[2] === dest.datum_params[2] && this.datum_params[3] === dest.datum_params[3] && this.datum_params[4] === dest.datum_params[4] && this.datum_params[5] === dest.datum_params[5] && this.datum_params[6] === dest.datum_params[6]);
    }
    else if (this.datum_type === PJD_GRIDSHIFT || dest.datum_type === PJD_GRIDSHIFT) {
      //alert("ERROR: Grid shift transformations are not implemented.");
      //return false
      //DGR 2012-07-29 lazy ...
      return this.nadgrids === dest.nadgrids;
    }
    else {
      return true; // datums are equal
    }
  }, // cs_compare_datums()

  /*
   * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
   * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
   * according to the current ellipsoid parameters.
   *
   *    Latitude  : Geodetic latitude in radians                     (input)
   *    Longitude : Geodetic longitude in radians                    (input)
   *    Height    : Geodetic height, in meters                       (input)
   *    X         : Calculated Geocentric X coordinate, in meters    (output)
   *    Y         : Calculated Geocentric Y coordinate, in meters    (output)
   *    Z         : Calculated Geocentric Z coordinate, in meters    (output)
   *
   */
  geodetic_to_geocentric: function(p) {
    var Longitude = p.x;
    var Latitude = p.y;
    var Height = p.z ? p.z : 0; //Z value not always supplied
    var X; // output
    var Y;
    var Z;

    var Error_Code = 0; //  GEOCENT_NO_ERROR;
    var Rn; /*  Earth radius at location  */
    var Sin_Lat; /*  Math.sin(Latitude)  */
    var Sin2_Lat; /*  Square of Math.sin(Latitude)  */
    var Cos_Lat; /*  Math.cos(Latitude)  */

    /*
     ** Don't blow up if Latitude is just a little out of the value
     ** range as it may just be a rounding issue.  Also removed longitude
     ** test, it should be wrapped by Math.cos() and Math.sin().  NFW for PROJ.4, Sep/2001.
     */
    if (Latitude < -HALF_PI && Latitude > -1.001 * HALF_PI) {
      Latitude = -HALF_PI;
    }
    else if (Latitude > HALF_PI && Latitude < 1.001 * HALF_PI) {
      Latitude = HALF_PI;
    }
    else if ((Latitude < -HALF_PI) || (Latitude > HALF_PI)) {
      /* Latitude out of range */
      //..reportError('geocent:lat out of range:' + Latitude);
      return null;
    }

    if (Longitude > Math.PI) {
      Longitude -= (2 * Math.PI);
    }
    Sin_Lat = Math.sin(Latitude);
    Cos_Lat = Math.cos(Latitude);
    Sin2_Lat = Sin_Lat * Sin_Lat;
    Rn = this.a / (Math.sqrt(1.0e0 - this.es * Sin2_Lat));
    X = (Rn + Height) * Cos_Lat * Math.cos(Longitude);
    Y = (Rn + Height) * Cos_Lat * Math.sin(Longitude);
    Z = ((Rn * (1 - this.es)) + Height) * Sin_Lat;

    p.x = X;
    p.y = Y;
    p.z = Z;
    return Error_Code;
  }, // cs_geodetic_to_geocentric()


  geocentric_to_geodetic: function(p) {
    /* local defintions and variables */
    /* end-criterium of loop, accuracy of sin(Latitude) */
    var genau = 1e-12;
    var genau2 = (genau * genau);
    var maxiter = 30;

    var P; /* distance between semi-minor axis and location */
    var RR; /* distance between center and location */
    var CT; /* sin of geocentric latitude */
    var ST; /* cos of geocentric latitude */
    var RX;
    var RK;
    var RN; /* Earth radius at location */
    var CPHI0; /* cos of start or old geodetic latitude in iterations */
    var SPHI0; /* sin of start or old geodetic latitude in iterations */
    var CPHI; /* cos of searched geodetic latitude */
    var SPHI; /* sin of searched geodetic latitude */
    var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
    var At_Pole; /* indicates location is in polar region */
    var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */

    var X = p.x;
    var Y = p.y;
    var Z = p.z ? p.z : 0.0; //Z value not always supplied
    var Longitude;
    var Latitude;
    var Height;

    At_Pole = false;
    P = Math.sqrt(X * X + Y * Y);
    RR = Math.sqrt(X * X + Y * Y + Z * Z);

    /*      special cases for latitude and longitude */
    if (P / this.a < genau) {

      /*  special case, if P=0. (X=0., Y=0.) */
      At_Pole = true;
      Longitude = 0.0;

      /*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
       *  of ellipsoid (=center of mass), Latitude becomes PI/2 */
      if (RR / this.a < genau) {
        Latitude = HALF_PI;
        Height = -this.b;
        return;
      }
    }
    else {
      /*  ellipsoidal (geodetic) longitude
       *  interval: -PI < Longitude <= +PI */
      Longitude = Math.atan2(Y, X);
    }

    /* --------------------------------------------------------------
     * Following iterative algorithm was developped by
     * "Institut for Erdmessung", University of Hannover, July 1988.
     * Internet: www.ife.uni-hannover.de
     * Iterative computation of CPHI,SPHI and Height.
     * Iteration of CPHI and SPHI to 10**-12 radian resp.
     * 2*10**-7 arcsec.
     * --------------------------------------------------------------
     */
    CT = Z / RR;
    ST = P / RR;
    RX = 1.0 / Math.sqrt(1.0 - this.es * (2.0 - this.es) * ST * ST);
    CPHI0 = ST * (1.0 - this.es) * RX;
    SPHI0 = CT * RX;
    iter = 0;

    /* loop to find sin(Latitude) resp. Latitude
     * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
    do {
      iter++;
      RN = this.a / Math.sqrt(1.0 - this.es * SPHI0 * SPHI0);

      /*  ellipsoidal (geodetic) height */
      Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - this.es * SPHI0 * SPHI0);

      RK = this.es * RN / (RN + Height);
      RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST);
      CPHI = ST * (1.0 - RK) * RX;
      SPHI = CT * RX;
      SDPHI = SPHI * CPHI0 - CPHI * SPHI0;
      CPHI0 = CPHI;
      SPHI0 = SPHI;
    }
    while (SDPHI * SDPHI > genau2 && iter < maxiter);

    /*      ellipsoidal (geodetic) latitude */
    Latitude = Math.atan(SPHI / Math.abs(CPHI));

    p.x = Longitude;
    p.y = Latitude;
    p.z = Height;
    return p;
  }, // cs_geocentric_to_geodetic()

  /** Convert_Geocentric_To_Geodetic
   * The method used here is derived from 'An Improved Algorithm for
   * Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996
   */
  geocentric_to_geodetic_noniter: function(p) {
    var X = p.x;
    var Y = p.y;
    var Z = p.z ? p.z : 0; //Z value not always supplied
    var Longitude;
    var Latitude;
    var Height;

    var W; /* distance from Z axis */
    var W2; /* square of distance from Z axis */
    var T0; /* initial estimate of vertical component */
    var T1; /* corrected estimate of vertical component */
    var S0; /* initial estimate of horizontal component */
    var S1; /* corrected estimate of horizontal component */
    var Sin_B0; /* Math.sin(B0), B0 is estimate of Bowring aux variable */
    var Sin3_B0; /* cube of Math.sin(B0) */
    var Cos_B0; /* Math.cos(B0) */
    var Sin_p1; /* Math.sin(phi1), phi1 is estimated latitude */
    var Cos_p1; /* Math.cos(phi1) */
    var Rn; /* Earth radius at location */
    var Sum; /* numerator of Math.cos(phi1) */
    var At_Pole; /* indicates location is in polar region */

    X = parseFloat(X); // cast from string to float
    Y = parseFloat(Y);
    Z = parseFloat(Z);

    At_Pole = false;
    if (X !== 0.0) {
      Longitude = Math.atan2(Y, X);
    }
    else {
      if (Y > 0) {
        Longitude = HALF_PI;
      }
      else if (Y < 0) {
        Longitude = -HALF_PI;
      }
      else {
        At_Pole = true;
        Longitude = 0.0;
        if (Z > 0.0) { /* north pole */
          Latitude = HALF_PI;
        }
        else if (Z < 0.0) { /* south pole */
          Latitude = -HALF_PI;
        }
        else { /* center of earth */
          Latitude = HALF_PI;
          Height = -this.b;
          return;
        }
      }
    }
    W2 = X * X + Y * Y;
    W = Math.sqrt(W2);
    T0 = Z * AD_C;
    S0 = Math.sqrt(T0 * T0 + W2);
    Sin_B0 = T0 / S0;
    Cos_B0 = W / S0;
    Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;
    T1 = Z + this.b * this.ep2 * Sin3_B0;
    Sum = W - this.a * this.es * Cos_B0 * Cos_B0 * Cos_B0;
    S1 = Math.sqrt(T1 * T1 + Sum * Sum);
    Sin_p1 = T1 / S1;
    Cos_p1 = Sum / S1;
    Rn = this.a / Math.sqrt(1.0 - this.es * Sin_p1 * Sin_p1);
    if (Cos_p1 >= COS_67P5) {
      Height = W / Cos_p1 - Rn;
    }
    else if (Cos_p1 <= -COS_67P5) {
      Height = W / -Cos_p1 - Rn;
    }
    else {
      Height = Z / Sin_p1 + Rn * (this.es - 1.0);
    }
    if (At_Pole === false) {
      Latitude = Math.atan(Sin_p1 / Cos_p1);
    }

    p.x = Longitude;
    p.y = Latitude;
    p.z = Height;
    return p;
  }, // geocentric_to_geodetic_noniter()

  /****************************************************************/
  // pj_geocentic_to_wgs84( p )
  //  p = point to transform in geocentric coordinates (x,y,z)
  geocentric_to_wgs84: function(p) {

    if (this.datum_type === PJD_3PARAM) {
      // if( x[io] === HUGE_VAL )
      //    continue;
      p.x += this.datum_params[0];
      p.y += this.datum_params[1];
      p.z += this.datum_params[2];

    }
    else if (this.datum_type === PJD_7PARAM) {
      var Dx_BF = this.datum_params[0];
      var Dy_BF = this.datum_params[1];
      var Dz_BF = this.datum_params[2];
      var Rx_BF = this.datum_params[3];
      var Ry_BF = this.datum_params[4];
      var Rz_BF = this.datum_params[5];
      var M_BF = this.datum_params[6];
      // if( x[io] === HUGE_VAL )
      //    continue;
      var x_out = M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF;
      var y_out = M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF;
      var z_out = M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF;
      p.x = x_out;
      p.y = y_out;
      p.z = z_out;
    }
  }, // cs_geocentric_to_wgs84

  /****************************************************************/
  // pj_geocentic_from_wgs84()
  //  coordinate system definition,
  //  point to transform in geocentric coordinates (x,y,z)
  geocentric_from_wgs84: function(p) {

    if (this.datum_type === PJD_3PARAM) {
      //if( x[io] === HUGE_VAL )
      //    continue;
      p.x -= this.datum_params[0];
      p.y -= this.datum_params[1];
      p.z -= this.datum_params[2];

    }
    else if (this.datum_type === PJD_7PARAM) {
      var Dx_BF = this.datum_params[0];
      var Dy_BF = this.datum_params[1];
      var Dz_BF = this.datum_params[2];
      var Rx_BF = this.datum_params[3];
      var Ry_BF = this.datum_params[4];
      var Rz_BF = this.datum_params[5];
      var M_BF = this.datum_params[6];
      var x_tmp = (p.x - Dx_BF) / M_BF;
      var y_tmp = (p.y - Dy_BF) / M_BF;
      var z_tmp = (p.z - Dz_BF) / M_BF;
      //if( x[io] === HUGE_VAL )
      //    continue;

      p.x = x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp;
      p.y = -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp;
      p.z = Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp;
    } //cs_geocentric_from_wgs84()
  }
};

/** point object, nothing fancy, just allows values to be
    passed back and forth by reference rather than by value.
    Other point classes may be used as long as they have
    x and y properties, which will get modified in the transform method.
*/
module.exports = datum;

},{}],"proj4/lib/datum_transform":[function(require,module,exports){
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var PJD_GRIDSHIFT = 3;
var PJD_NODATUM = 5; // WGS84 or equivalent
var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
module.exports = function(source, dest, point) {
  var wp, i, l;

  function checkParams(fallback) {
    return (fallback === PJD_3PARAM || fallback === PJD_7PARAM);
  }
  // Short cut if the datums are identical.
  if (source.compare_datums(dest)) {
    return point; // in this case, zero is sucess,
    // whereas cs_compare_datums returns 1 to indicate TRUE
    // confusing, should fix this
  }

  // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
  if (source.datum_type === PJD_NODATUM || dest.datum_type === PJD_NODATUM) {
    return point;
  }

  //DGR: 2012-07-29 : add nadgrids support (begin)
  var src_a = source.a;
  var src_es = source.es;

  var dst_a = dest.a;
  var dst_es = dest.es;

  var fallback = source.datum_type;
  // If this datum requires grid shifts, then apply it to geodetic coordinates.
  if (fallback === PJD_GRIDSHIFT) {
    if (this.apply_gridshift(source, 0, point) === 0) {
      source.a = SRS_WGS84_SEMIMAJOR;
      source.es = SRS_WGS84_ESQUARED;
    }
    else {
      // try 3 or 7 params transformation or nothing ?
      if (!source.datum_params) {
        source.a = src_a;
        source.es = source.es;
        return point;
      }
      wp = 1;
      for (i = 0, l = source.datum_params.length; i < l; i++) {
        wp *= source.datum_params[i];
      }
      if (wp === 0) {
        source.a = src_a;
        source.es = source.es;
        return point;
      }
      if (source.datum_params.length > 3) {
        fallback = PJD_7PARAM;
      }
      else {
        fallback = PJD_3PARAM;
      }
    }
  }
  if (dest.datum_type === PJD_GRIDSHIFT) {
    dest.a = SRS_WGS84_SEMIMAJOR;
    dest.es = SRS_WGS84_ESQUARED;
  }
  // Do we need to go through geocentric coordinates?
  if (source.es !== dest.es || source.a !== dest.a || checkParams(fallback) || checkParams(dest.datum_type)) {
    //DGR: 2012-07-29 : add nadgrids support (end)
    // Convert to geocentric coordinates.
    source.geodetic_to_geocentric(point);
    // CHECK_RETURN;
    // Convert between datums
    if (checkParams(source.datum_type)) {
      source.geocentric_to_wgs84(point);
      // CHECK_RETURN;
    }
    if (checkParams(dest.datum_type)) {
      dest.geocentric_from_wgs84(point);
      // CHECK_RETURN;
    }
    // Convert back to geodetic coordinates
    dest.geocentric_to_geodetic(point);
    // CHECK_RETURN;
  }
  // Apply grid shift to destination if required
  if (dest.datum_type === PJD_GRIDSHIFT) {
    this.apply_gridshift(dest, 1, point);
    // CHECK_RETURN;
  }

  source.a = src_a;
  source.es = src_es;
  dest.a = dst_a;
  dest.es = dst_es;

  return point;
};


},{}],"proj4/lib/defs":[function(require,module,exports){
var globals = require('./global');
var parseProj = require('./projString');
var wkt = require('./wkt');

function defs(name) {
  /*global console*/
  var that = this;
  if (arguments.length === 2) {
    var def = arguments[1];
    if (typeof def === 'string') {
      if (def.charAt(0) === '+') {
        defs[name] = parseProj(arguments[1]);
      }
      else {
        defs[name] = wkt(arguments[1]);
      }
    } else {
      defs[name] = def;
    }
  }
  else if (arguments.length === 1) {
    if (Array.isArray(name)) {
      return name.map(function(v) {
        if (Array.isArray(v)) {
          defs.apply(that, v);
        }
        else {
          defs(v);
        }
      });
    }
    else if (typeof name === 'string') {
      if (name in defs) {
        return defs[name];
      }
    }
    else if ('EPSG' in name) {
      defs['EPSG:' + name.EPSG] = name;
    }
    else if ('ESRI' in name) {
      defs['ESRI:' + name.ESRI] = name;
    }
    else if ('IAU2000' in name) {
      defs['IAU2000:' + name.IAU2000] = name;
    }
    else {
      console.log(name);
    }
    return;
  }


}
globals(defs);
module.exports = defs;

},{"./global":"proj4/lib/global","./projString":"proj4/lib/projString","./wkt":"proj4/lib/wkt"}],"proj4/lib/deriveConstants":[function(require,module,exports){
var Datum = require('./constants/Datum');
var Ellipsoid = require('./constants/Ellipsoid');
var extend = require('./extend');
var datum = require('./datum');
var EPSLN = 1.0e-10;
// ellipoid pj_set_ell.c
var SIXTH = 0.1666666666666666667;
/* 1/6 */
var RA4 = 0.04722222222222222222;
/* 17/360 */
var RA6 = 0.02215608465608465608;
module.exports = function(json) {
  // DGR 2011-03-20 : nagrids -> nadgrids
  if (json.datumCode && json.datumCode !== 'none') {
    var datumDef = Datum[json.datumCode];
    if (datumDef) {
      json.datum_params = datumDef.towgs84 ? datumDef.towgs84.split(',') : null;
      json.ellps = datumDef.ellipse;
      json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
    }
  }
  if (!json.a) { // do we have an ellipsoid?
    var ellipse = Ellipsoid[json.ellps] ? Ellipsoid[json.ellps] : Ellipsoid.WGS84;
    extend(json, ellipse);
  }
  if (json.rf && !json.b) {
    json.b = (1.0 - 1.0 / json.rf) * json.a;
  }
  if (json.rf === 0 || Math.abs(json.a - json.b) < EPSLN) {
    json.sphere = true;
    json.b = json.a;
  }
  json.a2 = json.a * json.a; // used in geocentric
  json.b2 = json.b * json.b; // used in geocentric
  json.es = (json.a2 - json.b2) / json.a2; // e ^ 2
  json.e = Math.sqrt(json.es); // eccentricity
  if (json.R_A) {
    json.a *= 1 - json.es * (SIXTH + json.es * (RA4 + json.es * RA6));
    json.a2 = json.a * json.a;
    json.b2 = json.b * json.b;
    json.es = 0;
  }
  json.ep2 = (json.a2 - json.b2) / json.b2; // used in geocentric
  if (!json.k0) {
    json.k0 = 1.0; //default value
  }
  //DGR 2010-11-12: axis
  if (!json.axis) {
    json.axis = "enu";
  }

  if (!json.datum) {
    json.datum = datum(json);
  }
  return json;
};

},{"./constants/Datum":"proj4/lib/constants/Datum","./constants/Ellipsoid":"proj4/lib/constants/Ellipsoid","./datum":"proj4/lib/datum","./extend":"proj4/lib/extend"}],"proj4/lib/extend":[function(require,module,exports){
module.exports = function(destination, source) {
  destination = destination || {};
  var value, property;
  if (!source) {
    return destination;
  }
  for (property in source) {
    value = source[property];
    if (value !== undefined) {
      destination[property] = value;
    }
  }
  return destination;
};

},{}],"proj4/lib/global":[function(require,module,exports){
module.exports = function(defs) {
  defs('EPSG:4326', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees");
  defs('EPSG:4269', "+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees");
  defs('EPSG:3857', "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");

  defs.WGS84 = defs['EPSG:4326'];
  defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857
  defs.GOOGLE = defs['EPSG:3857'];
  defs['EPSG:900913'] = defs['EPSG:3857'];
  defs['EPSG:102113'] = defs['EPSG:3857'];
};

},{}],"proj4/lib/includedProjections":[function(require,module,exports){
var projs = [
  require('./projections/tmerc'),
  require('./projections/utm'),
  require('./projections/sterea'),
  require('./projections/stere'),
  require('./projections/somerc'),
  require('./projections/omerc'),
  require('./projections/lcc'),
  require('./projections/krovak'),
  require('./projections/cass'),
  require('./projections/laea'),
  require('./projections/aea'),
  require('./projections/gnom'),
  require('./projections/cea'),
  require('./projections/eqc'),
  require('./projections/poly'),
  require('./projections/nzmg'),
  require('./projections/mill'),
  require('./projections/sinu'),
  require('./projections/moll'),
  require('./projections/eqdc'),
  require('./projections/vandg'),
  require('./projections/aeqd')
];
module.exports = function(proj4){
  projs.forEach(function(proj){
    proj4.Proj.projections.add(proj);
  });
};
},{"./projections/aea":"proj4/lib/projections/aea","./projections/aeqd":"proj4/lib/projections/aeqd","./projections/cass":"proj4/lib/projections/cass","./projections/cea":"proj4/lib/projections/cea","./projections/eqc":"proj4/lib/projections/eqc","./projections/eqdc":"proj4/lib/projections/eqdc","./projections/gnom":"proj4/lib/projections/gnom","./projections/krovak":"proj4/lib/projections/krovak","./projections/laea":"proj4/lib/projections/laea","./projections/lcc":"proj4/lib/projections/lcc","./projections/mill":"proj4/lib/projections/mill","./projections/moll":"proj4/lib/projections/moll","./projections/nzmg":"proj4/lib/projections/nzmg","./projections/omerc":"proj4/lib/projections/omerc","./projections/poly":"proj4/lib/projections/poly","./projections/sinu":"proj4/lib/projections/sinu","./projections/somerc":"proj4/lib/projections/somerc","./projections/stere":"proj4/lib/projections/stere","./projections/sterea":"proj4/lib/projections/sterea","./projections/tmerc":"proj4/lib/projections/tmerc","./projections/utm":"proj4/lib/projections/utm","./projections/vandg":"proj4/lib/projections/vandg"}],"proj4":[function(require,module,exports){
var proj4 = require('./core');
proj4.defaultDatum = 'WGS84'; //default datum
proj4.Proj = require('./Proj');
proj4.WGS84 = new proj4.Proj('WGS84');
proj4.Point = require('./Point');
proj4.toPoint = require("./common/toPoint");
proj4.defs = require('./defs');
proj4.transform = require('./transform');
proj4.mgrs = require('mgrs');
proj4.version = require('../package.json').version;
require('./includedProjections')(proj4);
module.exports = proj4;
},{"../package.json":"proj4/package.json","./Point":"proj4/lib/Point","./Proj":"proj4/lib/Proj","./common/toPoint":"proj4/lib/common/toPoint","./core":"proj4/lib/core","./defs":"proj4/lib/defs","./includedProjections":"proj4/lib/includedProjections","./transform":"proj4/lib/transform","mgrs":"proj4/node_modules/mgrs/mgrs"}],"proj4/lib/parseCode":[function(require,module,exports){
var defs = require('./defs');
var wkt = require('./wkt');
var projStr = require('./projString');
function testObj(code){
  return typeof code === 'string';
}
function testDef(code){
  return code in defs;
}
function testWKT(code){
  var codeWords = ['GEOGCS','GEOCCS','PROJCS','LOCAL_CS'];
  return codeWords.reduce(function(a,b){
    return a+1+code.indexOf(b);
  },0);
}
function testProj(code){
  return code[0] === '+';
}
function parse(code){
  if (testObj(code)) {
    //check to see if this is a WKT string
    if (testDef(code)) {
      return defs[code];
    }
    else if (testWKT(code)) {
      return wkt(code);
    }
    else if (testProj(code)) {
      return projStr(code);
    }
  }else{
    return code;
  }
}

module.exports = parse;
},{"./defs":"proj4/lib/defs","./projString":"proj4/lib/projString","./wkt":"proj4/lib/wkt"}],"proj4/lib/projString":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var PrimeMeridian = require('./constants/PrimeMeridian');
var units = require('./constants/units');

module.exports = function(defData) {
  var self = {};
  var paramObj = {};
  defData.split("+").map(function(v) {
    return v.trim();
  }).filter(function(a) {
    return a;
  }).forEach(function(a) {
    var split = a.split("=");
    split.push(true);
    paramObj[split[0].toLowerCase()] = split[1];
  });
  var paramName, paramVal, paramOutname;
  var params = {
    proj: 'projName',
    datum: 'datumCode',
    rf: function(v) {
      self.rf = parseFloat(v);
    },
    lat_0: function(v) {
      self.lat0 = v * D2R;
    },
    lat_1: function(v) {
      self.lat1 = v * D2R;
    },
    lat_2: function(v) {
      self.lat2 = v * D2R;
    },
    lat_ts: function(v) {
      self.lat_ts = v * D2R;
    },
    lon_0: function(v) {
      self.long0 = v * D2R;
    },
    lon_1: function(v) {
      self.long1 = v * D2R;
    },
    lon_2: function(v) {
      self.long2 = v * D2R;
    },
    alpha: function(v) {
      self.alpha = parseFloat(v) * D2R;
    },
    lonc: function(v) {
      self.longc = v * D2R;
    },
    x_0: function(v) {
      self.x0 = parseFloat(v);
    },
    y_0: function(v) {
      self.y0 = parseFloat(v);
    },
    k_0: function(v) {
      self.k0 = parseFloat(v);
    },
    k: function(v) {
      self.k0 = parseFloat(v);
    },
    a: function(v) {
      self.a = parseFloat(v);
    },
    b: function(v) {
      self.b = parseFloat(v);
    },
    r_a: function() {
      self.R_A = true;
    },
    zone: function(v) {
      self.zone = parseInt(v, 10);
    },
    south: function() {
      self.utmSouth = true;
    },
    towgs84: function(v) {
      self.datum_params = v.split(",").map(function(a) {
        return parseFloat(a);
      });
    },
    to_meter: function(v) {
      self.to_meter = parseFloat(v);
    },
    units: function(v) {
      self.units = v;
      if (units[v]) {
        self.to_meter = units[v].to_meter;
      }
    },
    from_greenwich: function(v) {
      self.from_greenwich = v * D2R;
    },
    pm: function(v) {
      self.from_greenwich = (PrimeMeridian[v] ? PrimeMeridian[v] : parseFloat(v)) * D2R;
    },
    nadgrids: function(v) {
      if (v === '@null') {
        self.datumCode = 'none';
      }
      else {
        self.nadgrids = v;
      }
    },
    axis: function(v) {
      var legalAxis = "ewnsud";
      if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
        self.axis = v;
      }
    }
  };
  for (paramName in paramObj) {
    paramVal = paramObj[paramName];
    if (paramName in params) {
      paramOutname = params[paramName];
      if (typeof paramOutname === 'function') {
        paramOutname(paramVal);
      }
      else {
        self[paramOutname] = paramVal;
      }
    }
    else {
      self[paramName] = paramVal;
    }
  }
  if(typeof self.datumCode === 'string' && self.datumCode !== "WGS84"){
    self.datumCode = self.datumCode.toLowerCase();
  }
  return self;
};

},{"./constants/PrimeMeridian":"proj4/lib/constants/PrimeMeridian","./constants/units":"proj4/lib/constants/units"}],"proj4/lib/projections":[function(require,module,exports){
var projs = [
  require('./projections/merc'),
  require('./projections/longlat')
];
var names = {};
var projStore = [];

function add(proj, i) {
  var len = projStore.length;
  if (!proj.names) {
    console.log(i);
    return true;
  }
  projStore[len] = proj;
  proj.names.forEach(function(n) {
    names[n.toLowerCase()] = len;
  });
  return this;
}

exports.add = add;

exports.get = function(name) {
  if (!name) {
    return false;
  }
  var n = name.toLowerCase();
  if (typeof names[n] !== 'undefined' && projStore[names[n]]) {
    return projStore[names[n]];
  }
};
exports.start = function() {
  projs.forEach(add);
};

},{"./projections/longlat":"proj4/lib/projections/longlat","./projections/merc":"proj4/lib/projections/merc"}],"proj4/lib/projections/aea":[function(require,module,exports){
var EPSLN = 1.0e-10;
var msfnz = require('../common/msfnz');
var qsfnz = require('../common/qsfnz');
var adjust_lon = require('../common/adjust_lon');
var asinz = require('../common/asinz');
exports.init = function() {

  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
    return;
  }
  this.temp = this.b / this.a;
  this.es = 1 - Math.pow(this.temp, 2);
  this.e3 = Math.sqrt(this.es);

  this.sin_po = Math.sin(this.lat1);
  this.cos_po = Math.cos(this.lat1);
  this.t1 = this.sin_po;
  this.con = this.sin_po;
  this.ms1 = msfnz(this.e3, this.sin_po, this.cos_po);
  this.qs1 = qsfnz(this.e3, this.sin_po, this.cos_po);

  this.sin_po = Math.sin(this.lat2);
  this.cos_po = Math.cos(this.lat2);
  this.t2 = this.sin_po;
  this.ms2 = msfnz(this.e3, this.sin_po, this.cos_po);
  this.qs2 = qsfnz(this.e3, this.sin_po, this.cos_po);

  this.sin_po = Math.sin(this.lat0);
  this.cos_po = Math.cos(this.lat0);
  this.t3 = this.sin_po;
  this.qs0 = qsfnz(this.e3, this.sin_po, this.cos_po);

  if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
    this.ns0 = (this.ms1 * this.ms1 - this.ms2 * this.ms2) / (this.qs2 - this.qs1);
  }
  else {
    this.ns0 = this.con;
  }
  this.c = this.ms1 * this.ms1 + this.ns0 * this.qs1;
  this.rh = this.a * Math.sqrt(this.c - this.ns0 * this.qs0) / this.ns0;
};

/* Albers Conical Equal Area forward equations--mapping lat,long to x,y
  -------------------------------------------------------------------*/
exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  this.sin_phi = Math.sin(lat);
  this.cos_phi = Math.cos(lat);

  var qs = qsfnz(this.e3, this.sin_phi, this.cos_phi);
  var rh1 = this.a * Math.sqrt(this.c - this.ns0 * qs) / this.ns0;
  var theta = this.ns0 * adjust_lon(lon - this.long0);
  var x = rh1 * Math.sin(theta) + this.x0;
  var y = this.rh - rh1 * Math.cos(theta) + this.y0;

  p.x = x;
  p.y = y;
  return p;
};


exports.inverse = function(p) {
  var rh1, qs, con, theta, lon, lat;

  p.x -= this.x0;
  p.y = this.rh - p.y + this.y0;
  if (this.ns0 >= 0) {
    rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
    con = 1;
  }
  else {
    rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
    con = -1;
  }
  theta = 0;
  if (rh1 !== 0) {
    theta = Math.atan2(con * p.x, con * p.y);
  }
  con = rh1 * this.ns0 / this.a;
  if (this.sphere) {
    lat = Math.asin((this.c - con * con) / (2 * this.ns0));
  }
  else {
    qs = (this.c - con * con) / this.ns0;
    lat = this.phi1z(this.e3, qs);
  }

  lon = adjust_lon(theta / this.ns0 + this.long0);
  p.x = lon;
  p.y = lat;
  return p;
};

/* Function to compute phi1, the latitude for the inverse of the
   Albers Conical Equal-Area projection.
-------------------------------------------*/
exports.phi1z = function(eccent, qs) {
  var sinphi, cosphi, con, com, dphi;
  var phi = asinz(0.5 * qs);
  if (eccent < EPSLN) {
    return phi;
  }

  var eccnts = eccent * eccent;
  for (var i = 1; i <= 25; i++) {
    sinphi = Math.sin(phi);
    cosphi = Math.cos(phi);
    con = eccent * sinphi;
    com = 1 - con * con;
    dphi = 0.5 * com * com / cosphi * (qs / (1 - eccnts) - sinphi / com + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
    phi = phi + dphi;
    if (Math.abs(dphi) <= 1e-7) {
      return phi;
    }
  }
  return null;
};
exports.names = ["Albers_Conic_Equal_Area", "Albers", "aea"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/msfnz":"proj4/lib/common/msfnz","../common/qsfnz":"proj4/lib/common/qsfnz"}],"proj4/lib/projections/aeqd":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var mlfn = require('../common/mlfn');
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var gN = require('../common/gN');
var asinz = require('../common/asinz');
var imlfn = require('../common/imlfn');
exports.init = function() {
  this.sin_p12 = Math.sin(this.lat0);
  this.cos_p12 = Math.cos(this.lat0);
};

exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var sinphi = Math.sin(p.y);
  var cosphi = Math.cos(p.y);
  var dlon = adjust_lon(lon - this.long0);
  var e0, e1, e2, e3, Mlp, Ml, tanphi, Nl1, Nl, psi, Az, G, H, GH, Hs, c, kp, cos_c, s, s2, s3, s4, s5;
  if (this.sphere) {
    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
      //North Pole case
      p.x = this.x0 + this.a * (HALF_PI - lat) * Math.sin(dlon);
      p.y = this.y0 - this.a * (HALF_PI - lat) * Math.cos(dlon);
      return p;
    }
    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
      //South Pole case
      p.x = this.x0 + this.a * (HALF_PI + lat) * Math.sin(dlon);
      p.y = this.y0 + this.a * (HALF_PI + lat) * Math.cos(dlon);
      return p;
    }
    else {
      //default case
      cos_c = this.sin_p12 * sinphi + this.cos_p12 * cosphi * Math.cos(dlon);
      c = Math.acos(cos_c);
      kp = c / Math.sin(c);
      p.x = this.x0 + this.a * kp * cosphi * Math.sin(dlon);
      p.y = this.y0 + this.a * kp * (this.cos_p12 * sinphi - this.sin_p12 * cosphi * Math.cos(dlon));
      return p;
    }
  }
  else {
    e0 = e0fn(this.es);
    e1 = e1fn(this.es);
    e2 = e2fn(this.es);
    e3 = e3fn(this.es);
    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
      //North Pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      Ml = this.a * mlfn(e0, e1, e2, e3, lat);
      p.x = this.x0 + (Mlp - Ml) * Math.sin(dlon);
      p.y = this.y0 - (Mlp - Ml) * Math.cos(dlon);
      return p;
    }
    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
      //South Pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      Ml = this.a * mlfn(e0, e1, e2, e3, lat);
      p.x = this.x0 + (Mlp + Ml) * Math.sin(dlon);
      p.y = this.y0 + (Mlp + Ml) * Math.cos(dlon);
      return p;
    }
    else {
      //Default case
      tanphi = sinphi / cosphi;
      Nl1 = gN(this.a, this.e, this.sin_p12);
      Nl = gN(this.a, this.e, sinphi);
      psi = Math.atan((1 - this.es) * tanphi + this.es * Nl1 * this.sin_p12 / (Nl * cosphi));
      Az = Math.atan2(Math.sin(dlon), this.cos_p12 * Math.tan(psi) - this.sin_p12 * Math.cos(dlon));
      if (Az === 0) {
        s = Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
      }
      else if (Math.abs(Math.abs(Az) - Math.PI) <= EPSLN) {
        s = -Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
      }
      else {
        s = Math.asin(Math.sin(dlon) * Math.cos(psi) / Math.sin(Az));
      }
      G = this.e * this.sin_p12 / Math.sqrt(1 - this.es);
      H = this.e * this.cos_p12 * Math.cos(Az) / Math.sqrt(1 - this.es);
      GH = G * H;
      Hs = H * H;
      s2 = s * s;
      s3 = s2 * s;
      s4 = s3 * s;
      s5 = s4 * s;
      c = Nl1 * s * (1 - s2 * Hs * (1 - Hs) / 6 + s3 / 8 * GH * (1 - 2 * Hs) + s4 / 120 * (Hs * (4 - 7 * Hs) - 3 * G * G * (1 - 7 * Hs)) - s5 / 48 * GH);
      p.x = this.x0 + c * Math.sin(Az);
      p.y = this.y0 + c * Math.cos(Az);
      return p;
    }
  }


};

exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var rh, z, sinz, cosz, lon, lat, con, e0, e1, e2, e3, Mlp, M, N1, psi, Az, cosAz, tmp, A, B, D, Ee, F;
  if (this.sphere) {
    rh = Math.sqrt(p.x * p.x + p.y * p.y);
    if (rh > (2 * HALF_PI * this.a)) {
      return;
    }
    z = rh / this.a;

    sinz = Math.sin(z);
    cosz = Math.cos(z);

    lon = this.long0;
    if (Math.abs(rh) <= EPSLN) {
      lat = this.lat0;
    }
    else {
      lat = asinz(cosz * this.sin_p12 + (p.y * sinz * this.cos_p12) / rh);
      con = Math.abs(this.lat0) - HALF_PI;
      if (Math.abs(con) <= EPSLN) {
        if (this.lat0 >= 0) {
          lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y));
        }
        else {
          lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y));
        }
      }
      else {
        /*con = cosz - this.sin_p12 * Math.sin(lat);
        if ((Math.abs(con) < EPSLN) && (Math.abs(p.x) < EPSLN)) {
          //no-op, just keep the lon value as is
        } else {
          var temp = Math.atan2((p.x * sinz * this.cos_p12), (con * rh));
          lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz * this.cos_p12), (con * rh)));
        }*/
        lon = adjust_lon(this.long0 + Math.atan2(p.x * sinz, rh * this.cos_p12 * cosz - p.y * this.sin_p12 * sinz));
      }
    }

    p.x = lon;
    p.y = lat;
    return p;
  }
  else {
    e0 = e0fn(this.es);
    e1 = e1fn(this.es);
    e2 = e2fn(this.es);
    e3 = e3fn(this.es);
    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
      //North pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      rh = Math.sqrt(p.x * p.x + p.y * p.y);
      M = Mlp - rh;
      lat = imlfn(M / this.a, e0, e1, e2, e3);
      lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
      p.x = lon;
      p.y = lat;
      return p;
    }
    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
      //South pole case
      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
      rh = Math.sqrt(p.x * p.x + p.y * p.y);
      M = rh - Mlp;

      lat = imlfn(M / this.a, e0, e1, e2, e3);
      lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
      p.x = lon;
      p.y = lat;
      return p;
    }
    else {
      //default case
      rh = Math.sqrt(p.x * p.x + p.y * p.y);
      Az = Math.atan2(p.x, p.y);
      N1 = gN(this.a, this.e, this.sin_p12);
      cosAz = Math.cos(Az);
      tmp = this.e * this.cos_p12 * cosAz;
      A = -tmp * tmp / (1 - this.es);
      B = 3 * this.es * (1 - A) * this.sin_p12 * this.cos_p12 * cosAz / (1 - this.es);
      D = rh / N1;
      Ee = D - A * (1 + A) * Math.pow(D, 3) / 6 - B * (1 + 3 * A) * Math.pow(D, 4) / 24;
      F = 1 - A * Ee * Ee / 2 - D * Ee * Ee * Ee / 6;
      psi = Math.asin(this.sin_p12 * Math.cos(Ee) + this.cos_p12 * Math.sin(Ee) * cosAz);
      lon = adjust_lon(this.long0 + Math.asin(Math.sin(Az) * Math.sin(Ee) / Math.cos(psi)));
      lat = Math.atan((1 - this.es * F * this.sin_p12 / Math.sin(psi)) * Math.tan(psi) / (1 - this.es));
      p.x = lon;
      p.y = lat;
      return p;
    }
  }

};
exports.names = ["Azimuthal_Equidistant", "aeqd"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/gN":"proj4/lib/common/gN","../common/imlfn":"proj4/lib/common/imlfn","../common/mlfn":"proj4/lib/common/mlfn"}],"proj4/lib/projections/cass":[function(require,module,exports){
var mlfn = require('../common/mlfn');
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var gN = require('../common/gN');
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var imlfn = require('../common/imlfn');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
exports.init = function() {
  if (!this.sphere) {
    this.e0 = e0fn(this.es);
    this.e1 = e1fn(this.es);
    this.e2 = e2fn(this.es);
    this.e3 = e3fn(this.es);
    this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
  }
};



/* Cassini forward equations--mapping lat,long to x,y
  -----------------------------------------------------------------------*/
exports.forward = function(p) {

  /* Forward equations
      -----------------*/
  var x, y;
  var lam = p.x;
  var phi = p.y;
  lam = adjust_lon(lam - this.long0);

  if (this.sphere) {
    x = this.a * Math.asin(Math.cos(phi) * Math.sin(lam));
    y = this.a * (Math.atan2(Math.tan(phi), Math.cos(lam)) - this.lat0);
  }
  else {
    //ellipsoid
    var sinphi = Math.sin(phi);
    var cosphi = Math.cos(phi);
    var nl = gN(this.a, this.e, sinphi);
    var tl = Math.tan(phi) * Math.tan(phi);
    var al = lam * Math.cos(phi);
    var asq = al * al;
    var cl = this.es * cosphi * cosphi / (1 - this.es);
    var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);

    x = nl * al * (1 - asq * tl * (1 / 6 - (8 - tl + 8 * cl) * asq / 120));
    y = ml - this.ml0 + nl * sinphi / cosphi * asq * (0.5 + (5 - tl + 6 * cl) * asq / 24);


  }

  p.x = x + this.x0;
  p.y = y + this.y0;
  return p;
};

/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var x = p.x / this.a;
  var y = p.y / this.a;
  var phi, lam;

  if (this.sphere) {
    var dd = y + this.lat0;
    phi = Math.asin(Math.sin(dd) * Math.cos(x));
    lam = Math.atan2(Math.tan(x), Math.cos(dd));
  }
  else {
    /* ellipsoid */
    var ml1 = this.ml0 / this.a + y;
    var phi1 = imlfn(ml1, this.e0, this.e1, this.e2, this.e3);
    if (Math.abs(Math.abs(phi1) - HALF_PI) <= EPSLN) {
      p.x = this.long0;
      p.y = HALF_PI;
      if (y < 0) {
        p.y *= -1;
      }
      return p;
    }
    var nl1 = gN(this.a, this.e, Math.sin(phi1));

    var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es);
    var tl1 = Math.pow(Math.tan(phi1), 2);
    var dl = x * this.a / nl1;
    var dsq = dl * dl;
    phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24);
    lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1);

  }

  p.x = adjust_lon(lam + this.long0);
  p.y = adjust_lat(phi);
  return p;

};
exports.names = ["Cassini", "Cassini_Soldner", "cass"];
},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/gN":"proj4/lib/common/gN","../common/imlfn":"proj4/lib/common/imlfn","../common/mlfn":"proj4/lib/common/mlfn"}],"proj4/lib/projections/cea":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var qsfnz = require('../common/qsfnz');
var msfnz = require('../common/msfnz');
var iqsfnz = require('../common/iqsfnz');
/*
  reference:  
    "Cartographic Projection Procedures for the UNIX Environment-
    A User's Manual" by Gerald I. Evenden,
    USGS Open File Report 90-284and Release 4 Interim Reports (2003)
*/
exports.init = function() {
  //no-op
  if (!this.sphere) {
    this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
  }
};


/* Cylindrical Equal Area forward equations--mapping lat,long to x,y
    ------------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var x, y;
  /* Forward equations
      -----------------*/
  var dlon = adjust_lon(lon - this.long0);
  if (this.sphere) {
    x = this.x0 + this.a * dlon * Math.cos(this.lat_ts);
    y = this.y0 + this.a * Math.sin(lat) / Math.cos(this.lat_ts);
  }
  else {
    var qs = qsfnz(this.e, Math.sin(lat));
    x = this.x0 + this.a * this.k0 * dlon;
    y = this.y0 + this.a * qs * 0.5 / this.k0;
  }

  p.x = x;
  p.y = y;
  return p;
};

/* Cylindrical Equal Area inverse equations--mapping x,y to lat/long
    ------------------------------------------------------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var lon, lat;

  if (this.sphere) {
    lon = adjust_lon(this.long0 + (p.x / this.a) / Math.cos(this.lat_ts));
    lat = Math.asin((p.y / this.a) * Math.cos(this.lat_ts));
  }
  else {
    lat = iqsfnz(this.e, 2 * p.y * this.k0 / this.a);
    lon = adjust_lon(this.long0 + p.x / (this.a * this.k0));
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["cea"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/iqsfnz":"proj4/lib/common/iqsfnz","../common/msfnz":"proj4/lib/common/msfnz","../common/qsfnz":"proj4/lib/common/qsfnz"}],"proj4/lib/projections/eqc":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
exports.init = function() {

  this.x0 = this.x0 || 0;
  this.y0 = this.y0 || 0;
  this.lat0 = this.lat0 || 0;
  this.long0 = this.long0 || 0;
  this.lat_ts = this.lat_ts || 0;
  this.title = this.title || "Equidistant Cylindrical (Plate Carre)";

  this.rc = Math.cos(this.lat_ts);
};


// forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  var dlon = adjust_lon(lon - this.long0);
  var dlat = adjust_lat(lat - this.lat0);
  p.x = this.x0 + (this.a * dlon * this.rc);
  p.y = this.y0 + (this.a * dlat);
  return p;
};

// inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
exports.inverse = function(p) {

  var x = p.x;
  var y = p.y;

  p.x = adjust_lon(this.long0 + ((x - this.x0) / (this.a * this.rc)));
  p.y = adjust_lat(this.lat0 + ((y - this.y0) / (this.a)));
  return p;
};
exports.names = ["Equirectangular", "Equidistant_Cylindrical", "eqc"];

},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/eqdc":[function(require,module,exports){
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var msfnz = require('../common/msfnz');
var mlfn = require('../common/mlfn');
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var imlfn = require('../common/imlfn');
var EPSLN = 1.0e-10;
exports.init = function() {

  /* Place parameters in static storage for common use
      -------------------------------------------------*/
  // Standard Parallels cannot be equal and on opposite sides of the equator
  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
    return;
  }
  this.lat2 = this.lat2 || this.lat1;
  this.temp = this.b / this.a;
  this.es = 1 - Math.pow(this.temp, 2);
  this.e = Math.sqrt(this.es);
  this.e0 = e0fn(this.es);
  this.e1 = e1fn(this.es);
  this.e2 = e2fn(this.es);
  this.e3 = e3fn(this.es);

  this.sinphi = Math.sin(this.lat1);
  this.cosphi = Math.cos(this.lat1);

  this.ms1 = msfnz(this.e, this.sinphi, this.cosphi);
  this.ml1 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat1);

  if (Math.abs(this.lat1 - this.lat2) < EPSLN) {
    this.ns = this.sinphi;
  }
  else {
    this.sinphi = Math.sin(this.lat2);
    this.cosphi = Math.cos(this.lat2);
    this.ms2 = msfnz(this.e, this.sinphi, this.cosphi);
    this.ml2 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat2);
    this.ns = (this.ms1 - this.ms2) / (this.ml2 - this.ml1);
  }
  this.g = this.ml1 + this.ms1 / this.ns;
  this.ml0 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
  this.rh = this.a * (this.g - this.ml0);
};


/* Equidistant Conic forward equations--mapping lat,long to x,y
  -----------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var rh1;

  /* Forward equations
      -----------------*/
  if (this.sphere) {
    rh1 = this.a * (this.g - lat);
  }
  else {
    var ml = mlfn(this.e0, this.e1, this.e2, this.e3, lat);
    rh1 = this.a * (this.g - ml);
  }
  var theta = this.ns * adjust_lon(lon - this.long0);
  var x = this.x0 + rh1 * Math.sin(theta);
  var y = this.y0 + this.rh - rh1 * Math.cos(theta);
  p.x = x;
  p.y = y;
  return p;
};

/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y = this.rh - p.y + this.y0;
  var con, rh1, lat, lon;
  if (this.ns >= 0) {
    rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
    con = 1;
  }
  else {
    rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
    con = -1;
  }
  var theta = 0;
  if (rh1 !== 0) {
    theta = Math.atan2(con * p.x, con * p.y);
  }

  if (this.sphere) {
    lon = adjust_lon(this.long0 + theta / this.ns);
    lat = adjust_lat(this.g - rh1 / this.a);
    p.x = lon;
    p.y = lat;
    return p;
  }
  else {
    var ml = this.g - rh1 / this.a;
    lat = imlfn(ml, this.e0, this.e1, this.e2, this.e3);
    lon = adjust_lon(this.long0 + theta / this.ns);
    p.x = lon;
    p.y = lat;
    return p;
  }

};
exports.names = ["Equidistant_Conic", "eqdc"];

},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/imlfn":"proj4/lib/common/imlfn","../common/mlfn":"proj4/lib/common/mlfn","../common/msfnz":"proj4/lib/common/msfnz"}],"proj4/lib/projections/gauss":[function(require,module,exports){
var FORTPI = Math.PI/4;
var srat = require('../common/srat');
var HALF_PI = Math.PI/2;
var MAX_ITER = 20;
exports.init = function() {
  var sphi = Math.sin(this.lat0);
  var cphi = Math.cos(this.lat0);
  cphi *= cphi;
  this.rc = Math.sqrt(1 - this.es) / (1 - this.es * sphi * sphi);
  this.C = Math.sqrt(1 + this.es * cphi * cphi / (1 - this.es));
  this.phic0 = Math.asin(sphi / this.C);
  this.ratexp = 0.5 * this.C * this.e;
  this.K = Math.tan(0.5 * this.phic0 + FORTPI) / (Math.pow(Math.tan(0.5 * this.lat0 + FORTPI), this.C) * srat(this.e * sphi, this.ratexp));
};

exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;

  p.y = 2 * Math.atan(this.K * Math.pow(Math.tan(0.5 * lat + FORTPI), this.C) * srat(this.e * Math.sin(lat), this.ratexp)) - HALF_PI;
  p.x = this.C * lon;
  return p;
};

exports.inverse = function(p) {
  var DEL_TOL = 1e-14;
  var lon = p.x / this.C;
  var lat = p.y;
  var num = Math.pow(Math.tan(0.5 * lat + FORTPI) / this.K, 1 / this.C);
  for (var i = MAX_ITER; i > 0; --i) {
    lat = 2 * Math.atan(num * srat(this.e * Math.sin(p.y), - 0.5 * this.e)) - HALF_PI;
    if (Math.abs(lat - p.y) < DEL_TOL) {
      break;
    }
    p.y = lat;
  }
  /* convergence failed */
  if (!i) {
    return null;
  }
  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["gauss"];

},{"../common/srat":"proj4/lib/common/srat"}],"proj4/lib/projections/gnom":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var EPSLN = 1.0e-10;
var asinz = require('../common/asinz');

/*
  reference:
    Wolfram Mathworld "Gnomonic Projection"
    http://mathworld.wolfram.com/GnomonicProjection.html
    Accessed: 12th November 2009
  */
exports.init = function() {

  /* Place parameters in static storage for common use
      -------------------------------------------------*/
  this.sin_p14 = Math.sin(this.lat0);
  this.cos_p14 = Math.cos(this.lat0);
  // Approximation for projecting points to the horizon (infinity)
  this.infinity_dist = 1000 * this.a;
  this.rc = 1;
};


/* Gnomonic forward equations--mapping lat,long to x,y
    ---------------------------------------------------*/
exports.forward = function(p) {
  var sinphi, cosphi; /* sin and cos value        */
  var dlon; /* delta longitude value      */
  var coslon; /* cos of longitude        */
  var ksp; /* scale factor          */
  var g;
  var x, y;
  var lon = p.x;
  var lat = p.y;
  /* Forward equations
      -----------------*/
  dlon = adjust_lon(lon - this.long0);

  sinphi = Math.sin(lat);
  cosphi = Math.cos(lat);

  coslon = Math.cos(dlon);
  g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
  ksp = 1;
  if ((g > 0) || (Math.abs(g) <= EPSLN)) {
    x = this.x0 + this.a * ksp * cosphi * Math.sin(dlon) / g;
    y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon) / g;
  }
  else {

    // Point is in the opposing hemisphere and is unprojectable
    // We still need to return a reasonable point, so we project 
    // to infinity, on a bearing 
    // equivalent to the northern hemisphere equivalent
    // This is a reasonable approximation for short shapes and lines that 
    // straddle the horizon.

    x = this.x0 + this.infinity_dist * cosphi * Math.sin(dlon);
    y = this.y0 + this.infinity_dist * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);

  }
  p.x = x;
  p.y = y;
  return p;
};


exports.inverse = function(p) {
  var rh; /* Rho */
  var sinc, cosc;
  var c;
  var lon, lat;

  /* Inverse equations
      -----------------*/
  p.x = (p.x - this.x0) / this.a;
  p.y = (p.y - this.y0) / this.a;

  p.x /= this.k0;
  p.y /= this.k0;

  if ((rh = Math.sqrt(p.x * p.x + p.y * p.y))) {
    c = Math.atan2(rh, this.rc);
    sinc = Math.sin(c);
    cosc = Math.cos(c);

    lat = asinz(cosc * this.sin_p14 + (p.y * sinc * this.cos_p14) / rh);
    lon = Math.atan2(p.x * sinc, rh * this.cos_p14 * cosc - p.y * this.sin_p14 * sinc);
    lon = adjust_lon(this.long0 + lon);
  }
  else {
    lat = this.phic0;
    lon = 0;
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["gnom"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz"}],"proj4/lib/projections/krovak":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
exports.init = function() {
  this.a = 6377397.155;
  this.es = 0.006674372230614;
  this.e = Math.sqrt(this.es);
  if (!this.lat0) {
    this.lat0 = 0.863937979737193;
  }
  if (!this.long0) {
    this.long0 = 0.7417649320975901 - 0.308341501185665;
  }
  /* if scale not set default to 0.9999 */
  if (!this.k0) {
    this.k0 = 0.9999;
  }
  this.s45 = 0.785398163397448; /* 45 */
  this.s90 = 2 * this.s45;
  this.fi0 = this.lat0;
  this.e2 = this.es;
  this.e = Math.sqrt(this.e2);
  this.alfa = Math.sqrt(1 + (this.e2 * Math.pow(Math.cos(this.fi0), 4)) / (1 - this.e2));
  this.uq = 1.04216856380474;
  this.u0 = Math.asin(Math.sin(this.fi0) / this.alfa);
  this.g = Math.pow((1 + this.e * Math.sin(this.fi0)) / (1 - this.e * Math.sin(this.fi0)), this.alfa * this.e / 2);
  this.k = Math.tan(this.u0 / 2 + this.s45) / Math.pow(Math.tan(this.fi0 / 2 + this.s45), this.alfa) * this.g;
  this.k1 = this.k0;
  this.n0 = this.a * Math.sqrt(1 - this.e2) / (1 - this.e2 * Math.pow(Math.sin(this.fi0), 2));
  this.s0 = 1.37008346281555;
  this.n = Math.sin(this.s0);
  this.ro0 = this.k1 * this.n0 / Math.tan(this.s0);
  this.ad = this.s90 - this.uq;
};

/* ellipsoid */
/* calculate xy from lat/lon */
/* Constants, identical to inverse transform function */
exports.forward = function(p) {
  var gfi, u, deltav, s, d, eps, ro;
  var lon = p.x;
  var lat = p.y;
  var delta_lon = adjust_lon(lon - this.long0);
  /* Transformation */
  gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2));
  u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45);
  deltav = -delta_lon * this.alfa;
  s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav));
  d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s));
  eps = this.n * d;
  ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n);
  p.y = ro * Math.cos(eps) / 1;
  p.x = ro * Math.sin(eps) / 1;

  if (!this.czech) {
    p.y *= -1;
    p.x *= -1;
  }
  return (p);
};

/* calculate lat/lon from xy */
exports.inverse = function(p) {
  var u, deltav, s, d, eps, ro, fi1;
  var ok;

  /* Transformation */
  /* revert y, x*/
  var tmp = p.x;
  p.x = p.y;
  p.y = tmp;
  if (!this.czech) {
    p.y *= -1;
    p.x *= -1;
  }
  ro = Math.sqrt(p.x * p.x + p.y * p.y);
  eps = Math.atan2(p.y, p.x);
  d = eps / Math.sin(this.s0);
  s = 2 * (Math.atan(Math.pow(this.ro0 / ro, 1 / this.n) * Math.tan(this.s0 / 2 + this.s45)) - this.s45);
  u = Math.asin(Math.cos(this.ad) * Math.sin(s) - Math.sin(this.ad) * Math.cos(s) * Math.cos(d));
  deltav = Math.asin(Math.cos(s) * Math.sin(d) / Math.cos(u));
  p.x = this.long0 - deltav / this.alfa;
  fi1 = u;
  ok = 0;
  var iter = 0;
  do {
    p.y = 2 * (Math.atan(Math.pow(this.k, - 1 / this.alfa) * Math.pow(Math.tan(u / 2 + this.s45), 1 / this.alfa) * Math.pow((1 + this.e * Math.sin(fi1)) / (1 - this.e * Math.sin(fi1)), this.e / 2)) - this.s45);
    if (Math.abs(fi1 - p.y) < 0.0000000001) {
      ok = 1;
    }
    fi1 = p.y;
    iter += 1;
  } while (ok === 0 && iter < 15);
  if (iter >= 15) {
    return null;
  }

  return (p);
};
exports.names = ["Krovak", "krovak"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/laea":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var FORTPI = Math.PI/4;
var EPSLN = 1.0e-10;
var qsfnz = require('../common/qsfnz');
var adjust_lon = require('../common/adjust_lon');
/*
  reference
    "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
    The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
  */

exports.S_POLE = 1;
exports.N_POLE = 2;
exports.EQUIT = 3;
exports.OBLIQ = 4;


/* Initialize the Lambert Azimuthal Equal Area projection
  ------------------------------------------------------*/
exports.init = function() {
  var t = Math.abs(this.lat0);
  if (Math.abs(t - HALF_PI) < EPSLN) {
    this.mode = this.lat0 < 0 ? this.S_POLE : this.N_POLE;
  }
  else if (Math.abs(t) < EPSLN) {
    this.mode = this.EQUIT;
  }
  else {
    this.mode = this.OBLIQ;
  }
  if (this.es > 0) {
    var sinphi;

    this.qp = qsfnz(this.e, 1);
    this.mmf = 0.5 / (1 - this.es);
    this.apa = this.authset(this.es);
    switch (this.mode) {
    case this.N_POLE:
      this.dd = 1;
      break;
    case this.S_POLE:
      this.dd = 1;
      break;
    case this.EQUIT:
      this.rq = Math.sqrt(0.5 * this.qp);
      this.dd = 1 / this.rq;
      this.xmf = 1;
      this.ymf = 0.5 * this.qp;
      break;
    case this.OBLIQ:
      this.rq = Math.sqrt(0.5 * this.qp);
      sinphi = Math.sin(this.lat0);
      this.sinb1 = qsfnz(this.e, sinphi) / this.qp;
      this.cosb1 = Math.sqrt(1 - this.sinb1 * this.sinb1);
      this.dd = Math.cos(this.lat0) / (Math.sqrt(1 - this.es * sinphi * sinphi) * this.rq * this.cosb1);
      this.ymf = (this.xmf = this.rq) / this.dd;
      this.xmf *= this.dd;
      break;
    }
  }
  else {
    if (this.mode === this.OBLIQ) {
      this.sinph0 = Math.sin(this.lat0);
      this.cosph0 = Math.cos(this.lat0);
    }
  }
};

/* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y
  -----------------------------------------------------------------------*/
exports.forward = function(p) {

  /* Forward equations
      -----------------*/
  var x, y, coslam, sinlam, sinphi, q, sinb, cosb, b, cosphi;
  var lam = p.x;
  var phi = p.y;

  lam = adjust_lon(lam - this.long0);

  if (this.sphere) {
    sinphi = Math.sin(phi);
    cosphi = Math.cos(phi);
    coslam = Math.cos(lam);
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      y = (this.mode === this.EQUIT) ? 1 + cosphi * coslam : 1 + this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
      if (y <= EPSLN) {
        return null;
      }
      y = Math.sqrt(2 / y);
      x = y * cosphi * Math.sin(lam);
      y *= (this.mode === this.EQUIT) ? sinphi : this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
    }
    else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
      if (this.mode === this.N_POLE) {
        coslam = -coslam;
      }
      if (Math.abs(phi + this.phi0) < EPSLN) {
        return null;
      }
      y = FORTPI - phi * 0.5;
      y = 2 * ((this.mode === this.S_POLE) ? Math.cos(y) : Math.sin(y));
      x = y * Math.sin(lam);
      y *= coslam;
    }
  }
  else {
    sinb = 0;
    cosb = 0;
    b = 0;
    coslam = Math.cos(lam);
    sinlam = Math.sin(lam);
    sinphi = Math.sin(phi);
    q = qsfnz(this.e, sinphi);
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      sinb = q / this.qp;
      cosb = Math.sqrt(1 - sinb * sinb);
    }
    switch (this.mode) {
    case this.OBLIQ:
      b = 1 + this.sinb1 * sinb + this.cosb1 * cosb * coslam;
      break;
    case this.EQUIT:
      b = 1 + cosb * coslam;
      break;
    case this.N_POLE:
      b = HALF_PI + phi;
      q = this.qp - q;
      break;
    case this.S_POLE:
      b = phi - HALF_PI;
      q = this.qp + q;
      break;
    }
    if (Math.abs(b) < EPSLN) {
      return null;
    }
    switch (this.mode) {
    case this.OBLIQ:
    case this.EQUIT:
      b = Math.sqrt(2 / b);
      if (this.mode === this.OBLIQ) {
        y = this.ymf * b * (this.cosb1 * sinb - this.sinb1 * cosb * coslam);
      }
      else {
        y = (b = Math.sqrt(2 / (1 + cosb * coslam))) * sinb * this.ymf;
      }
      x = this.xmf * b * cosb * sinlam;
      break;
    case this.N_POLE:
    case this.S_POLE:
      if (q >= 0) {
        x = (b = Math.sqrt(q)) * sinlam;
        y = coslam * ((this.mode === this.S_POLE) ? b : -b);
      }
      else {
        x = y = 0;
      }
      break;
    }
  }

  p.x = this.a * x + this.x0;
  p.y = this.a * y + this.y0;
  return p;
};

/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var x = p.x / this.a;
  var y = p.y / this.a;
  var lam, phi, cCe, sCe, q, rho, ab;

  if (this.sphere) {
    var cosz = 0,
      rh, sinz = 0;

    rh = Math.sqrt(x * x + y * y);
    phi = rh * 0.5;
    if (phi > 1) {
      return null;
    }
    phi = 2 * Math.asin(phi);
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      sinz = Math.sin(phi);
      cosz = Math.cos(phi);
    }
    switch (this.mode) {
    case this.EQUIT:
      phi = (Math.abs(rh) <= EPSLN) ? 0 : Math.asin(y * sinz / rh);
      x *= sinz;
      y = cosz * rh;
      break;
    case this.OBLIQ:
      phi = (Math.abs(rh) <= EPSLN) ? this.phi0 : Math.asin(cosz * this.sinph0 + y * sinz * this.cosph0 / rh);
      x *= sinz * this.cosph0;
      y = (cosz - Math.sin(phi) * this.sinph0) * rh;
      break;
    case this.N_POLE:
      y = -y;
      phi = HALF_PI - phi;
      break;
    case this.S_POLE:
      phi -= HALF_PI;
      break;
    }
    lam = (y === 0 && (this.mode === this.EQUIT || this.mode === this.OBLIQ)) ? 0 : Math.atan2(x, y);
  }
  else {
    ab = 0;
    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
      x /= this.dd;
      y *= this.dd;
      rho = Math.sqrt(x * x + y * y);
      if (rho < EPSLN) {
        p.x = 0;
        p.y = this.phi0;
        return p;
      }
      sCe = 2 * Math.asin(0.5 * rho / this.rq);
      cCe = Math.cos(sCe);
      x *= (sCe = Math.sin(sCe));
      if (this.mode === this.OBLIQ) {
        ab = cCe * this.sinb1 + y * sCe * this.cosb1 / rho;
        q = this.qp * ab;
        y = rho * this.cosb1 * cCe - y * this.sinb1 * sCe;
      }
      else {
        ab = y * sCe / rho;
        q = this.qp * ab;
        y = rho * cCe;
      }
    }
    else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
      if (this.mode === this.N_POLE) {
        y = -y;
      }
      q = (x * x + y * y);
      if (!q) {
        p.x = 0;
        p.y = this.phi0;
        return p;
      }
      ab = 1 - q / this.qp;
      if (this.mode === this.S_POLE) {
        ab = -ab;
      }
    }
    lam = Math.atan2(x, y);
    phi = this.authlat(Math.asin(ab), this.apa);
  }


  p.x = adjust_lon(this.long0 + lam);
  p.y = phi;
  return p;
};

/* determine latitude from authalic latitude */
exports.P00 = 0.33333333333333333333;
exports.P01 = 0.17222222222222222222;
exports.P02 = 0.10257936507936507936;
exports.P10 = 0.06388888888888888888;
exports.P11 = 0.06640211640211640211;
exports.P20 = 0.01641501294219154443;

exports.authset = function(es) {
  var t;
  var APA = [];
  APA[0] = es * this.P00;
  t = es * es;
  APA[0] += t * this.P01;
  APA[1] = t * this.P10;
  t *= es;
  APA[0] += t * this.P02;
  APA[1] += t * this.P11;
  APA[2] = t * this.P20;
  return APA;
};

exports.authlat = function(beta, APA) {
  var t = beta + beta;
  return (beta + APA[0] * Math.sin(t) + APA[1] * Math.sin(t + t) + APA[2] * Math.sin(t + t + t));
};
exports.names = ["Lambert Azimuthal Equal Area", "Lambert_Azimuthal_Equal_Area", "laea"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/qsfnz":"proj4/lib/common/qsfnz"}],"proj4/lib/projections/lcc":[function(require,module,exports){
var EPSLN = 1.0e-10;
var msfnz = require('../common/msfnz');
var tsfnz = require('../common/tsfnz');
var HALF_PI = Math.PI/2;
var sign = require('../common/sign');
var adjust_lon = require('../common/adjust_lon');
var phi2z = require('../common/phi2z');
exports.init = function() {

  // array of:  r_maj,r_min,lat1,lat2,c_lon,c_lat,false_east,false_north
  //double c_lat;                   /* center latitude                      */
  //double c_lon;                   /* center longitude                     */
  //double lat1;                    /* first standard parallel              */
  //double lat2;                    /* second standard parallel             */
  //double r_maj;                   /* major axis                           */
  //double r_min;                   /* minor axis                           */
  //double false_east;              /* x offset in meters                   */
  //double false_north;             /* y offset in meters                   */

  if (!this.lat2) {
    this.lat2 = this.lat1;
  } //if lat2 is not defined
  if (!this.k0) {
    this.k0 = 1;
  }
  this.x0 = this.x0 || 0;
  this.y0 = this.y0 || 0;
  // Standard Parallels cannot be equal and on opposite sides of the equator
  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
    return;
  }

  var temp = this.b / this.a;
  this.e = Math.sqrt(1 - temp * temp);

  var sin1 = Math.sin(this.lat1);
  var cos1 = Math.cos(this.lat1);
  var ms1 = msfnz(this.e, sin1, cos1);
  var ts1 = tsfnz(this.e, this.lat1, sin1);

  var sin2 = Math.sin(this.lat2);
  var cos2 = Math.cos(this.lat2);
  var ms2 = msfnz(this.e, sin2, cos2);
  var ts2 = tsfnz(this.e, this.lat2, sin2);

  var ts0 = tsfnz(this.e, this.lat0, Math.sin(this.lat0));

  if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
    this.ns = Math.log(ms1 / ms2) / Math.log(ts1 / ts2);
  }
  else {
    this.ns = sin1;
  }
  if (isNaN(this.ns)) {
    this.ns = sin1;
  }
  this.f0 = ms1 / (this.ns * Math.pow(ts1, this.ns));
  this.rh = this.a * this.f0 * Math.pow(ts0, this.ns);
  if (!this.title) {
    this.title = "Lambert Conformal Conic";
  }
};


// Lambert Conformal conic forward equations--mapping lat,long to x,y
// -----------------------------------------------------------------
exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  // singular cases :
  if (Math.abs(2 * Math.abs(lat) - Math.PI) <= EPSLN) {
    lat = sign(lat) * (HALF_PI - 2 * EPSLN);
  }

  var con = Math.abs(Math.abs(lat) - HALF_PI);
  var ts, rh1;
  if (con > EPSLN) {
    ts = tsfnz(this.e, lat, Math.sin(lat));
    rh1 = this.a * this.f0 * Math.pow(ts, this.ns);
  }
  else {
    con = lat * this.ns;
    if (con <= 0) {
      return null;
    }
    rh1 = 0;
  }
  var theta = this.ns * adjust_lon(lon - this.long0);
  p.x = this.k0 * (rh1 * Math.sin(theta)) + this.x0;
  p.y = this.k0 * (this.rh - rh1 * Math.cos(theta)) + this.y0;

  return p;
};

// Lambert Conformal Conic inverse equations--mapping x,y to lat/long
// -----------------------------------------------------------------
exports.inverse = function(p) {

  var rh1, con, ts;
  var lat, lon;
  var x = (p.x - this.x0) / this.k0;
  var y = (this.rh - (p.y - this.y0) / this.k0);
  if (this.ns > 0) {
    rh1 = Math.sqrt(x * x + y * y);
    con = 1;
  }
  else {
    rh1 = -Math.sqrt(x * x + y * y);
    con = -1;
  }
  var theta = 0;
  if (rh1 !== 0) {
    theta = Math.atan2((con * x), (con * y));
  }
  if ((rh1 !== 0) || (this.ns > 0)) {
    con = 1 / this.ns;
    ts = Math.pow((rh1 / (this.a * this.f0)), con);
    lat = phi2z(this.e, ts);
    if (lat === -9999) {
      return null;
    }
  }
  else {
    lat = -HALF_PI;
  }
  lon = adjust_lon(theta / this.ns + this.long0);

  p.x = lon;
  p.y = lat;
  return p;
};

exports.names = ["Lambert Tangential Conformal Conic Projection", "Lambert_Conformal_Conic", "Lambert_Conformal_Conic_2SP", "lcc"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/msfnz":"proj4/lib/common/msfnz","../common/phi2z":"proj4/lib/common/phi2z","../common/sign":"proj4/lib/common/sign","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/longlat":[function(require,module,exports){
exports.init = function() {
  //no-op for longlat
};

function identity(pt) {
  return pt;
}
exports.forward = identity;
exports.inverse = identity;
exports.names = ["longlat", "identity"];

},{}],"proj4/lib/projections/merc":[function(require,module,exports){
var msfnz = require('../common/msfnz');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var R2D = 57.29577951308232088;
var adjust_lon = require('../common/adjust_lon');
var FORTPI = Math.PI/4;
var tsfnz = require('../common/tsfnz');
var phi2z = require('../common/phi2z');
exports.init = function() {
  var con = this.b / this.a;
  this.es = 1 - con * con;
  if(!('x0' in this)){
    this.x0 = 0;
  }
  if(!('y0' in this)){
    this.y0 = 0;
  }
  this.e = Math.sqrt(this.es);
  if (this.lat_ts) {
    if (this.sphere) {
      this.k0 = Math.cos(this.lat_ts);
    }
    else {
      this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
    }
  }
  else {
    if (!this.k0) {
      if (this.k) {
        this.k0 = this.k;
      }
      else {
        this.k0 = 1;
      }
    }
  }
};

/* Mercator forward equations--mapping lat,long to x,y
  --------------------------------------------------*/

exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  // convert to radians
  if (lat * R2D > 90 && lat * R2D < -90 && lon * R2D > 180 && lon * R2D < -180) {
    return null;
  }

  var x, y;
  if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
    return null;
  }
  else {
    if (this.sphere) {
      x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
      y = this.y0 + this.a * this.k0 * Math.log(Math.tan(FORTPI + 0.5 * lat));
    }
    else {
      var sinphi = Math.sin(lat);
      var ts = tsfnz(this.e, lat, sinphi);
      x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
      y = this.y0 - this.a * this.k0 * Math.log(ts);
    }
    p.x = x;
    p.y = y;
    return p;
  }
};


/* Mercator inverse equations--mapping x,y to lat/long
  --------------------------------------------------*/
exports.inverse = function(p) {

  var x = p.x - this.x0;
  var y = p.y - this.y0;
  var lon, lat;

  if (this.sphere) {
    lat = HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
  }
  else {
    var ts = Math.exp(-y / (this.a * this.k0));
    lat = phi2z(this.e, ts);
    if (lat === -9999) {
      return null;
    }
  }
  lon = adjust_lon(this.long0 + x / (this.a * this.k0));

  p.x = lon;
  p.y = lat;
  return p;
};

exports.names = ["Mercator", "Popular Visualisation Pseudo Mercator", "Mercator_1SP", "Mercator_Auxiliary_Sphere", "merc"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/msfnz":"proj4/lib/common/msfnz","../common/phi2z":"proj4/lib/common/phi2z","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/mill":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
/*
  reference
    "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
    The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
  */


/* Initialize the Miller Cylindrical projection
  -------------------------------------------*/
exports.init = function() {
  //no-op
};


/* Miller Cylindrical forward equations--mapping lat,long to x,y
    ------------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  /* Forward equations
      -----------------*/
  var dlon = adjust_lon(lon - this.long0);
  var x = this.x0 + this.a * dlon;
  var y = this.y0 + this.a * Math.log(Math.tan((Math.PI / 4) + (lat / 2.5))) * 1.25;

  p.x = x;
  p.y = y;
  return p;
};

/* Miller Cylindrical inverse equations--mapping x,y to lat/long
    ------------------------------------------------------------*/
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;

  var lon = adjust_lon(this.long0 + p.x / this.a);
  var lat = 2.5 * (Math.atan(Math.exp(0.8 * p.y / this.a)) - Math.PI / 4);

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Miller_Cylindrical", "mill"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/moll":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var EPSLN = 1.0e-10;
exports.init = function() {};

/* Mollweide forward equations--mapping lat,long to x,y
    ----------------------------------------------------*/
exports.forward = function(p) {

  /* Forward equations
      -----------------*/
  var lon = p.x;
  var lat = p.y;

  var delta_lon = adjust_lon(lon - this.long0);
  var theta = lat;
  var con = Math.PI * Math.sin(lat);

  /* Iterate using the Newton-Raphson method to find theta
      -----------------------------------------------------*/
  for (var i = 0; true; i++) {
    var delta_theta = -(theta + Math.sin(theta) - con) / (1 + Math.cos(theta));
    theta += delta_theta;
    if (Math.abs(delta_theta) < EPSLN) {
      break;
    }
  }
  theta /= 2;

  /* If the latitude is 90 deg, force the x coordinate to be "0 + false easting"
       this is done here because of precision problems with "cos(theta)"
       --------------------------------------------------------------------------*/
  if (Math.PI / 2 - Math.abs(lat) < EPSLN) {
    delta_lon = 0;
  }
  var x = 0.900316316158 * this.a * delta_lon * Math.cos(theta) + this.x0;
  var y = 1.4142135623731 * this.a * Math.sin(theta) + this.y0;

  p.x = x;
  p.y = y;
  return p;
};

exports.inverse = function(p) {
  var theta;
  var arg;

  /* Inverse equations
      -----------------*/
  p.x -= this.x0;
  p.y -= this.y0;
  arg = p.y / (1.4142135623731 * this.a);

  /* Because of division by zero problems, 'arg' can not be 1.  Therefore
       a number very close to one is used instead.
       -------------------------------------------------------------------*/
  if (Math.abs(arg) > 0.999999999999) {
    arg = 0.999999999999;
  }
  theta = Math.asin(arg);
  var lon = adjust_lon(this.long0 + (p.x / (0.900316316158 * this.a * Math.cos(theta))));
  if (lon < (-Math.PI)) {
    lon = -Math.PI;
  }
  if (lon > Math.PI) {
    lon = Math.PI;
  }
  arg = (2 * theta + Math.sin(2 * theta)) / Math.PI;
  if (Math.abs(arg) > 1) {
    arg = 1;
  }
  var lat = Math.asin(arg);

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Mollweide", "moll"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon"}],"proj4/lib/projections/nzmg":[function(require,module,exports){
var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
/*
  reference
    Department of Land and Survey Technical Circular 1973/32
      http://www.linz.govt.nz/docs/miscellaneous/nz-map-definition.pdf
    OSG Technical Report 4.1
      http://www.linz.govt.nz/docs/miscellaneous/nzmg.pdf
  */

/**
 * iterations: Number of iterations to refine inverse transform.
 *     0 -> km accuracy
 *     1 -> m accuracy -- suitable for most mapping applications
 *     2 -> mm accuracy
 */
exports.iterations = 1;

exports.init = function() {
  this.A = [];
  this.A[1] = 0.6399175073;
  this.A[2] = -0.1358797613;
  this.A[3] = 0.063294409;
  this.A[4] = -0.02526853;
  this.A[5] = 0.0117879;
  this.A[6] = -0.0055161;
  this.A[7] = 0.0026906;
  this.A[8] = -0.001333;
  this.A[9] = 0.00067;
  this.A[10] = -0.00034;

  this.B_re = [];
  this.B_im = [];
  this.B_re[1] = 0.7557853228;
  this.B_im[1] = 0;
  this.B_re[2] = 0.249204646;
  this.B_im[2] = 0.003371507;
  this.B_re[3] = -0.001541739;
  this.B_im[3] = 0.041058560;
  this.B_re[4] = -0.10162907;
  this.B_im[4] = 0.01727609;
  this.B_re[5] = -0.26623489;
  this.B_im[5] = -0.36249218;
  this.B_re[6] = -0.6870983;
  this.B_im[6] = -1.1651967;

  this.C_re = [];
  this.C_im = [];
  this.C_re[1] = 1.3231270439;
  this.C_im[1] = 0;
  this.C_re[2] = -0.577245789;
  this.C_im[2] = -0.007809598;
  this.C_re[3] = 0.508307513;
  this.C_im[3] = -0.112208952;
  this.C_re[4] = -0.15094762;
  this.C_im[4] = 0.18200602;
  this.C_re[5] = 1.01418179;
  this.C_im[5] = 1.64497696;
  this.C_re[6] = 1.9660549;
  this.C_im[6] = 2.5127645;

  this.D = [];
  this.D[1] = 1.5627014243;
  this.D[2] = 0.5185406398;
  this.D[3] = -0.03333098;
  this.D[4] = -0.1052906;
  this.D[5] = -0.0368594;
  this.D[6] = 0.007317;
  this.D[7] = 0.01220;
  this.D[8] = 0.00394;
  this.D[9] = -0.0013;
};

/**
    New Zealand Map Grid Forward  - long/lat to x/y
    long/lat in radians
  */
exports.forward = function(p) {
  var n;
  var lon = p.x;
  var lat = p.y;

  var delta_lat = lat - this.lat0;
  var delta_lon = lon - this.long0;

  // 1. Calculate d_phi and d_psi    ...                          // and d_lambda
  // For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians.
  var d_phi = delta_lat / SEC_TO_RAD * 1E-5;
  var d_lambda = delta_lon;
  var d_phi_n = 1; // d_phi^0

  var d_psi = 0;
  for (n = 1; n <= 10; n++) {
    d_phi_n = d_phi_n * d_phi;
    d_psi = d_psi + this.A[n] * d_phi_n;
  }

  // 2. Calculate theta
  var th_re = d_psi;
  var th_im = d_lambda;

  // 3. Calculate z
  var th_n_re = 1;
  var th_n_im = 0; // theta^0
  var th_n_re1;
  var th_n_im1;

  var z_re = 0;
  var z_im = 0;
  for (n = 1; n <= 6; n++) {
    th_n_re1 = th_n_re * th_re - th_n_im * th_im;
    th_n_im1 = th_n_im * th_re + th_n_re * th_im;
    th_n_re = th_n_re1;
    th_n_im = th_n_im1;
    z_re = z_re + this.B_re[n] * th_n_re - this.B_im[n] * th_n_im;
    z_im = z_im + this.B_im[n] * th_n_re + this.B_re[n] * th_n_im;
  }

  // 4. Calculate easting and northing
  p.x = (z_im * this.a) + this.x0;
  p.y = (z_re * this.a) + this.y0;

  return p;
};


/**
    New Zealand Map Grid Inverse  -  x/y to long/lat
  */
exports.inverse = function(p) {
  var n;
  var x = p.x;
  var y = p.y;

  var delta_x = x - this.x0;
  var delta_y = y - this.y0;

  // 1. Calculate z
  var z_re = delta_y / this.a;
  var z_im = delta_x / this.a;

  // 2a. Calculate theta - first approximation gives km accuracy
  var z_n_re = 1;
  var z_n_im = 0; // z^0
  var z_n_re1;
  var z_n_im1;

  var th_re = 0;
  var th_im = 0;
  for (n = 1; n <= 6; n++) {
    z_n_re1 = z_n_re * z_re - z_n_im * z_im;
    z_n_im1 = z_n_im * z_re + z_n_re * z_im;
    z_n_re = z_n_re1;
    z_n_im = z_n_im1;
    th_re = th_re + this.C_re[n] * z_n_re - this.C_im[n] * z_n_im;
    th_im = th_im + this.C_im[n] * z_n_re + this.C_re[n] * z_n_im;
  }

  // 2b. Iterate to refine the accuracy of the calculation
  //        0 iterations gives km accuracy
  //        1 iteration gives m accuracy -- good enough for most mapping applications
  //        2 iterations bives mm accuracy
  for (var i = 0; i < this.iterations; i++) {
    var th_n_re = th_re;
    var th_n_im = th_im;
    var th_n_re1;
    var th_n_im1;

    var num_re = z_re;
    var num_im = z_im;
    for (n = 2; n <= 6; n++) {
      th_n_re1 = th_n_re * th_re - th_n_im * th_im;
      th_n_im1 = th_n_im * th_re + th_n_re * th_im;
      th_n_re = th_n_re1;
      th_n_im = th_n_im1;
      num_re = num_re + (n - 1) * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
      num_im = num_im + (n - 1) * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
    }

    th_n_re = 1;
    th_n_im = 0;
    var den_re = this.B_re[1];
    var den_im = this.B_im[1];
    for (n = 2; n <= 6; n++) {
      th_n_re1 = th_n_re * th_re - th_n_im * th_im;
      th_n_im1 = th_n_im * th_re + th_n_re * th_im;
      th_n_re = th_n_re1;
      th_n_im = th_n_im1;
      den_re = den_re + n * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
      den_im = den_im + n * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
    }

    // Complex division
    var den2 = den_re * den_re + den_im * den_im;
    th_re = (num_re * den_re + num_im * den_im) / den2;
    th_im = (num_im * den_re - num_re * den_im) / den2;
  }

  // 3. Calculate d_phi              ...                                    // and d_lambda
  var d_psi = th_re;
  var d_lambda = th_im;
  var d_psi_n = 1; // d_psi^0

  var d_phi = 0;
  for (n = 1; n <= 9; n++) {
    d_psi_n = d_psi_n * d_psi;
    d_phi = d_phi + this.D[n] * d_psi_n;
  }

  // 4. Calculate latitude and longitude
  // d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians.
  var lat = this.lat0 + (d_phi * SEC_TO_RAD * 1E5);
  var lon = this.long0 + d_lambda;

  p.x = lon;
  p.y = lat;

  return p;
};
exports.names = ["New_Zealand_Map_Grid", "nzmg"];
},{}],"proj4/lib/projections/omerc":[function(require,module,exports){
var tsfnz = require('../common/tsfnz');
var adjust_lon = require('../common/adjust_lon');
var phi2z = require('../common/phi2z');
var HALF_PI = Math.PI/2;
var FORTPI = Math.PI/4;
var EPSLN = 1.0e-10;

/* Initialize the Oblique Mercator  projection
    ------------------------------------------*/
exports.init = function() {
  this.no_off = this.no_off || false;
  this.no_rot = this.no_rot || false;

  if (isNaN(this.k0)) {
    this.k0 = 1;
  }
  var sinlat = Math.sin(this.lat0);
  var coslat = Math.cos(this.lat0);
  var con = this.e * sinlat;

  this.bl = Math.sqrt(1 + this.es / (1 - this.es) * Math.pow(coslat, 4));
  this.al = this.a * this.bl * this.k0 * Math.sqrt(1 - this.es) / (1 - con * con);
  var t0 = tsfnz(this.e, this.lat0, sinlat);
  var dl = this.bl / coslat * Math.sqrt((1 - this.es) / (1 - con * con));
  if (dl * dl < 1) {
    dl = 1;
  }
  var fl;
  var gl;
  if (!isNaN(this.longc)) {
    //Central point and azimuth method

    if (this.lat0 >= 0) {
      fl = dl + Math.sqrt(dl * dl - 1);
    }
    else {
      fl = dl - Math.sqrt(dl * dl - 1);
    }
    this.el = fl * Math.pow(t0, this.bl);
    gl = 0.5 * (fl - 1 / fl);
    this.gamma0 = Math.asin(Math.sin(this.alpha) / dl);
    this.long0 = this.longc - Math.asin(gl * Math.tan(this.gamma0)) / this.bl;

  }
  else {
    //2 points method
    var t1 = tsfnz(this.e, this.lat1, Math.sin(this.lat1));
    var t2 = tsfnz(this.e, this.lat2, Math.sin(this.lat2));
    if (this.lat0 >= 0) {
      this.el = (dl + Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
    }
    else {
      this.el = (dl - Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
    }
    var hl = Math.pow(t1, this.bl);
    var ll = Math.pow(t2, this.bl);
    fl = this.el / hl;
    gl = 0.5 * (fl - 1 / fl);
    var jl = (this.el * this.el - ll * hl) / (this.el * this.el + ll * hl);
    var pl = (ll - hl) / (ll + hl);
    var dlon12 = adjust_lon(this.long1 - this.long2);
    this.long0 = 0.5 * (this.long1 + this.long2) - Math.atan(jl * Math.tan(0.5 * this.bl * (dlon12)) / pl) / this.bl;
    this.long0 = adjust_lon(this.long0);
    var dlon10 = adjust_lon(this.long1 - this.long0);
    this.gamma0 = Math.atan(Math.sin(this.bl * (dlon10)) / gl);
    this.alpha = Math.asin(dl * Math.sin(this.gamma0));
  }

  if (this.no_off) {
    this.uc = 0;
  }
  else {
    if (this.lat0 >= 0) {
      this.uc = this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
    }
    else {
      this.uc = -1 * this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
    }
  }

};


/* Oblique Mercator forward equations--mapping lat,long to x,y
    ----------------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var dlon = adjust_lon(lon - this.long0);
  var us, vs;
  var con;
  if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
    if (lat > 0) {
      con = -1;
    }
    else {
      con = 1;
    }
    vs = this.al / this.bl * Math.log(Math.tan(FORTPI + con * this.gamma0 * 0.5));
    us = -1 * con * HALF_PI * this.al / this.bl;
  }
  else {
    var t = tsfnz(this.e, lat, Math.sin(lat));
    var ql = this.el / Math.pow(t, this.bl);
    var sl = 0.5 * (ql - 1 / ql);
    var tl = 0.5 * (ql + 1 / ql);
    var vl = Math.sin(this.bl * (dlon));
    var ul = (sl * Math.sin(this.gamma0) - vl * Math.cos(this.gamma0)) / tl;
    if (Math.abs(Math.abs(ul) - 1) <= EPSLN) {
      vs = Number.POSITIVE_INFINITY;
    }
    else {
      vs = 0.5 * this.al * Math.log((1 - ul) / (1 + ul)) / this.bl;
    }
    if (Math.abs(Math.cos(this.bl * (dlon))) <= EPSLN) {
      us = this.al * this.bl * (dlon);
    }
    else {
      us = this.al * Math.atan2(sl * Math.cos(this.gamma0) + vl * Math.sin(this.gamma0), Math.cos(this.bl * dlon)) / this.bl;
    }
  }

  if (this.no_rot) {
    p.x = this.x0 + us;
    p.y = this.y0 + vs;
  }
  else {

    us -= this.uc;
    p.x = this.x0 + vs * Math.cos(this.alpha) + us * Math.sin(this.alpha);
    p.y = this.y0 + us * Math.cos(this.alpha) - vs * Math.sin(this.alpha);
  }
  return p;
};

exports.inverse = function(p) {
  var us, vs;
  if (this.no_rot) {
    vs = p.y - this.y0;
    us = p.x - this.x0;
  }
  else {
    vs = (p.x - this.x0) * Math.cos(this.alpha) - (p.y - this.y0) * Math.sin(this.alpha);
    us = (p.y - this.y0) * Math.cos(this.alpha) + (p.x - this.x0) * Math.sin(this.alpha);
    us += this.uc;
  }
  var qp = Math.exp(-1 * this.bl * vs / this.al);
  var sp = 0.5 * (qp - 1 / qp);
  var tp = 0.5 * (qp + 1 / qp);
  var vp = Math.sin(this.bl * us / this.al);
  var up = (vp * Math.cos(this.gamma0) + sp * Math.sin(this.gamma0)) / tp;
  var ts = Math.pow(this.el / Math.sqrt((1 + up) / (1 - up)), 1 / this.bl);
  if (Math.abs(up - 1) < EPSLN) {
    p.x = this.long0;
    p.y = HALF_PI;
  }
  else if (Math.abs(up + 1) < EPSLN) {
    p.x = this.long0;
    p.y = -1 * HALF_PI;
  }
  else {
    p.y = phi2z(this.e, ts);
    p.x = adjust_lon(this.long0 - Math.atan2(sp * Math.cos(this.gamma0) - vp * Math.sin(this.gamma0), Math.cos(this.bl * us / this.al)) / this.bl);
  }
  return p;
};

exports.names = ["Hotine_Oblique_Mercator", "Hotine Oblique Mercator", "Hotine_Oblique_Mercator_Azimuth_Natural_Origin", "Hotine_Oblique_Mercator_Azimuth_Center", "omerc"];
},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/phi2z":"proj4/lib/common/phi2z","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/poly":[function(require,module,exports){
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var mlfn = require('../common/mlfn');
var EPSLN = 1.0e-10;
var gN = require('../common/gN');
var MAX_ITER = 20;
exports.init = function() {
  /* Place parameters in static storage for common use
      -------------------------------------------------*/
  this.temp = this.b / this.a;
  this.es = 1 - Math.pow(this.temp, 2); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles
  this.e = Math.sqrt(this.es);
  this.e0 = e0fn(this.es);
  this.e1 = e1fn(this.es);
  this.e2 = e2fn(this.es);
  this.e3 = e3fn(this.es);
  this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); //si que des zeros le calcul ne se fait pas
};


/* Polyconic forward equations--mapping lat,long to x,y
    ---------------------------------------------------*/
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var x, y, el;
  var dlon = adjust_lon(lon - this.long0);
  el = dlon * Math.sin(lat);
  if (this.sphere) {
    if (Math.abs(lat) <= EPSLN) {
      x = this.a * dlon;
      y = -1 * this.a * this.lat0;
    }
    else {
      x = this.a * Math.sin(el) / Math.tan(lat);
      y = this.a * (adjust_lat(lat - this.lat0) + (1 - Math.cos(el)) / Math.tan(lat));
    }
  }
  else {
    if (Math.abs(lat) <= EPSLN) {
      x = this.a * dlon;
      y = -1 * this.ml0;
    }
    else {
      var nl = gN(this.a, this.e, Math.sin(lat)) / Math.tan(lat);
      x = nl * Math.sin(el);
      y = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat) - this.ml0 + nl * (1 - Math.cos(el));
    }

  }
  p.x = x + this.x0;
  p.y = y + this.y0;
  return p;
};


/* Inverse equations
  -----------------*/
exports.inverse = function(p) {
  var lon, lat, x, y, i;
  var al, bl;
  var phi, dphi;
  x = p.x - this.x0;
  y = p.y - this.y0;

  if (this.sphere) {
    if (Math.abs(y + this.a * this.lat0) <= EPSLN) {
      lon = adjust_lon(x / this.a + this.long0);
      lat = 0;
    }
    else {
      al = this.lat0 + y / this.a;
      bl = x * x / this.a / this.a + al * al;
      phi = al;
      var tanphi;
      for (i = MAX_ITER; i; --i) {
        tanphi = Math.tan(phi);
        dphi = -1 * (al * (phi * tanphi + 1) - phi - 0.5 * (phi * phi + bl) * tanphi) / ((phi - al) / tanphi - 1);
        phi += dphi;
        if (Math.abs(dphi) <= EPSLN) {
          lat = phi;
          break;
        }
      }
      lon = adjust_lon(this.long0 + (Math.asin(x * Math.tan(phi) / this.a)) / Math.sin(lat));
    }
  }
  else {
    if (Math.abs(y + this.ml0) <= EPSLN) {
      lat = 0;
      lon = adjust_lon(this.long0 + x / this.a);
    }
    else {

      al = (this.ml0 + y) / this.a;
      bl = x * x / this.a / this.a + al * al;
      phi = al;
      var cl, mln, mlnp, ma;
      var con;
      for (i = MAX_ITER; i; --i) {
        con = this.e * Math.sin(phi);
        cl = Math.sqrt(1 - con * con) * Math.tan(phi);
        mln = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);
        mlnp = this.e0 - 2 * this.e1 * Math.cos(2 * phi) + 4 * this.e2 * Math.cos(4 * phi) - 6 * this.e3 * Math.cos(6 * phi);
        ma = mln / this.a;
        dphi = (al * (cl * ma + 1) - ma - 0.5 * cl * (ma * ma + bl)) / (this.es * Math.sin(2 * phi) * (ma * ma + bl - 2 * al * ma) / (4 * cl) + (al - ma) * (cl * mlnp - 2 / Math.sin(2 * phi)) - mlnp);
        phi -= dphi;
        if (Math.abs(dphi) <= EPSLN) {
          lat = phi;
          break;
        }
      }

      //lat=phi4z(this.e,this.e0,this.e1,this.e2,this.e3,al,bl,0,0);
      cl = Math.sqrt(1 - this.es * Math.pow(Math.sin(lat), 2)) * Math.tan(lat);
      lon = adjust_lon(this.long0 + Math.asin(x * cl / this.a) / Math.sin(lat));
    }
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Polyconic", "poly"];
},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/gN":"proj4/lib/common/gN","../common/mlfn":"proj4/lib/common/mlfn"}],"proj4/lib/projections/sinu":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var adjust_lat = require('../common/adjust_lat');
var pj_enfn = require('../common/pj_enfn');
var MAX_ITER = 20;
var pj_mlfn = require('../common/pj_mlfn');
var pj_inv_mlfn = require('../common/pj_inv_mlfn');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var asinz = require('../common/asinz');
exports.init = function() {
  /* Place parameters in static storage for common use
    -------------------------------------------------*/


  if (!this.sphere) {
    this.en = pj_enfn(this.es);
  }
  else {
    this.n = 1;
    this.m = 0;
    this.es = 0;
    this.C_y = Math.sqrt((this.m + 1) / this.n);
    this.C_x = this.C_y / (this.m + 1);
  }

};

/* Sinusoidal forward equations--mapping lat,long to x,y
  -----------------------------------------------------*/
exports.forward = function(p) {
  var x, y;
  var lon = p.x;
  var lat = p.y;
  /* Forward equations
    -----------------*/
  lon = adjust_lon(lon - this.long0);

  if (this.sphere) {
    if (!this.m) {
      lat = this.n !== 1 ? Math.asin(this.n * Math.sin(lat)) : lat;
    }
    else {
      var k = this.n * Math.sin(lat);
      for (var i = MAX_ITER; i; --i) {
        var V = (this.m * lat + Math.sin(lat) - k) / (this.m + Math.cos(lat));
        lat -= V;
        if (Math.abs(V) < EPSLN) {
          break;
        }
      }
    }
    x = this.a * this.C_x * lon * (this.m + Math.cos(lat));
    y = this.a * this.C_y * lat;

  }
  else {

    var s = Math.sin(lat);
    var c = Math.cos(lat);
    y = this.a * pj_mlfn(lat, s, c, this.en);
    x = this.a * lon * c / Math.sqrt(1 - this.es * s * s);
  }

  p.x = x;
  p.y = y;
  return p;
};

exports.inverse = function(p) {
  var lat, temp, lon, s;

  p.x -= this.x0;
  lon = p.x / this.a;
  p.y -= this.y0;
  lat = p.y / this.a;

  if (this.sphere) {
    lat /= this.C_y;
    lon = lon / (this.C_x * (this.m + Math.cos(lat)));
    if (this.m) {
      lat = asinz((this.m * lat + Math.sin(lat)) / this.n);
    }
    else if (this.n !== 1) {
      lat = asinz(Math.sin(lat) / this.n);
    }
    lon = adjust_lon(lon + this.long0);
    lat = adjust_lat(lat);
  }
  else {
    lat = pj_inv_mlfn(p.y / this.a, this.es, this.en);
    s = Math.abs(lat);
    if (s < HALF_PI) {
      s = Math.sin(lat);
      temp = this.long0 + p.x * Math.sqrt(1 - this.es * s * s) / (this.a * Math.cos(lat));
      //temp = this.long0 + p.x / (this.a * Math.cos(lat));
      lon = adjust_lon(temp);
    }
    else if ((s - EPSLN) < HALF_PI) {
      lon = this.long0;
    }
  }
  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Sinusoidal", "sinu"];
},{"../common/adjust_lat":"proj4/lib/common/adjust_lat","../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/pj_enfn":"proj4/lib/common/pj_enfn","../common/pj_inv_mlfn":"proj4/lib/common/pj_inv_mlfn","../common/pj_mlfn":"proj4/lib/common/pj_mlfn"}],"proj4/lib/projections/somerc":[function(require,module,exports){
/*
  references:
    Formules et constantes pour le Calcul pour la
    projection cylindrique conforme à axe oblique et pour la transformation entre
    des systèmes de référence.
    http://www.swisstopo.admin.ch/internet/swisstopo/fr/home/topics/survey/sys/refsys/switzerland.parsysrelated1.31216.downloadList.77004.DownloadFile.tmp/swissprojectionfr.pdf
  */
exports.init = function() {
  var phy0 = this.lat0;
  this.lambda0 = this.long0;
  var sinPhy0 = Math.sin(phy0);
  var semiMajorAxis = this.a;
  var invF = this.rf;
  var flattening = 1 / invF;
  var e2 = 2 * flattening - Math.pow(flattening, 2);
  var e = this.e = Math.sqrt(e2);
  this.R = this.k0 * semiMajorAxis * Math.sqrt(1 - e2) / (1 - e2 * Math.pow(sinPhy0, 2));
  this.alpha = Math.sqrt(1 + e2 / (1 - e2) * Math.pow(Math.cos(phy0), 4));
  this.b0 = Math.asin(sinPhy0 / this.alpha);
  var k1 = Math.log(Math.tan(Math.PI / 4 + this.b0 / 2));
  var k2 = Math.log(Math.tan(Math.PI / 4 + phy0 / 2));
  var k3 = Math.log((1 + e * sinPhy0) / (1 - e * sinPhy0));
  this.K = k1 - this.alpha * k2 + this.alpha * e / 2 * k3;
};


exports.forward = function(p) {
  var Sa1 = Math.log(Math.tan(Math.PI / 4 - p.y / 2));
  var Sa2 = this.e / 2 * Math.log((1 + this.e * Math.sin(p.y)) / (1 - this.e * Math.sin(p.y)));
  var S = -this.alpha * (Sa1 + Sa2) + this.K;

  // spheric latitude
  var b = 2 * (Math.atan(Math.exp(S)) - Math.PI / 4);

  // spheric longitude
  var I = this.alpha * (p.x - this.lambda0);

  // psoeudo equatorial rotation
  var rotI = Math.atan(Math.sin(I) / (Math.sin(this.b0) * Math.tan(b) + Math.cos(this.b0) * Math.cos(I)));

  var rotB = Math.asin(Math.cos(this.b0) * Math.sin(b) - Math.sin(this.b0) * Math.cos(b) * Math.cos(I));

  p.y = this.R / 2 * Math.log((1 + Math.sin(rotB)) / (1 - Math.sin(rotB))) + this.y0;
  p.x = this.R * rotI + this.x0;
  return p;
};

exports.inverse = function(p) {
  var Y = p.x - this.x0;
  var X = p.y - this.y0;

  var rotI = Y / this.R;
  var rotB = 2 * (Math.atan(Math.exp(X / this.R)) - Math.PI / 4);

  var b = Math.asin(Math.cos(this.b0) * Math.sin(rotB) + Math.sin(this.b0) * Math.cos(rotB) * Math.cos(rotI));
  var I = Math.atan(Math.sin(rotI) / (Math.cos(this.b0) * Math.cos(rotI) - Math.sin(this.b0) * Math.tan(rotB)));

  var lambda = this.lambda0 + I / this.alpha;

  var S = 0;
  var phy = b;
  var prevPhy = -1000;
  var iteration = 0;
  while (Math.abs(phy - prevPhy) > 0.0000001) {
    if (++iteration > 20) {
      //...reportError("omercFwdInfinity");
      return;
    }
    //S = Math.log(Math.tan(Math.PI / 4 + phy / 2));
    S = 1 / this.alpha * (Math.log(Math.tan(Math.PI / 4 + b / 2)) - this.K) + this.e * Math.log(Math.tan(Math.PI / 4 + Math.asin(this.e * Math.sin(phy)) / 2));
    prevPhy = phy;
    phy = 2 * Math.atan(Math.exp(S)) - Math.PI / 2;
  }

  p.x = lambda;
  p.y = phy;
  return p;
};

exports.names = ["somerc"];

},{}],"proj4/lib/projections/stere":[function(require,module,exports){
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var sign = require('../common/sign');
var msfnz = require('../common/msfnz');
var tsfnz = require('../common/tsfnz');
var phi2z = require('../common/phi2z');
var adjust_lon = require('../common/adjust_lon');
exports.ssfn_ = function(phit, sinphi, eccen) {
  sinphi *= eccen;
  return (Math.tan(0.5 * (HALF_PI + phit)) * Math.pow((1 - sinphi) / (1 + sinphi), 0.5 * eccen));
};

exports.init = function() {
  this.coslat0 = Math.cos(this.lat0);
  this.sinlat0 = Math.sin(this.lat0);
  if (this.sphere) {
    if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
      this.k0 = 0.5 * (1 + sign(this.lat0) * Math.sin(this.lat_ts));
    }
  }
  else {
    if (Math.abs(this.coslat0) <= EPSLN) {
      if (this.lat0 > 0) {
        //North pole
        //trace('stere:north pole');
        this.con = 1;
      }
      else {
        //South pole
        //trace('stere:south pole');
        this.con = -1;
      }
    }
    this.cons = Math.sqrt(Math.pow(1 + this.e, 1 + this.e) * Math.pow(1 - this.e, 1 - this.e));
    if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
      this.k0 = 0.5 * this.cons * msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)) / tsfnz(this.e, this.con * this.lat_ts, this.con * Math.sin(this.lat_ts));
    }
    this.ms1 = msfnz(this.e, this.sinlat0, this.coslat0);
    this.X0 = 2 * Math.atan(this.ssfn_(this.lat0, this.sinlat0, this.e)) - HALF_PI;
    this.cosX0 = Math.cos(this.X0);
    this.sinX0 = Math.sin(this.X0);
  }
};

// Stereographic forward equations--mapping lat,long to x,y
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;
  var sinlat = Math.sin(lat);
  var coslat = Math.cos(lat);
  var A, X, sinX, cosX, ts, rh;
  var dlon = adjust_lon(lon - this.long0);

  if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= EPSLN && Math.abs(lat + this.lat0) <= EPSLN) {
    //case of the origine point
    //trace('stere:this is the origin point');
    p.x = NaN;
    p.y = NaN;
    return p;
  }
  if (this.sphere) {
    //trace('stere:sphere case');
    A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon));
    p.x = this.a * A * coslat * Math.sin(dlon) + this.x0;
    p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0;
    return p;
  }
  else {
    X = 2 * Math.atan(this.ssfn_(lat, sinlat, this.e)) - HALF_PI;
    cosX = Math.cos(X);
    sinX = Math.sin(X);
    if (Math.abs(this.coslat0) <= EPSLN) {
      ts = tsfnz(this.e, lat * this.con, this.con * sinlat);
      rh = 2 * this.a * this.k0 * ts / this.cons;
      p.x = this.x0 + rh * Math.sin(lon - this.long0);
      p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0);
      //trace(p.toString());
      return p;
    }
    else if (Math.abs(this.sinlat0) < EPSLN) {
      //Eq
      //trace('stere:equateur');
      A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon));
      p.y = A * sinX;
    }
    else {
      //other case
      //trace('stere:normal case');
      A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon)));
      p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0;
    }
    p.x = A * cosX * Math.sin(dlon) + this.x0;
  }
  //trace(p.toString());
  return p;
};


//* Stereographic inverse equations--mapping x,y to lat/long
exports.inverse = function(p) {
  p.x -= this.x0;
  p.y -= this.y0;
  var lon, lat, ts, ce, Chi;
  var rh = Math.sqrt(p.x * p.x + p.y * p.y);
  if (this.sphere) {
    var c = 2 * Math.atan(rh / (0.5 * this.a * this.k0));
    lon = this.long0;
    lat = this.lat0;
    if (rh <= EPSLN) {
      p.x = lon;
      p.y = lat;
      return p;
    }
    lat = Math.asin(Math.cos(c) * this.sinlat0 + p.y * Math.sin(c) * this.coslat0 / rh);
    if (Math.abs(this.coslat0) < EPSLN) {
      if (this.lat0 > 0) {
        lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
      }
      else {
        lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
      }
    }
    else {
      lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(c), rh * this.coslat0 * Math.cos(c) - p.y * this.sinlat0 * Math.sin(c)));
    }
    p.x = lon;
    p.y = lat;
    return p;
  }
  else {
    if (Math.abs(this.coslat0) <= EPSLN) {
      if (rh <= EPSLN) {
        lat = this.lat0;
        lon = this.long0;
        p.x = lon;
        p.y = lat;
        //trace(p.toString());
        return p;
      }
      p.x *= this.con;
      p.y *= this.con;
      ts = rh * this.cons / (2 * this.a * this.k0);
      lat = this.con * phi2z(this.e, ts);
      lon = this.con * adjust_lon(this.con * this.long0 + Math.atan2(p.x, - 1 * p.y));
    }
    else {
      ce = 2 * Math.atan(rh * this.cosX0 / (2 * this.a * this.k0 * this.ms1));
      lon = this.long0;
      if (rh <= EPSLN) {
        Chi = this.X0;
      }
      else {
        Chi = Math.asin(Math.cos(ce) * this.sinX0 + p.y * Math.sin(ce) * this.cosX0 / rh);
        lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(ce), rh * this.cosX0 * Math.cos(ce) - p.y * this.sinX0 * Math.sin(ce)));
      }
      lat = -1 * phi2z(this.e, Math.tan(0.5 * (HALF_PI + Chi)));
    }
  }
  p.x = lon;
  p.y = lat;

  //trace(p.toString());
  return p;

};
exports.names = ["stere", "Stereographic_South_Pole", "Polar Stereographic (variant B)"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/msfnz":"proj4/lib/common/msfnz","../common/phi2z":"proj4/lib/common/phi2z","../common/sign":"proj4/lib/common/sign","../common/tsfnz":"proj4/lib/common/tsfnz"}],"proj4/lib/projections/sterea":[function(require,module,exports){
var gauss = require('./gauss');
var adjust_lon = require('../common/adjust_lon');
exports.init = function() {
  gauss.init.apply(this);
  if (!this.rc) {
    return;
  }
  this.sinc0 = Math.sin(this.phic0);
  this.cosc0 = Math.cos(this.phic0);
  this.R2 = 2 * this.rc;
  if (!this.title) {
    this.title = "Oblique Stereographic Alternative";
  }
};

exports.forward = function(p) {
  var sinc, cosc, cosl, k;
  p.x = adjust_lon(p.x - this.long0);
  gauss.forward.apply(this, [p]);
  sinc = Math.sin(p.y);
  cosc = Math.cos(p.y);
  cosl = Math.cos(p.x);
  k = this.k0 * this.R2 / (1 + this.sinc0 * sinc + this.cosc0 * cosc * cosl);
  p.x = k * cosc * Math.sin(p.x);
  p.y = k * (this.cosc0 * sinc - this.sinc0 * cosc * cosl);
  p.x = this.a * p.x + this.x0;
  p.y = this.a * p.y + this.y0;
  return p;
};

exports.inverse = function(p) {
  var sinc, cosc, lon, lat, rho;
  p.x = (p.x - this.x0) / this.a;
  p.y = (p.y - this.y0) / this.a;

  p.x /= this.k0;
  p.y /= this.k0;
  if ((rho = Math.sqrt(p.x * p.x + p.y * p.y))) {
    var c = 2 * Math.atan2(rho, this.R2);
    sinc = Math.sin(c);
    cosc = Math.cos(c);
    lat = Math.asin(cosc * this.sinc0 + p.y * sinc * this.cosc0 / rho);
    lon = Math.atan2(p.x * sinc, rho * this.cosc0 * cosc - p.y * this.sinc0 * sinc);
  }
  else {
    lat = this.phic0;
    lon = 0;
  }

  p.x = lon;
  p.y = lat;
  gauss.inverse.apply(this, [p]);
  p.x = adjust_lon(p.x + this.long0);
  return p;
};

exports.names = ["Stereographic_North_Pole", "Oblique_Stereographic", "Polar_Stereographic", "sterea","Oblique Stereographic Alternative"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","./gauss":"proj4/lib/projections/gauss"}],"proj4/lib/projections/tmerc":[function(require,module,exports){
var e0fn = require('../common/e0fn');
var e1fn = require('../common/e1fn');
var e2fn = require('../common/e2fn');
var e3fn = require('../common/e3fn');
var mlfn = require('../common/mlfn');
var adjust_lon = require('../common/adjust_lon');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var sign = require('../common/sign');
var asinz = require('../common/asinz');

exports.init = function() {
  this.e0 = e0fn(this.es);
  this.e1 = e1fn(this.es);
  this.e2 = e2fn(this.es);
  this.e3 = e3fn(this.es);
  this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
};

/**
    Transverse Mercator Forward  - long/lat to x/y
    long/lat in radians
  */
exports.forward = function(p) {
  var lon = p.x;
  var lat = p.y;

  var delta_lon = adjust_lon(lon - this.long0);
  var con;
  var x, y;
  var sin_phi = Math.sin(lat);
  var cos_phi = Math.cos(lat);

  if (this.sphere) {
    var b = cos_phi * Math.sin(delta_lon);
    if ((Math.abs(Math.abs(b) - 1)) < 0.0000000001) {
      return (93);
    }
    else {
      x = 0.5 * this.a * this.k0 * Math.log((1 + b) / (1 - b));
      con = Math.acos(cos_phi * Math.cos(delta_lon) / Math.sqrt(1 - b * b));
      if (lat < 0) {
        con = -con;
      }
      y = this.a * this.k0 * (con - this.lat0);
    }
  }
  else {
    var al = cos_phi * delta_lon;
    var als = Math.pow(al, 2);
    var c = this.ep2 * Math.pow(cos_phi, 2);
    var tq = Math.tan(lat);
    var t = Math.pow(tq, 2);
    con = 1 - this.es * Math.pow(sin_phi, 2);
    var n = this.a / Math.sqrt(con);
    var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat);

    x = this.k0 * n * al * (1 + als / 6 * (1 - t + c + als / 20 * (5 - 18 * t + Math.pow(t, 2) + 72 * c - 58 * this.ep2))) + this.x0;
    y = this.k0 * (ml - this.ml0 + n * tq * (als * (0.5 + als / 24 * (5 - t + 9 * c + 4 * Math.pow(c, 2) + als / 30 * (61 - 58 * t + Math.pow(t, 2) + 600 * c - 330 * this.ep2))))) + this.y0;

  }
  p.x = x;
  p.y = y;
  return p;
};

/**
    Transverse Mercator Inverse  -  x/y to long/lat
  */
exports.inverse = function(p) {
  var con, phi;
  var delta_phi;
  var i;
  var max_iter = 6;
  var lat, lon;

  if (this.sphere) {
    var f = Math.exp(p.x / (this.a * this.k0));
    var g = 0.5 * (f - 1 / f);
    var temp = this.lat0 + p.y / (this.a * this.k0);
    var h = Math.cos(temp);
    con = Math.sqrt((1 - h * h) / (1 + g * g));
    lat = asinz(con);
    if (temp < 0) {
      lat = -lat;
    }
    if ((g === 0) && (h === 0)) {
      lon = this.long0;
    }
    else {
      lon = adjust_lon(Math.atan2(g, h) + this.long0);
    }
  }
  else { // ellipsoidal form
    var x = p.x - this.x0;
    var y = p.y - this.y0;

    con = (this.ml0 + y / this.k0) / this.a;
    phi = con;
    for (i = 0; true; i++) {
      delta_phi = ((con + this.e1 * Math.sin(2 * phi) - this.e2 * Math.sin(4 * phi) + this.e3 * Math.sin(6 * phi)) / this.e0) - phi;
      phi += delta_phi;
      if (Math.abs(delta_phi) <= EPSLN) {
        break;
      }
      if (i >= max_iter) {
        return (95);
      }
    } // for()
    if (Math.abs(phi) < HALF_PI) {
      var sin_phi = Math.sin(phi);
      var cos_phi = Math.cos(phi);
      var tan_phi = Math.tan(phi);
      var c = this.ep2 * Math.pow(cos_phi, 2);
      var cs = Math.pow(c, 2);
      var t = Math.pow(tan_phi, 2);
      var ts = Math.pow(t, 2);
      con = 1 - this.es * Math.pow(sin_phi, 2);
      var n = this.a / Math.sqrt(con);
      var r = n * (1 - this.es) / con;
      var d = x / (n * this.k0);
      var ds = Math.pow(d, 2);
      lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24 * (5 + 3 * t + 10 * c - 4 * cs - 9 * this.ep2 - ds / 30 * (61 + 90 * t + 298 * c + 45 * ts - 252 * this.ep2 - 3 * cs)));
      lon = adjust_lon(this.long0 + (d * (1 - ds / 6 * (1 + 2 * t + c - ds / 20 * (5 - 2 * c + 28 * t - 3 * cs + 8 * this.ep2 + 24 * ts))) / cos_phi));
    }
    else {
      lat = HALF_PI * sign(y);
      lon = this.long0;
    }
  }
  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Transverse_Mercator", "Transverse Mercator", "tmerc"];

},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz","../common/e0fn":"proj4/lib/common/e0fn","../common/e1fn":"proj4/lib/common/e1fn","../common/e2fn":"proj4/lib/common/e2fn","../common/e3fn":"proj4/lib/common/e3fn","../common/mlfn":"proj4/lib/common/mlfn","../common/sign":"proj4/lib/common/sign"}],"proj4/lib/projections/utm":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var tmerc = require('./tmerc');
exports.dependsOn = 'tmerc';
exports.init = function() {
  if (!this.zone) {
    return;
  }
  this.lat0 = 0;
  this.long0 = ((6 * Math.abs(this.zone)) - 183) * D2R;
  this.x0 = 500000;
  this.y0 = this.utmSouth ? 10000000 : 0;
  this.k0 = 0.9996;

  tmerc.init.apply(this);
  this.forward = tmerc.forward;
  this.inverse = tmerc.inverse;
};
exports.names = ["Universal Transverse Mercator System", "utm"];

},{"./tmerc":"proj4/lib/projections/tmerc"}],"proj4/lib/projections/vandg":[function(require,module,exports){
var adjust_lon = require('../common/adjust_lon');
var HALF_PI = Math.PI/2;
var EPSLN = 1.0e-10;
var asinz = require('../common/asinz');
/* Initialize the Van Der Grinten projection
  ----------------------------------------*/
exports.init = function() {
  //this.R = 6370997; //Radius of earth
  this.R = this.a;
};

exports.forward = function(p) {

  var lon = p.x;
  var lat = p.y;

  /* Forward equations
    -----------------*/
  var dlon = adjust_lon(lon - this.long0);
  var x, y;

  if (Math.abs(lat) <= EPSLN) {
    x = this.x0 + this.R * dlon;
    y = this.y0;
  }
  var theta = asinz(2 * Math.abs(lat / Math.PI));
  if ((Math.abs(dlon) <= EPSLN) || (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN)) {
    x = this.x0;
    if (lat >= 0) {
      y = this.y0 + Math.PI * this.R * Math.tan(0.5 * theta);
    }
    else {
      y = this.y0 + Math.PI * this.R * -Math.tan(0.5 * theta);
    }
    //  return(OK);
  }
  var al = 0.5 * Math.abs((Math.PI / dlon) - (dlon / Math.PI));
  var asq = al * al;
  var sinth = Math.sin(theta);
  var costh = Math.cos(theta);

  var g = costh / (sinth + costh - 1);
  var gsq = g * g;
  var m = g * (2 / sinth - 1);
  var msq = m * m;
  var con = Math.PI * this.R * (al * (g - msq) + Math.sqrt(asq * (g - msq) * (g - msq) - (msq + asq) * (gsq - msq))) / (msq + asq);
  if (dlon < 0) {
    con = -con;
  }
  x = this.x0 + con;
  //con = Math.abs(con / (Math.PI * this.R));
  var q = asq + g;
  con = Math.PI * this.R * (m * q - al * Math.sqrt((msq + asq) * (asq + 1) - q * q)) / (msq + asq);
  if (lat >= 0) {
    //y = this.y0 + Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
    y = this.y0 + con;
  }
  else {
    //y = this.y0 - Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
    y = this.y0 - con;
  }
  p.x = x;
  p.y = y;
  return p;
};

/* Van Der Grinten inverse equations--mapping x,y to lat/long
  ---------------------------------------------------------*/
exports.inverse = function(p) {
  var lon, lat;
  var xx, yy, xys, c1, c2, c3;
  var a1;
  var m1;
  var con;
  var th1;
  var d;

  /* inverse equations
    -----------------*/
  p.x -= this.x0;
  p.y -= this.y0;
  con = Math.PI * this.R;
  xx = p.x / con;
  yy = p.y / con;
  xys = xx * xx + yy * yy;
  c1 = -Math.abs(yy) * (1 + xys);
  c2 = c1 - 2 * yy * yy + xx * xx;
  c3 = -2 * c1 + 1 + 2 * yy * yy + xys * xys;
  d = yy * yy / c3 + (2 * c2 * c2 * c2 / c3 / c3 / c3 - 9 * c1 * c2 / c3 / c3) / 27;
  a1 = (c1 - c2 * c2 / 3 / c3) / c3;
  m1 = 2 * Math.sqrt(-a1 / 3);
  con = ((3 * d) / a1) / m1;
  if (Math.abs(con) > 1) {
    if (con >= 0) {
      con = 1;
    }
    else {
      con = -1;
    }
  }
  th1 = Math.acos(con) / 3;
  if (p.y >= 0) {
    lat = (-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
  }
  else {
    lat = -(-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
  }

  if (Math.abs(xx) < EPSLN) {
    lon = this.long0;
  }
  else {
    lon = adjust_lon(this.long0 + Math.PI * (xys - 1 + Math.sqrt(1 + 2 * (xx * xx - yy * yy) + xys * xys)) / 2 / xx);
  }

  p.x = lon;
  p.y = lat;
  return p;
};
exports.names = ["Van_der_Grinten_I", "VanDerGrinten", "vandg"];
},{"../common/adjust_lon":"proj4/lib/common/adjust_lon","../common/asinz":"proj4/lib/common/asinz"}],"proj4/lib/transform":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var R2D = 57.29577951308232088;
var PJD_3PARAM = 1;
var PJD_7PARAM = 2;
var datum_transform = require('./datum_transform');
var adjust_axis = require('./adjust_axis');
var proj = require('./Proj');
var toPoint = require('./common/toPoint');
module.exports = function transform(source, dest, point) {
  var wgs84;
  if (Array.isArray(point)) {
    point = toPoint(point);
  }
  function checkNotWGS(source, dest) {
    return ((source.datum.datum_type === PJD_3PARAM || source.datum.datum_type === PJD_7PARAM) && dest.datumCode !== "WGS84");
  }

  // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
  if (source.datum && dest.datum && (checkNotWGS(source, dest) || checkNotWGS(dest, source))) {
    wgs84 = new proj('WGS84');
    transform(source, wgs84, point);
    source = wgs84;
  }
  // DGR, 2010/11/12
  if (source.axis !== "enu") {
    adjust_axis(source, false, point);
  }
  // Transform source points to long/lat, if they aren't already.
  if (source.projName === "longlat") {
    point.x *= D2R; // convert degrees to radians
    point.y *= D2R;
  }
  else {
    if (source.to_meter) {
      point.x *= source.to_meter;
      point.y *= source.to_meter;
    }
    source.inverse(point); // Convert Cartesian to longlat
  }
  // Adjust for the prime meridian if necessary
  if (source.from_greenwich) {
    point.x += source.from_greenwich;
  }

  // Convert datums if needed, and if possible.
  point = datum_transform(source.datum, dest.datum, point);

  // Adjust for the prime meridian if necessary
  if (dest.from_greenwich) {
    point.x -= dest.from_greenwich;
  }

  if (dest.projName === "longlat") {
    // convert radians to decimal degrees
    point.x *= R2D;
    point.y *= R2D;
  }
  else { // else project
    dest.forward(point);
    if (dest.to_meter) {
      point.x /= dest.to_meter;
      point.y /= dest.to_meter;
    }
  }

  // DGR, 2010/11/12
  if (dest.axis !== "enu") {
    adjust_axis(dest, true, point);
  }

  return point;
};
},{"./Proj":"proj4/lib/Proj","./adjust_axis":"proj4/lib/adjust_axis","./common/toPoint":"proj4/lib/common/toPoint","./datum_transform":"proj4/lib/datum_transform"}],"proj4/lib/wkt":[function(require,module,exports){
var D2R = 0.01745329251994329577;
var extend = require('./extend');

function mapit(obj, key, v) {
  obj[key] = v.map(function(aa) {
    var o = {};
    sExpr(aa, o);
    return o;
  }).reduce(function(a, b) {
    return extend(a, b);
  }, {});
}

function sExpr(v, obj) {
  var key;
  if (!Array.isArray(v)) {
    obj[v] = true;
    return;
  }
  else {
    key = v.shift();
    if (key === 'PARAMETER') {
      key = v.shift();
    }
    if (v.length === 1) {
      if (Array.isArray(v[0])) {
        obj[key] = {};
        sExpr(v[0], obj[key]);
      }
      else {
        obj[key] = v[0];
      }
    }
    else if (!v.length) {
      obj[key] = true;
    }
    else if (key === 'TOWGS84') {
      obj[key] = v;
    }
    else {
      obj[key] = {};
      if (['UNIT', 'PRIMEM', 'VERT_DATUM'].indexOf(key) > -1) {
        obj[key] = {
          name: v[0].toLowerCase(),
          convert: v[1]
        };
        if (v.length === 3) {
          obj[key].auth = v[2];
        }
      }
      else if (key === 'SPHEROID') {
        obj[key] = {
          name: v[0],
          a: v[1],
          rf: v[2]
        };
        if (v.length === 4) {
          obj[key].auth = v[3];
        }
      }
      else if (['GEOGCS', 'GEOCCS', 'DATUM', 'VERT_CS', 'COMPD_CS', 'LOCAL_CS', 'FITTED_CS', 'LOCAL_DATUM'].indexOf(key) > -1) {
        v[0] = ['name', v[0]];
        mapit(obj, key, v);
      }
      else if (v.every(function(aa) {
        return Array.isArray(aa);
      })) {
        mapit(obj, key, v);
      }
      else {
        sExpr(v, obj[key]);
      }
    }
  }
}

function rename(obj, params) {
  var outName = params[0];
  var inName = params[1];
  if (!(outName in obj) && (inName in obj)) {
    obj[outName] = obj[inName];
    if (params.length === 3) {
      obj[outName] = params[2](obj[outName]);
    }
  }
}

function d2r(input) {
  return input * D2R;
}

function cleanWKT(wkt) {
  if (wkt.type === 'GEOGCS') {
    wkt.projName = 'longlat';
  }
  else if (wkt.type === 'LOCAL_CS') {
    wkt.projName = 'identity';
    wkt.local = true;
  }
  else {
    if (typeof wkt.PROJECTION === "object") {
      wkt.projName = Object.keys(wkt.PROJECTION)[0];
    }
    else {
      wkt.projName = wkt.PROJECTION;
    }
  }
  if (wkt.UNIT) {
    wkt.units = wkt.UNIT.name.toLowerCase();
    if (wkt.units === 'metre') {
      wkt.units = 'meter';
    }
    if (wkt.UNIT.convert) {
      if (wkt.type === 'GEOGCS') {
        if (wkt.DATUM && wkt.DATUM.SPHEROID) {
          wkt.to_meter = parseFloat(wkt.UNIT.convert, 10)*wkt.DATUM.SPHEROID.a;
        }
      } else {
        wkt.to_meter = parseFloat(wkt.UNIT.convert, 10);
      }
    }
  }

  if (wkt.GEOGCS) {
    //if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){
    //  wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R;
    //}
    if (wkt.GEOGCS.DATUM) {
      wkt.datumCode = wkt.GEOGCS.DATUM.name.toLowerCase();
    }
    else {
      wkt.datumCode = wkt.GEOGCS.name.toLowerCase();
    }
    if (wkt.datumCode.slice(0, 2) === 'd_') {
      wkt.datumCode = wkt.datumCode.slice(2);
    }
    if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') {
      wkt.datumCode = 'nzgd49';
    }
    if (wkt.datumCode === "wgs_1984") {
      if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
        wkt.sphere = true;
      }
      wkt.datumCode = 'wgs84';
    }
    if (wkt.datumCode.slice(-6) === '_ferro') {
      wkt.datumCode = wkt.datumCode.slice(0, - 6);
    }
    if (wkt.datumCode.slice(-8) === '_jakarta') {
      wkt.datumCode = wkt.datumCode.slice(0, - 8);
    }
    if (~wkt.datumCode.indexOf('belge')) {
      wkt.datumCode = "rnb72";
    }
    if (wkt.GEOGCS.DATUM && wkt.GEOGCS.DATUM.SPHEROID) {
      wkt.ellps = wkt.GEOGCS.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
      if (wkt.ellps.toLowerCase().slice(0, 13) === "international") {
        wkt.ellps = 'intl';
      }

      wkt.a = wkt.GEOGCS.DATUM.SPHEROID.a;
      wkt.rf = parseFloat(wkt.GEOGCS.DATUM.SPHEROID.rf, 10);
    }
    if (~wkt.datumCode.indexOf('osgb_1936')) {
      wkt.datumCode = "osgb36";
    }
  }
  if (wkt.b && !isFinite(wkt.b)) {
    wkt.b = wkt.a;
  }

  function toMeter(input) {
    var ratio = wkt.to_meter || 1;
    return parseFloat(input, 10) * ratio;
  }
  var renamer = function(a) {
    return rename(wkt, a);
  };
  var list = [
    ['standard_parallel_1', 'Standard_Parallel_1'],
    ['standard_parallel_2', 'Standard_Parallel_2'],
    ['false_easting', 'False_Easting'],
    ['false_northing', 'False_Northing'],
    ['central_meridian', 'Central_Meridian'],
    ['latitude_of_origin', 'Latitude_Of_Origin'],
    ['latitude_of_origin', 'Central_Parallel'],
    ['scale_factor', 'Scale_Factor'],
    ['k0', 'scale_factor'],
    ['latitude_of_center', 'Latitude_of_center'],
    ['lat0', 'latitude_of_center', d2r],
    ['longitude_of_center', 'Longitude_Of_Center'],
    ['longc', 'longitude_of_center', d2r],
    ['x0', 'false_easting', toMeter],
    ['y0', 'false_northing', toMeter],
    ['long0', 'central_meridian', d2r],
    ['lat0', 'latitude_of_origin', d2r],
    ['lat0', 'standard_parallel_1', d2r],
    ['lat1', 'standard_parallel_1', d2r],
    ['lat2', 'standard_parallel_2', d2r],
    ['alpha', 'azimuth', d2r],
    ['srsCode', 'name']
  ];
  list.forEach(renamer);
  if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === "Lambert_Azimuthal_Equal_Area")) {
    wkt.long0 = wkt.longc;
  }
  if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
    wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
    wkt.lat_ts = wkt.lat1;
  }
}
module.exports = function(wkt, self) {
  var lisp = JSON.parse(("," + wkt).replace(/\s*\,\s*([A-Z_0-9]+?)(\[)/g, ',["$1",').slice(1).replace(/\s*\,\s*([A-Z_0-9]+?)\]/g, ',"$1"]').replace(/,\["VERTCS".+/,''));
  var type = lisp.shift();
  var name = lisp.shift();
  lisp.unshift(['name', name]);
  lisp.unshift(['type', type]);
  lisp.unshift('output');
  var obj = {};
  sExpr(lisp, obj);
  cleanWKT(obj.output);
  return extend(self, obj.output);
};

},{"./extend":"proj4/lib/extend"}],"proj4/node_modules/mgrs/mgrs":[function(require,module,exports){



/**
 * UTM zones are grouped, and assigned to one of a group of 6
 * sets.
 *
 * {int} @private
 */
var NUM_100K_SETS = 6;

/**
 * The column letters (for easting) of the lower left value, per
 * set.
 *
 * {string} @private
 */
var SET_ORIGIN_COLUMN_LETTERS = 'AJSAJS';

/**
 * The row letters (for northing) of the lower left value, per
 * set.
 *
 * {string} @private
 */
var SET_ORIGIN_ROW_LETTERS = 'AFAFAF';

var A = 65; // A
var I = 73; // I
var O = 79; // O
var V = 86; // V
var Z = 90; // Z

/**
 * Conversion of lat/lon to MGRS.
 *
 * @param {object} ll Object literal with lat and lon properties on a
 *     WGS84 ellipsoid.
 * @param {int} accuracy Accuracy in digits (5 for 1 m, 4 for 10 m, 3 for
 *      100 m, 2 for 1000 m or 1 for 10000 m). Optional, default is 5.
 * @return {string} the MGRS string for the given location and accuracy.
 */
exports.forward = function(ll, accuracy) {
  accuracy = accuracy || 5; // default accuracy 1m
  return encode(LLtoUTM({
    lat: ll[1],
    lon: ll[0]
  }), accuracy);
};

/**
 * Conversion of MGRS to lat/lon.
 *
 * @param {string} mgrs MGRS string.
 * @return {array} An array with left (longitude), bottom (latitude), right
 *     (longitude) and top (latitude) values in WGS84, representing the
 *     bounding box for the provided MGRS reference.
 */
exports.inverse = function(mgrs) {
  var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
  if (bbox.lat && bbox.lon) {
    return [bbox.lon, bbox.lat, bbox.lon, bbox.lat];
  }
  return [bbox.left, bbox.bottom, bbox.right, bbox.top];
};

exports.toPoint = function(mgrs) {
  var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
  if (bbox.lat && bbox.lon) {
    return [bbox.lon, bbox.lat];
  }
  return [(bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2];
};
/**
 * Conversion from degrees to radians.
 *
 * @private
 * @param {number} deg the angle in degrees.
 * @return {number} the angle in radians.
 */
function degToRad(deg) {
  return (deg * (Math.PI / 180.0));
}

/**
 * Conversion from radians to degrees.
 *
 * @private
 * @param {number} rad the angle in radians.
 * @return {number} the angle in degrees.
 */
function radToDeg(rad) {
  return (180.0 * (rad / Math.PI));
}

/**
 * Converts a set of Longitude and Latitude co-ordinates to UTM
 * using the WGS84 ellipsoid.
 *
 * @private
 * @param {object} ll Object literal with lat and lon properties
 *     representing the WGS84 coordinate to be converted.
 * @return {object} Object literal containing the UTM value with easting,
 *     northing, zoneNumber and zoneLetter properties, and an optional
 *     accuracy property in digits. Returns null if the conversion failed.
 */
function LLtoUTM(ll) {
  var Lat = ll.lat;
  var Long = ll.lon;
  var a = 6378137.0; //ellip.radius;
  var eccSquared = 0.00669438; //ellip.eccsq;
  var k0 = 0.9996;
  var LongOrigin;
  var eccPrimeSquared;
  var N, T, C, A, M;
  var LatRad = degToRad(Lat);
  var LongRad = degToRad(Long);
  var LongOriginRad;
  var ZoneNumber;
  // (int)
  ZoneNumber = Math.floor((Long + 180) / 6) + 1;

  //Make sure the longitude 180.00 is in Zone 60
  if (Long === 180) {
    ZoneNumber = 60;
  }

  // Special zone for Norway
  if (Lat >= 56.0 && Lat < 64.0 && Long >= 3.0 && Long < 12.0) {
    ZoneNumber = 32;
  }

  // Special zones for Svalbard
  if (Lat >= 72.0 && Lat < 84.0) {
    if (Long >= 0.0 && Long < 9.0) {
      ZoneNumber = 31;
    }
    else if (Long >= 9.0 && Long < 21.0) {
      ZoneNumber = 33;
    }
    else if (Long >= 21.0 && Long < 33.0) {
      ZoneNumber = 35;
    }
    else if (Long >= 33.0 && Long < 42.0) {
      ZoneNumber = 37;
    }
  }

  LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin
  // in middle of
  // zone
  LongOriginRad = degToRad(LongOrigin);

  eccPrimeSquared = (eccSquared) / (1 - eccSquared);

  N = a / Math.sqrt(1 - eccSquared * Math.sin(LatRad) * Math.sin(LatRad));
  T = Math.tan(LatRad) * Math.tan(LatRad);
  C = eccPrimeSquared * Math.cos(LatRad) * Math.cos(LatRad);
  A = Math.cos(LatRad) * (LongRad - LongOriginRad);

  M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * LatRad) + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * LatRad));

  var UTMEasting = (k0 * N * (A + (1 - T + C) * A * A * A / 6.0 + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120.0) + 500000.0);

  var UTMNorthing = (k0 * (M + N * Math.tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0 + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720.0)));
  if (Lat < 0.0) {
    UTMNorthing += 10000000.0; //10000000 meter offset for
    // southern hemisphere
  }

  return {
    northing: Math.round(UTMNorthing),
    easting: Math.round(UTMEasting),
    zoneNumber: ZoneNumber,
    zoneLetter: getLetterDesignator(Lat)
  };
}

/**
 * Converts UTM coords to lat/long, using the WGS84 ellipsoid. This is a convenience
 * class where the Zone can be specified as a single string eg."60N" which
 * is then broken down into the ZoneNumber and ZoneLetter.
 *
 * @private
 * @param {object} utm An object literal with northing, easting, zoneNumber
 *     and zoneLetter properties. If an optional accuracy property is
 *     provided (in meters), a bounding box will be returned instead of
 *     latitude and longitude.
 * @return {object} An object literal containing either lat and lon values
 *     (if no accuracy was provided), or top, right, bottom and left values
 *     for the bounding box calculated according to the provided accuracy.
 *     Returns null if the conversion failed.
 */
function UTMtoLL(utm) {

  var UTMNorthing = utm.northing;
  var UTMEasting = utm.easting;
  var zoneLetter = utm.zoneLetter;
  var zoneNumber = utm.zoneNumber;
  // check the ZoneNummber is valid
  if (zoneNumber < 0 || zoneNumber > 60) {
    return null;
  }

  var k0 = 0.9996;
  var a = 6378137.0; //ellip.radius;
  var eccSquared = 0.00669438; //ellip.eccsq;
  var eccPrimeSquared;
  var e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared));
  var N1, T1, C1, R1, D, M;
  var LongOrigin;
  var mu, phi1Rad;

  // remove 500,000 meter offset for longitude
  var x = UTMEasting - 500000.0;
  var y = UTMNorthing;

  // We must know somehow if we are in the Northern or Southern
  // hemisphere, this is the only time we use the letter So even
  // if the Zone letter isn't exactly correct it should indicate
  // the hemisphere correctly
  if (zoneLetter < 'N') {
    y -= 10000000.0; // remove 10,000,000 meter offset used
    // for southern hemisphere
  }

  // There are 60 zones with zone 1 being at West -180 to -174
  LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin
  // in middle of
  // zone

  eccPrimeSquared = (eccSquared) / (1 - eccSquared);

  M = y / k0;
  mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256));

  phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu);
  // double phi1 = ProjMath.radToDeg(phi1Rad);

  N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad));
  T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad);
  C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad);
  R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5);
  D = x / (N1 * k0);

  var lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720);
  lat = radToDeg(lat);

  var lon = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad);
  lon = LongOrigin + radToDeg(lon);

  var result;
  if (utm.accuracy) {
    var topRight = UTMtoLL({
      northing: utm.northing + utm.accuracy,
      easting: utm.easting + utm.accuracy,
      zoneLetter: utm.zoneLetter,
      zoneNumber: utm.zoneNumber
    });
    result = {
      top: topRight.lat,
      right: topRight.lon,
      bottom: lat,
      left: lon
    };
  }
  else {
    result = {
      lat: lat,
      lon: lon
    };
  }
  return result;
}

/**
 * Calculates the MGRS letter designator for the given latitude.
 *
 * @private
 * @param {number} lat The latitude in WGS84 to get the letter designator
 *     for.
 * @return {char} The letter designator.
 */
function getLetterDesignator(lat) {
  //This is here as an error flag to show that the Latitude is
  //outside MGRS limits
  var LetterDesignator = 'Z';

  if ((84 >= lat) && (lat >= 72)) {
    LetterDesignator = 'X';
  }
  else if ((72 > lat) && (lat >= 64)) {
    LetterDesignator = 'W';
  }
  else if ((64 > lat) && (lat >= 56)) {
    LetterDesignator = 'V';
  }
  else if ((56 > lat) && (lat >= 48)) {
    LetterDesignator = 'U';
  }
  else if ((48 > lat) && (lat >= 40)) {
    LetterDesignator = 'T';
  }
  else if ((40 > lat) && (lat >= 32)) {
    LetterDesignator = 'S';
  }
  else if ((32 > lat) && (lat >= 24)) {
    LetterDesignator = 'R';
  }
  else if ((24 > lat) && (lat >= 16)) {
    LetterDesignator = 'Q';
  }
  else if ((16 > lat) && (lat >= 8)) {
    LetterDesignator = 'P';
  }
  else if ((8 > lat) && (lat >= 0)) {
    LetterDesignator = 'N';
  }
  else if ((0 > lat) && (lat >= -8)) {
    LetterDesignator = 'M';
  }
  else if ((-8 > lat) && (lat >= -16)) {
    LetterDesignator = 'L';
  }
  else if ((-16 > lat) && (lat >= -24)) {
    LetterDesignator = 'K';
  }
  else if ((-24 > lat) && (lat >= -32)) {
    LetterDesignator = 'J';
  }
  else if ((-32 > lat) && (lat >= -40)) {
    LetterDesignator = 'H';
  }
  else if ((-40 > lat) && (lat >= -48)) {
    LetterDesignator = 'G';
  }
  else if ((-48 > lat) && (lat >= -56)) {
    LetterDesignator = 'F';
  }
  else if ((-56 > lat) && (lat >= -64)) {
    LetterDesignator = 'E';
  }
  else if ((-64 > lat) && (lat >= -72)) {
    LetterDesignator = 'D';
  }
  else if ((-72 > lat) && (lat >= -80)) {
    LetterDesignator = 'C';
  }
  return LetterDesignator;
}

/**
 * Encodes a UTM location as MGRS string.
 *
 * @private
 * @param {object} utm An object literal with easting, northing,
 *     zoneLetter, zoneNumber
 * @param {number} accuracy Accuracy in digits (1-5).
 * @return {string} MGRS string for the given UTM location.
 */
function encode(utm, accuracy) {
  // prepend with leading zeroes
  var seasting = "00000" + utm.easting,
    snorthing = "00000" + utm.northing;

  return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy);
}

/**
 * Get the two letter 100k designator for a given UTM easting,
 * northing and zone number value.
 *
 * @private
 * @param {number} easting
 * @param {number} northing
 * @param {number} zoneNumber
 * @return the two letter 100k designator for the given UTM location.
 */
function get100kID(easting, northing, zoneNumber) {
  var setParm = get100kSetForZone(zoneNumber);
  var setColumn = Math.floor(easting / 100000);
  var setRow = Math.floor(northing / 100000) % 20;
  return getLetter100kID(setColumn, setRow, setParm);
}

/**
 * Given a UTM zone number, figure out the MGRS 100K set it is in.
 *
 * @private
 * @param {number} i An UTM zone number.
 * @return {number} the 100k set the UTM zone is in.
 */
function get100kSetForZone(i) {
  var setParm = i % NUM_100K_SETS;
  if (setParm === 0) {
    setParm = NUM_100K_SETS;
  }

  return setParm;
}

/**
 * Get the two-letter MGRS 100k designator given information
 * translated from the UTM northing, easting and zone number.
 *
 * @private
 * @param {number} column the column index as it relates to the MGRS
 *        100k set spreadsheet, created from the UTM easting.
 *        Values are 1-8.
 * @param {number} row the row index as it relates to the MGRS 100k set
 *        spreadsheet, created from the UTM northing value. Values
 *        are from 0-19.
 * @param {number} parm the set block, as it relates to the MGRS 100k set
 *        spreadsheet, created from the UTM zone. Values are from
 *        1-60.
 * @return two letter MGRS 100k code.
 */
function getLetter100kID(column, row, parm) {
  // colOrigin and rowOrigin are the letters at the origin of the set
  var index = parm - 1;
  var colOrigin = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(index);
  var rowOrigin = SET_ORIGIN_ROW_LETTERS.charCodeAt(index);

  // colInt and rowInt are the letters to build to return
  var colInt = colOrigin + column - 1;
  var rowInt = rowOrigin + row;
  var rollover = false;

  if (colInt > Z) {
    colInt = colInt - Z + A - 1;
    rollover = true;
  }

  if (colInt === I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) {
    colInt++;
  }

  if (colInt === O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) {
    colInt++;

    if (colInt === I) {
      colInt++;
    }
  }

  if (colInt > Z) {
    colInt = colInt - Z + A - 1;
  }

  if (rowInt > V) {
    rowInt = rowInt - V + A - 1;
    rollover = true;
  }
  else {
    rollover = false;
  }

  if (((rowInt === I) || ((rowOrigin < I) && (rowInt > I))) || (((rowInt > I) || (rowOrigin < I)) && rollover)) {
    rowInt++;
  }

  if (((rowInt === O) || ((rowOrigin < O) && (rowInt > O))) || (((rowInt > O) || (rowOrigin < O)) && rollover)) {
    rowInt++;

    if (rowInt === I) {
      rowInt++;
    }
  }

  if (rowInt > V) {
    rowInt = rowInt - V + A - 1;
  }

  var twoLetter = String.fromCharCode(colInt) + String.fromCharCode(rowInt);
  return twoLetter;
}

/**
 * Decode the UTM parameters from a MGRS string.
 *
 * @private
 * @param {string} mgrsString an UPPERCASE coordinate string is expected.
 * @return {object} An object literal with easting, northing, zoneLetter,
 *     zoneNumber and accuracy (in meters) properties.
 */
function decode(mgrsString) {

  if (mgrsString && mgrsString.length === 0) {
    throw ("MGRSPoint coverting from nothing");
  }

  var length = mgrsString.length;

  var hunK = null;
  var sb = "";
  var testChar;
  var i = 0;

  // get Zone number
  while (!(/[A-Z]/).test(testChar = mgrsString.charAt(i))) {
    if (i >= 2) {
      throw ("MGRSPoint bad conversion from: " + mgrsString);
    }
    sb += testChar;
    i++;
  }

  var zoneNumber = parseInt(sb, 10);

  if (i === 0 || i + 3 > length) {
    // A good MGRS string has to be 4-5 digits long,
    // ##AAA/#AAA at least.
    throw ("MGRSPoint bad conversion from: " + mgrsString);
  }

  var zoneLetter = mgrsString.charAt(i++);

  // Should we check the zone letter here? Why not.
  if (zoneLetter <= 'A' || zoneLetter === 'B' || zoneLetter === 'Y' || zoneLetter >= 'Z' || zoneLetter === 'I' || zoneLetter === 'O') {
    throw ("MGRSPoint zone letter " + zoneLetter + " not handled: " + mgrsString);
  }

  hunK = mgrsString.substring(i, i += 2);

  var set = get100kSetForZone(zoneNumber);

  var east100k = getEastingFromChar(hunK.charAt(0), set);
  var north100k = getNorthingFromChar(hunK.charAt(1), set);

  // We have a bug where the northing may be 2000000 too low.
  // How
  // do we know when to roll over?

  while (north100k < getMinNorthing(zoneLetter)) {
    north100k += 2000000;
  }

  // calculate the char index for easting/northing separator
  var remainder = length - i;

  if (remainder % 2 !== 0) {
    throw ("MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" + mgrsString);
  }

  var sep = remainder / 2;

  var sepEasting = 0.0;
  var sepNorthing = 0.0;
  var accuracyBonus, sepEastingString, sepNorthingString, easting, northing;
  if (sep > 0) {
    accuracyBonus = 100000.0 / Math.pow(10, sep);
    sepEastingString = mgrsString.substring(i, i + sep);
    sepEasting = parseFloat(sepEastingString) * accuracyBonus;
    sepNorthingString = mgrsString.substring(i + sep);
    sepNorthing = parseFloat(sepNorthingString) * accuracyBonus;
  }

  easting = sepEasting + east100k;
  northing = sepNorthing + north100k;

  return {
    easting: easting,
    northing: northing,
    zoneLetter: zoneLetter,
    zoneNumber: zoneNumber,
    accuracy: accuracyBonus
  };
}

/**
 * Given the first letter from a two-letter MGRS 100k zone, and given the
 * MGRS table set for the zone number, figure out the easting value that
 * should be added to the other, secondary easting value.
 *
 * @private
 * @param {char} e The first letter from a two-letter MGRS 100´k zone.
 * @param {number} set The MGRS table set for the zone number.
 * @return {number} The easting value for the given letter and set.
 */
function getEastingFromChar(e, set) {
  // colOrigin is the letter at the origin of the set for the
  // column
  var curCol = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(set - 1);
  var eastingValue = 100000.0;
  var rewindMarker = false;

  while (curCol !== e.charCodeAt(0)) {
    curCol++;
    if (curCol === I) {
      curCol++;
    }
    if (curCol === O) {
      curCol++;
    }
    if (curCol > Z) {
      if (rewindMarker) {
        throw ("Bad character: " + e);
      }
      curCol = A;
      rewindMarker = true;
    }
    eastingValue += 100000.0;
  }

  return eastingValue;
}

/**
 * Given the second letter from a two-letter MGRS 100k zone, and given the
 * MGRS table set for the zone number, figure out the northing value that
 * should be added to the other, secondary northing value. You have to
 * remember that Northings are determined from the equator, and the vertical
 * cycle of letters mean a 2000000 additional northing meters. This happens
 * approx. every 18 degrees of latitude. This method does *NOT* count any
 * additional northings. You have to figure out how many 2000000 meters need
 * to be added for the zone letter of the MGRS coordinate.
 *
 * @private
 * @param {char} n Second letter of the MGRS 100k zone
 * @param {number} set The MGRS table set number, which is dependent on the
 *     UTM zone number.
 * @return {number} The northing value for the given letter and set.
 */
function getNorthingFromChar(n, set) {

  if (n > 'V') {
    throw ("MGRSPoint given invalid Northing " + n);
  }

  // rowOrigin is the letter at the origin of the set for the
  // column
  var curRow = SET_ORIGIN_ROW_LETTERS.charCodeAt(set - 1);
  var northingValue = 0.0;
  var rewindMarker = false;

  while (curRow !== n.charCodeAt(0)) {
    curRow++;
    if (curRow === I) {
      curRow++;
    }
    if (curRow === O) {
      curRow++;
    }
    // fixing a bug making whole application hang in this loop
    // when 'n' is a wrong character
    if (curRow > V) {
      if (rewindMarker) { // making sure that this loop ends
        throw ("Bad character: " + n);
      }
      curRow = A;
      rewindMarker = true;
    }
    northingValue += 100000.0;
  }

  return northingValue;
}

/**
 * The function getMinNorthing returns the minimum northing value of a MGRS
 * zone.
 *
 * Ported from Geotrans' c Lattitude_Band_Value structure table.
 *
 * @private
 * @param {char} zoneLetter The MGRS zone to get the min northing for.
 * @return {number}
 */
function getMinNorthing(zoneLetter) {
  var northing;
  switch (zoneLetter) {
  case 'C':
    northing = 1100000.0;
    break;
  case 'D':
    northing = 2000000.0;
    break;
  case 'E':
    northing = 2800000.0;
    break;
  case 'F':
    northing = 3700000.0;
    break;
  case 'G':
    northing = 4600000.0;
    break;
  case 'H':
    northing = 5500000.0;
    break;
  case 'J':
    northing = 6400000.0;
    break;
  case 'K':
    northing = 7300000.0;
    break;
  case 'L':
    northing = 8200000.0;
    break;
  case 'M':
    northing = 9100000.0;
    break;
  case 'N':
    northing = 0.0;
    break;
  case 'P':
    northing = 800000.0;
    break;
  case 'Q':
    northing = 1700000.0;
    break;
  case 'R':
    northing = 2600000.0;
    break;
  case 'S':
    northing = 3500000.0;
    break;
  case 'T':
    northing = 4400000.0;
    break;
  case 'U':
    northing = 5300000.0;
    break;
  case 'V':
    northing = 6200000.0;
    break;
  case 'W':
    northing = 7000000.0;
    break;
  case 'X':
    northing = 7900000.0;
    break;
  default:
    northing = -1.0;
  }
  if (northing >= 0.0) {
    return northing;
  }
  else {
    throw ("Invalid zone letter: " + zoneLetter);
  }

}

},{}],"proj4/package.json":[function(require,module,exports){
module.exports={
  "name": "proj4",
  "version": "2.3.14",
  "description": "Proj4js is a JavaScript library to transform point coordinates from one coordinate system to another, including datum transformations.",
  "main": "lib/index.js",
  "directories": {
    "test": "test",
    "doc": "docs"
  },
  "scripts": {
    "test": "./node_modules/istanbul/lib/cli.js test ./node_modules/mocha/bin/_mocha test/test.js"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/proj4js/proj4js.git"
  },
  "author": "",
  "license": "MIT",
  "jam": {
    "main": "dist/proj4.js",
    "include": [
      "dist/proj4.js",
      "README.md",
      "AUTHORS",
      "LICENSE.md"
    ]
  },
  "devDependencies": {
    "grunt-cli": "~0.1.13",
    "grunt": "~0.4.2",
    "grunt-contrib-connect": "~0.6.0",
    "grunt-contrib-jshint": "~0.8.0",
    "chai": "~1.8.1",
    "mocha": "~1.17.1",
    "grunt-mocha-phantomjs": "~0.4.0",
    "browserify": "~12.0.1",
    "grunt-browserify": "~4.0.1",
    "grunt-contrib-uglify": "~0.11.1",
    "curl": "git://github.com/cujojs/curl.git",
    "istanbul": "~0.2.4",
    "tin": "~0.4.0"
  },
  "dependencies": {
    "mgrs": "~0.0.2"
  },
  "contributors": [
    {
      "name": "Mike Adair",
      "email": "madair@dmsolutions.ca"
    },
    {
      "name": "Richard Greenwood",
      "email": "rich@greenwoodmap.com"
    },
    {
      "name": "Calvin Metcalf",
      "email": "calvin.metcalf@gmail.com"
    },
    {
      "name": "Richard Marsden",
      "url": "http://www.winwaed.com"
    },
    {
      "name": "T. Mittan"
    },
    {
      "name": "D. Steinwand"
    },
    {
      "name": "S. Nelson"
    }
  ],
  "gitHead": "7619c8a63df1eae5bad0b9ad31ca1d87b0549243",
  "bugs": {
    "url": "https://github.com/proj4js/proj4js/issues"
  },
  "homepage": "https://github.com/proj4js/proj4js#readme",
  "_id": "proj4@2.3.14",
  "_shasum": "928906144388980c914c5a357fc493aba59a747a",
  "_from": "proj4@>=2.3.10 <3.0.0",
  "_npmVersion": "2.14.12",
  "_nodeVersion": "4.2.6",
  "_npmUser": {
    "name": "ahocevar",
    "email": "andreas.hocevar@gmail.com"
  },
  "dist": {
    "shasum": "928906144388980c914c5a357fc493aba59a747a",
    "tarball": "https://registry.npmjs.org/proj4/-/proj4-2.3.14.tgz"
  },
  "maintainers": [
    {
      "name": "cwmma",
      "email": "calvin.metcalf@gmail.com"
    },
    {
      "name": "ahocevar",
      "email": "andreas.hocevar@gmail.com"
    }
  ],
  "_npmOperationalInternal": {
    "host": "packages-13-west.internal.npmjs.com",
    "tmp": "tmp/proj4-2.3.14.tgz_1457689264880_0.9409773757215589"
  },
  "_resolved": "https://registry.npmjs.org/proj4/-/proj4-2.3.14.tgz"
}

},{}],"rbush":[function(require,module,exports){
'use strict';

module.exports = rbush;

var quickselect = require('quickselect');

function rbush(maxEntries, format) {
    if (!(this instanceof rbush)) return new rbush(maxEntries, format);

    // max entries in a node is 9 by default; min node fill is 40% for best performance
    this._maxEntries = Math.max(4, maxEntries || 9);
    this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));

    if (format) {
        this._initFormat(format);
    }

    this.clear();
}

rbush.prototype = {

    all: function () {
        return this._all(this.data, []);
    },

    search: function (bbox) {

        var node = this.data,
            result = [],
            toBBox = this.toBBox;

        if (!intersects(bbox, node)) return result;

        var nodesToSearch = [],
            i, len, child, childBBox;

        while (node) {
            for (i = 0, len = node.children.length; i < len; i++) {

                child = node.children[i];
                childBBox = node.leaf ? toBBox(child) : child;

                if (intersects(bbox, childBBox)) {
                    if (node.leaf) result.push(child);
                    else if (contains(bbox, childBBox)) this._all(child, result);
                    else nodesToSearch.push(child);
                }
            }
            node = nodesToSearch.pop();
        }

        return result;
    },

    collides: function (bbox) {

        var node = this.data,
            toBBox = this.toBBox;

        if (!intersects(bbox, node)) return false;

        var nodesToSearch = [],
            i, len, child, childBBox;

        while (node) {
            for (i = 0, len = node.children.length; i < len; i++) {

                child = node.children[i];
                childBBox = node.leaf ? toBBox(child) : child;

                if (intersects(bbox, childBBox)) {
                    if (node.leaf || contains(bbox, childBBox)) return true;
                    nodesToSearch.push(child);
                }
            }
            node = nodesToSearch.pop();
        }

        return false;
    },

    load: function (data) {
        if (!(data && data.length)) return this;

        if (data.length < this._minEntries) {
            for (var i = 0, len = data.length; i < len; i++) {
                this.insert(data[i]);
            }
            return this;
        }

        // recursively build the tree with the given data from stratch using OMT algorithm
        var node = this._build(data.slice(), 0, data.length - 1, 0);

        if (!this.data.children.length) {
            // save as is if tree is empty
            this.data = node;

        } else if (this.data.height === node.height) {
            // split root if trees have the same height
            this._splitRoot(this.data, node);

        } else {
            if (this.data.height < node.height) {
                // swap trees if inserted one is bigger
                var tmpNode = this.data;
                this.data = node;
                node = tmpNode;
            }

            // insert the small tree into the large tree at appropriate level
            this._insert(node, this.data.height - node.height - 1, true);
        }

        return this;
    },

    insert: function (item) {
        if (item) this._insert(item, this.data.height - 1);
        return this;
    },

    clear: function () {
        this.data = createNode([]);
        return this;
    },

    remove: function (item, equalsFn) {
        if (!item) return this;

        var node = this.data,
            bbox = this.toBBox(item),
            path = [],
            indexes = [],
            i, parent, index, goingUp;

        // depth-first iterative tree traversal
        while (node || path.length) {

            if (!node) { // go up
                node = path.pop();
                parent = path[path.length - 1];
                i = indexes.pop();
                goingUp = true;
            }

            if (node.leaf) { // check current node
                index = findItem(item, node.children, equalsFn);

                if (index !== -1) {
                    // item found, remove the item and condense tree upwards
                    node.children.splice(index, 1);
                    path.push(node);
                    this._condense(path);
                    return this;
                }
            }

            if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
                path.push(node);
                indexes.push(i);
                i = 0;
                parent = node;
                node = node.children[0];

            } else if (parent) { // go right
                i++;
                node = parent.children[i];
                goingUp = false;

            } else node = null; // nothing found
        }

        return this;
    },

    toBBox: function (item) { return item; },

    compareMinX: compareNodeMinX,
    compareMinY: compareNodeMinY,

    toJSON: function () { return this.data; },

    fromJSON: function (data) {
        this.data = data;
        return this;
    },

    _all: function (node, result) {
        var nodesToSearch = [];
        while (node) {
            if (node.leaf) result.push.apply(result, node.children);
            else nodesToSearch.push.apply(nodesToSearch, node.children);

            node = nodesToSearch.pop();
        }
        return result;
    },

    _build: function (items, left, right, height) {

        var N = right - left + 1,
            M = this._maxEntries,
            node;

        if (N <= M) {
            // reached leaf level; return leaf
            node = createNode(items.slice(left, right + 1));
            calcBBox(node, this.toBBox);
            return node;
        }

        if (!height) {
            // target height of the bulk-loaded tree
            height = Math.ceil(Math.log(N) / Math.log(M));

            // target number of root entries to maximize storage utilization
            M = Math.ceil(N / Math.pow(M, height - 1));
        }

        node = createNode([]);
        node.leaf = false;
        node.height = height;

        // split the items into M mostly square tiles

        var N2 = Math.ceil(N / M),
            N1 = N2 * Math.ceil(Math.sqrt(M)),
            i, j, right2, right3;

        multiSelect(items, left, right, N1, this.compareMinX);

        for (i = left; i <= right; i += N1) {

            right2 = Math.min(i + N1 - 1, right);

            multiSelect(items, i, right2, N2, this.compareMinY);

            for (j = i; j <= right2; j += N2) {

                right3 = Math.min(j + N2 - 1, right2);

                // pack each entry recursively
                node.children.push(this._build(items, j, right3, height - 1));
            }
        }

        calcBBox(node, this.toBBox);

        return node;
    },

    _chooseSubtree: function (bbox, node, level, path) {

        var i, len, child, targetNode, area, enlargement, minArea, minEnlargement;

        while (true) {
            path.push(node);

            if (node.leaf || path.length - 1 === level) break;

            minArea = minEnlargement = Infinity;

            for (i = 0, len = node.children.length; i < len; i++) {
                child = node.children[i];
                area = bboxArea(child);
                enlargement = enlargedArea(bbox, child) - area;

                // choose entry with the least area enlargement
                if (enlargement < minEnlargement) {
                    minEnlargement = enlargement;
                    minArea = area < minArea ? area : minArea;
                    targetNode = child;

                } else if (enlargement === minEnlargement) {
                    // otherwise choose one with the smallest area
                    if (area < minArea) {
                        minArea = area;
                        targetNode = child;
                    }
                }
            }

            node = targetNode || node.children[0];
        }

        return node;
    },

    _insert: function (item, level, isNode) {

        var toBBox = this.toBBox,
            bbox = isNode ? item : toBBox(item),
            insertPath = [];

        // find the best node for accommodating the item, saving all nodes along the path too
        var node = this._chooseSubtree(bbox, this.data, level, insertPath);

        // put the item into the node
        node.children.push(item);
        extend(node, bbox);

        // split on node overflow; propagate upwards if necessary
        while (level >= 0) {
            if (insertPath[level].children.length > this._maxEntries) {
                this._split(insertPath, level);
                level--;
            } else break;
        }

        // adjust bboxes along the insertion path
        this._adjustParentBBoxes(bbox, insertPath, level);
    },

    // split overflowed node into two
    _split: function (insertPath, level) {

        var node = insertPath[level],
            M = node.children.length,
            m = this._minEntries;

        this._chooseSplitAxis(node, m, M);

        var splitIndex = this._chooseSplitIndex(node, m, M);

        var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
        newNode.height = node.height;
        newNode.leaf = node.leaf;

        calcBBox(node, this.toBBox);
        calcBBox(newNode, this.toBBox);

        if (level) insertPath[level - 1].children.push(newNode);
        else this._splitRoot(node, newNode);
    },

    _splitRoot: function (node, newNode) {
        // split root node
        this.data = createNode([node, newNode]);
        this.data.height = node.height + 1;
        this.data.leaf = false;
        calcBBox(this.data, this.toBBox);
    },

    _chooseSplitIndex: function (node, m, M) {

        var i, bbox1, bbox2, overlap, area, minOverlap, minArea, index;

        minOverlap = minArea = Infinity;

        for (i = m; i <= M - m; i++) {
            bbox1 = distBBox(node, 0, i, this.toBBox);
            bbox2 = distBBox(node, i, M, this.toBBox);

            overlap = intersectionArea(bbox1, bbox2);
            area = bboxArea(bbox1) + bboxArea(bbox2);

            // choose distribution with minimum overlap
            if (overlap < minOverlap) {
                minOverlap = overlap;
                index = i;

                minArea = area < minArea ? area : minArea;

            } else if (overlap === minOverlap) {
                // otherwise choose distribution with minimum area
                if (area < minArea) {
                    minArea = area;
                    index = i;
                }
            }
        }

        return index;
    },

    // sorts node children by the best axis for split
    _chooseSplitAxis: function (node, m, M) {

        var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX,
            compareMinY = node.leaf ? this.compareMinY : compareNodeMinY,
            xMargin = this._allDistMargin(node, m, M, compareMinX),
            yMargin = this._allDistMargin(node, m, M, compareMinY);

        // if total distributions margin value is minimal for x, sort by minX,
        // otherwise it's already sorted by minY
        if (xMargin < yMargin) node.children.sort(compareMinX);
    },

    // total margin of all possible split distributions where each node is at least m full
    _allDistMargin: function (node, m, M, compare) {

        node.children.sort(compare);

        var toBBox = this.toBBox,
            leftBBox = distBBox(node, 0, m, toBBox),
            rightBBox = distBBox(node, M - m, M, toBBox),
            margin = bboxMargin(leftBBox) + bboxMargin(rightBBox),
            i, child;

        for (i = m; i < M - m; i++) {
            child = node.children[i];
            extend(leftBBox, node.leaf ? toBBox(child) : child);
            margin += bboxMargin(leftBBox);
        }

        for (i = M - m - 1; i >= m; i--) {
            child = node.children[i];
            extend(rightBBox, node.leaf ? toBBox(child) : child);
            margin += bboxMargin(rightBBox);
        }

        return margin;
    },

    _adjustParentBBoxes: function (bbox, path, level) {
        // adjust bboxes along the given tree path
        for (var i = level; i >= 0; i--) {
            extend(path[i], bbox);
        }
    },

    _condense: function (path) {
        // go through the path, removing empty nodes and updating bboxes
        for (var i = path.length - 1, siblings; i >= 0; i--) {
            if (path[i].children.length === 0) {
                if (i > 0) {
                    siblings = path[i - 1].children;
                    siblings.splice(siblings.indexOf(path[i]), 1);

                } else this.clear();

            } else calcBBox(path[i], this.toBBox);
        }
    },

    _initFormat: function (format) {
        // data format (minX, minY, maxX, maxY accessors)

        // uses eval-type function compilation instead of just accepting a toBBox function
        // because the algorithms are very sensitive to sorting functions performance,
        // so they should be dead simple and without inner calls

        var compareArr = ['return a', ' - b', ';'];

        this.compareMinX = new Function('a', 'b', compareArr.join(format[0]));
        this.compareMinY = new Function('a', 'b', compareArr.join(format[1]));

        this.toBBox = new Function('a',
            'return {minX: a' + format[0] +
            ', minY: a' + format[1] +
            ', maxX: a' + format[2] +
            ', maxY: a' + format[3] + '};');
    }
};

function findItem(item, items, equalsFn) {
    if (!equalsFn) return items.indexOf(item);

    for (var i = 0; i < items.length; i++) {
        if (equalsFn(item, items[i])) return i;
    }
    return -1;
}

// calculate node's bbox from bboxes of its children
function calcBBox(node, toBBox) {
    distBBox(node, 0, node.children.length, toBBox, node);
}

// min bounding rectangle of node children from k to p-1
function distBBox(node, k, p, toBBox, destNode) {
    if (!destNode) destNode = createNode(null);
    destNode.minX = Infinity;
    destNode.minY = Infinity;
    destNode.maxX = -Infinity;
    destNode.maxY = -Infinity;

    for (var i = k, child; i < p; i++) {
        child = node.children[i];
        extend(destNode, node.leaf ? toBBox(child) : child);
    }

    return destNode;
}

function extend(a, b) {
    a.minX = Math.min(a.minX, b.minX);
    a.minY = Math.min(a.minY, b.minY);
    a.maxX = Math.max(a.maxX, b.maxX);
    a.maxY = Math.max(a.maxY, b.maxY);
    return a;
}

function compareNodeMinX(a, b) { return a.minX - b.minX; }
function compareNodeMinY(a, b) { return a.minY - b.minY; }

function bboxArea(a)   { return (a.maxX - a.minX) * (a.maxY - a.minY); }
function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }

function enlargedArea(a, b) {
    return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
           (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
}

function intersectionArea(a, b) {
    var minX = Math.max(a.minX, b.minX),
        minY = Math.max(a.minY, b.minY),
        maxX = Math.min(a.maxX, b.maxX),
        maxY = Math.min(a.maxY, b.maxY);

    return Math.max(0, maxX - minX) *
           Math.max(0, maxY - minY);
}

function contains(a, b) {
    return a.minX <= b.minX &&
           a.minY <= b.minY &&
           b.maxX <= a.maxX &&
           b.maxY <= a.maxY;
}

function intersects(a, b) {
    return b.minX <= a.maxX &&
           b.minY <= a.maxY &&
           b.maxX >= a.minX &&
           b.maxY >= a.minY;
}

function createNode(children) {
    return {
        children: children,
        height: 1,
        leaf: true,
        minX: Infinity,
        minY: Infinity,
        maxX: -Infinity,
        maxY: -Infinity
    };
}

// sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
// combines selection algorithm with binary divide & conquer approach

function multiSelect(arr, left, right, n, compare) {
    var stack = [left, right],
        mid;

    while (stack.length) {
        right = stack.pop();
        left = stack.pop();

        if (right - left <= n) continue;

        mid = left + Math.ceil((right - left) / n / 2) * n;
        quickselect(arr, mid, left, right, compare);

        stack.push(left, mid, mid, right);
    }
}

},{"quickselect":"rbush/node_modules/quickselect/index"}],"rbush/node_modules/quickselect/index":[function(require,module,exports){
'use strict';

module.exports = partialSort;

// Floyd-Rivest selection algorithm:
// Rearrange items so that all items in the [left, k] range are smaller than all items in (k, right];
// The k-th element will have the (k - left + 1)th smallest value in [left, right]

function partialSort(arr, k, left, right, compare) {
    left = left || 0;
    right = right || (arr.length - 1);
    compare = compare || defaultCompare;

    while (right > left) {
        if (right - left > 600) {
            var n = right - left + 1;
            var m = k - left + 1;
            var z = Math.log(n);
            var s = 0.5 * Math.exp(2 * z / 3);
            var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
            var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
            var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
            partialSort(arr, k, newLeft, newRight, compare);
        }

        var t = arr[k];
        var i = left;
        var j = right;

        swap(arr, left, k);
        if (compare(arr[right], t) > 0) swap(arr, left, right);

        while (i < j) {
            swap(arr, i, j);
            i++;
            j--;
            while (compare(arr[i], t) < 0) i++;
            while (compare(arr[j], t) > 0) j--;
        }

        if (compare(arr[left], t) === 0) swap(arr, left, j);
        else {
            j++;
            swap(arr, j, right);
        }

        if (j <= k) left = j + 1;
        if (k <= j) right = j - 1;
    }
}

function swap(arr, i, j) {
    var tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

function defaultCompare(a, b) {
    return a < b ? -1 : a > b ? 1 : 0;
}

},{}],"sprintf":[function(require,module,exports){
/**
sprintf() for JavaScript 0.7-beta1
http://www.diveintojavascript.com/projects/javascript-sprintf

Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of sprintf() for JavaScript nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Changelog:
2010.11.07 - 0.7-beta1-node
  - converted it to a node.js compatible module

2010.09.06 - 0.7-beta1
  - features: vsprintf, support for named placeholders
  - enhancements: format cache, reduced global namespace pollution

2010.05.22 - 0.6:
 - reverted to 0.4 and fixed the bug regarding the sign of the number 0
 Note:
 Thanks to Raphael Pigulla <raph (at] n3rd [dot) org> (http://www.n3rd.org/)
 who warned me about a bug in 0.5, I discovered that the last update was
 a regress. I appologize for that.

2010.05.09 - 0.5:
 - bug fix: 0 is now preceeded with a + sign
 - bug fix: the sign was not at the right position on padded results (Kamal Abdali)
 - switched from GPL to BSD license

2007.10.21 - 0.4:
 - unit test and patch (David Baird)

2007.09.17 - 0.3:
 - bug fix: no longer throws exception on empty paramenters (Hans Pufal)

2007.09.11 - 0.2:
 - feature: added argument swapping

2007.04.03 - 0.1:
 - initial release
**/

var sprintf = (function() {
	function get_type(variable) {
		return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
	}
	function str_repeat(input, multiplier) {
		for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
		return output.join('');
	}

	var str_format = function() {
		if (!str_format.cache.hasOwnProperty(arguments[0])) {
			str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
		}
		return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
	};

	// convert object to simple one line string without indentation or
	// newlines. Note that this implementation does not print array
	// values to their actual place for sparse arrays. 
	//
	// For example sparse array like this
	//    l = []
	//    l[4] = 1
	// Would be printed as "[1]" instead of "[, , , , 1]"
	// 
	// If argument 'seen' is not null and array the function will check for 
	// circular object references from argument.
	str_format.object_stringify = function(obj, depth, maxdepth, seen) {
		var str = '';
		if (obj != null) {
			switch( typeof(obj) ) {
			case 'function': 
				return '[Function' + (obj.name ? ': '+obj.name : '') + ']';
			    break;
			case 'object':
				if ( obj instanceof Error) { return '[' + obj.toString() + ']' };
				if (depth >= maxdepth) return '[Object]'
				if (seen) {
					// add object to seen list
					seen = seen.slice(0)
					seen.push(obj);
				}
				if (obj.length != null) { //array
					str += '[';
					var arr = []
					for (var i in obj) {
						if (seen && seen.indexOf(obj[i]) >= 0) arr.push('[Circular]');
						else arr.push(str_format.object_stringify(obj[i], depth+1, maxdepth, seen));
					}
					str += arr.join(', ') + ']';
				} else if ('getMonth' in obj) { // date
					return 'Date(' + obj + ')';
				} else { // object
					str += '{';
					var arr = []
					for (var k in obj) { 
						if(obj.hasOwnProperty(k)) {
							if (seen && seen.indexOf(obj[k]) >= 0) arr.push(k + ': [Circular]');
							else arr.push(k +': ' +str_format.object_stringify(obj[k], depth+1, maxdepth, seen)); 
						}
					}
					str += arr.join(', ') + '}';
				}
				return str;
				break;
			case 'string':				
				return '"' + obj + '"';
				break
			}
		}
		return '' + obj;
	}

	str_format.format = function(parse_tree, argv) {
		var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
		for (i = 0; i < tree_length; i++) {
			node_type = get_type(parse_tree[i]);
			if (node_type === 'string') {
				output.push(parse_tree[i]);
			}
			else if (node_type === 'array') {
				match = parse_tree[i]; // convenience purposes only
				if (match[2]) { // keyword argument
					arg = argv[cursor];
					for (k = 0; k < match[2].length; k++) {
						if (!arg.hasOwnProperty(match[2][k])) {
							throw new Error(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
						}
						arg = arg[match[2][k]];
					}
				}
				else if (match[1]) { // positional argument (explicit)
					arg = argv[match[1]];
				}
				else { // positional argument (implicit)
					arg = argv[cursor++];
				}

				if (/[^sO]/.test(match[8]) && (get_type(arg) != 'number')) {
					throw new Error(sprintf('[sprintf] expecting number but found %s "' + arg + '"', get_type(arg)));
				}
				switch (match[8]) {
					case 'b': arg = arg.toString(2); break;
					case 'c': arg = String.fromCharCode(arg); break;
					case 'd': arg = parseInt(arg, 10); break;
					case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
					case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
				    case 'O': arg = str_format.object_stringify(arg, 0, parseInt(match[7]) || 5); break;
					case 'o': arg = arg.toString(8); break;
					case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
					case 'u': arg = Math.abs(arg); break;
					case 'x': arg = arg.toString(16); break;
					case 'X': arg = arg.toString(16).toUpperCase(); break;
				}
				arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
				pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
				pad_length = match[6] - String(arg).length;
				pad = match[6] ? str_repeat(pad_character, pad_length) : '';
				output.push(match[5] ? arg + pad : pad + arg);
			}
		}
		return output.join('');
	};

	str_format.cache = {};

	str_format.parse = function(fmt) {
		var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
		while (_fmt) {
			if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
				parse_tree.push(match[0]);
			}
			else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
				parse_tree.push('%');
			}
			else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosOuxX])/.exec(_fmt)) !== null) {
				if (match[2]) {
					arg_names |= 1;
					var field_list = [], replacement_field = match[2], field_match = [];
					if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
						field_list.push(field_match[1]);
						while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
							if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
								field_list.push(field_match[1]);
							}
							else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
								field_list.push(field_match[1]);
							}
							else {
								throw new Error('[sprintf] ' + replacement_field);
							}
						}
					}
					else {
                        throw new Error('[sprintf] ' + replacement_field);
					}
					match[2] = field_list;
				}
				else {
					arg_names |= 2;
				}
				if (arg_names === 3) {
					throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
				}
				parse_tree.push(match);
			}
			else {
				throw new Error('[sprintf] ' + _fmt);
			}
			_fmt = _fmt.substring(match[0].length);
		}
		return parse_tree;
	};

	return str_format;
})();

var vsprintf = function(fmt, argv) {
	var argvClone = argv.slice();
	argvClone.unshift(fmt);
	return sprintf.apply(null, argvClone);
};

module.exports = sprintf;
sprintf.sprintf = sprintf;
sprintf.vsprintf = vsprintf;

},{}],"timezone/index":[function(require,module,exports){
!function (definition) {
  if (typeof module == "object" && module.exports) module.exports = definition();
  else if (typeof define == "function") define(definition);
  else this.tz = definition();
} (function () {
/*
  function die () {
    console.log.apply(console, __slice.call(arguments, 0));
    return process.exit(1);
  }

  function say () { return console.log.apply(console, __slice.call(arguments, 0)) }
*/
  function actualize (entry, rule, year) {
    var actualized, date = rule.day[1];

    do {
      actualized = new Date(Date.UTC(year, rule.month, Math.abs(date++)));
    } while (rule.day[0] < 7 && actualized.getUTCDay() != rule.day[0])

    actualized = {
      clock: rule.clock,
      sort: actualized.getTime(),
      rule: rule,
      save: rule.save * 6e4,
      offset: entry.offset
    };

    actualized[actualized.clock] = actualized.sort + rule.time * 6e4;

    if (actualized.posix) {
      actualized.wallclock = actualized[actualized.clock] + (entry.offset + rule.saved);
    } else {
      actualized.posix = actualized[actualized.clock] - (entry.offset + rule.saved);
    }

    return actualized;
  }

  function find (request, clock, time) {
    var i, I, entry, found, zone = request[request.zone], actualized = [], abbrev, rules
      , j, year = new Date(time).getUTCFullYear(), off = 1;
    for (i = 1, I = zone.length; i < I; i++) if (zone[i][clock] <= time) break;
    entry = zone[i];
    if (entry.rules) {
      rules = request[entry.rules];
      for (j = year + 1; j >= year - off; --j)
        for (i = 0, I = rules.length; i < I; i++)
          if (rules[i].from <= j && j <= rules[i].to) actualized.push(actualize(entry, rules[i], j));
          else if (rules[i].to < j && off == 1) off = j - rules[i].to;
      actualized.sort(function (a, b) { return a.sort - b.sort });
      for (i = 0, I = actualized.length; i < I; i++) {
        if (time >= actualized[i][clock] && actualized[i][actualized[i].clock] > entry[actualized[i].clock]) found = actualized[i];
      }
    }
    if (found) {
      if (abbrev = /^(.*)\/(.*)$/.exec(entry.format)) {
        found.abbrev = abbrev[found.save ? 2 : 1];
      } else {
        found.abbrev = entry.format.replace(/%s/, found.rule.letter);
      }
    }
    return found || entry;
  }

  function convertToWallclock (request, posix) {
    if (request.zone == "UTC") return posix;
    request.entry = find(request, "posix", posix);
    return posix + request.entry.offset + request.entry.save;
  }

  function convertToPOSIX (request, wallclock) {
    if (request.zone == "UTC") return wallclock;

    var entry, diff;
    request.entry = entry = find(request, "wallclock", wallclock);
    diff = wallclock - entry.wallclock;

    return 0 < diff && diff < entry.save ? null : wallclock - entry.offset - entry.save;
  }

  function adjust (request, posix, match) {
    var increment = +(match[1] + 1) // conversion necessary for week day addition
      , offset = match[2] * increment
      , index = UNITS.indexOf(match[3].toLowerCase())
      , date
      ;
    if (index > 9) {
      posix += offset * TIME[index - 10];
    } else {
      date = new Date(convertToWallclock(request, posix));
      if (index < 7) {
        while (offset) {
          date.setUTCDate(date.getUTCDate() + increment);
          if (date.getUTCDay() == index) offset -= increment;
        }
      } else if (index == 7) {
        date.setUTCFullYear(date.getUTCFullYear() + offset);
      } else if (index == 8) {
        date.setUTCMonth(date.getUTCMonth() + offset);
      } else {
        date.setUTCDate(date.getUTCDate() + offset);
      }
      if ((posix = convertToPOSIX(request, date.getTime())) == null) {
        posix = convertToPOSIX(request, date.getTime() + 864e5 * increment) - 864e5 * increment;
      }
    }
    return posix;
  }

  function convert (vargs) {
    if (!vargs.length) return "0.0.38";

    var request = Object.create(this)
      , adjustments = []
      , i, I, $, argument, date
      ;

    for (i = 0; i < vargs.length; i++) { // leave the for loop alone, it works.
      argument = vargs[i];
      // https://twitter.com/bigeasy/status/215112186572439552
      if (Array.isArray(argument)) {
        if (!i && !isNaN(argument[1])) {
          date = argument;
        } else {
          argument.splice.apply(vargs, [ i--, 1 ].concat(argument));
        }
      } else if (isNaN(argument)) {
        $ = typeof argument;
        if ($ == "string") {
          if (~argument.indexOf("%")) {
            request.format = argument;
          } else if (!i && argument == "*") {
            date = argument;
          } else if (!i && ($ = /^(\d{4})-(\d{2})-(\d{2})(?:[T\s](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|(([+-])(\d{2}(:\d{2}){0,2})))?)?$/.exec(argument))) {
            date = [];
            date.push.apply(date, $.slice(1, 8));
            if ($[9]) {
              date.push($[10] + 1);
              date.push.apply(date, $[11].split(/:/));
            } else if ($[8]) {
              date.push(1);
            }
          } else if (/^\w{2,3}_\w{2}$/.test(argument)) {
            request.locale = argument;
          } else if ($ = UNIT_RE.exec(argument)) {
            adjustments.push($);
          } else {
            request.zone = argument;
          }
        } else if ($ == "function") {
          if ($ = argument.call(request)) return $;
        } else if (/^\w{2,3}_\w{2}$/.test(argument.name)) {
          request[argument.name] = argument;
        } else if (argument.zones) {
          for ($ in argument.zones) request[$] = argument.zones[$];
          for ($ in argument.rules) request[$] = argument.rules[$];
        }
      } else if (!i) {
        date = argument;
      }
    }

    if (!request[request.locale]) delete request.locale;
    if (!request[request.zone]) delete request.zone;

    if (date != null) {
      if (date == "*") {
        date = request.clock();
      } else if (Array.isArray(date)) {
        I = !date[7];
        for (i = 0; i < 11; i++) date[i] = +(date[i] || 0); // conversion necessary for decrement
        --date[1]; // Grr..
        date = Date.UTC.apply(Date.UTC, date.slice(0, 8)) +
          -date[7] * (date[8] * 36e5 + date[9] * 6e4 + date[10] * 1e3);
      } else {
        date = Math.floor(date);
      }
      if (!isNaN(date)) {
        if (I) date = convertToPOSIX(request, date);

        if (date == null) return date;

        for (i = 0, I = adjustments.length; i < I; i++) {
          date = adjust(request, date, adjustments[i]);
        }

        if (!request.format) return date;

        $ = new Date(convertToWallclock(request, date));
        return request.format.replace(/%([-0_^]?)(:{0,3})(\d*)(.)/g,
        function (value, flag, colons, padding, specifier) {
          var f, fill = "0", pad;
          if (f = request[specifier]) {
            value = String(f.call(request, $, date, flag, colons.length));
            if ((flag || f.style) == "_") fill = " ";
            pad = flag == "-" ? 0 : f.pad || 0;
            while (value.length < pad) value = fill + value;
            pad = flag == "-" ? 0 : padding || f.pad;
            while (value.length < pad) value = fill + value;
            if (specifier == "N" && pad < value.length) value = value.slice(0, pad);
            if (flag == "^") value = value.toUpperCase();
          }
          return value;
        });
      }
    }

    return function () { return request.convert(arguments) };
  }

  var context =
    { clock: function () { return +(new Date()) }
    , zone: "UTC"
    , entry: { abbrev: "UTC", offset: 0, save: 0 }
    , UTC: 1
    , z: function(date, posix, flag, delimiters) {
        var offset = this.entry.offset + this.entry.save
          , seconds = Math.abs(offset / 1000), parts = [], part = 3600, i, z;
        for (i = 0; i < 3; i++) {
          parts.push(("0" + Math.floor(seconds / part)).slice(-2));
          seconds %= part;
          part /= 60;
        }
        if (flag == "^" && !offset) return "Z";
        if (flag == "^") delimiters = 3;
        if (delimiters == 3) {
          z = parts.join(":");
          z = z.replace(/:00$/, "");
          if (flag != "^") z = z.replace(/:00$/, "");
        } else if (delimiters) {
          z = parts.slice(0, delimiters + 1).join(":");
          if (flag == "^") z = z.replace(/:00$/, "");
        } else {
          z = parts.slice(0, 2).join("");
        }
        z = (offset < 0 ? "-" : "+") + z;
        z = z.replace(/([-+])(0)/, { "_": " $1", "-": "$1" }[flag] || "$1$2");
        return z;
      }
    , "%": function(date) { return "%" }
    , n: function (date) { return "\n" }
    , t: function (date) { return "\t" }
    , U: function (date) { return weekOfYear(date, 0) }
    , W: function (date) { return weekOfYear(date, 1) }
    , V: function (date) { return isoWeek(date)[0] }
    , G: function (date) { return isoWeek(date)[1] }
    , g: function (date) { return isoWeek(date)[1] % 100 }
    , j: function (date) { return Math.floor((date.getTime() - Date.UTC(date.getUTCFullYear(), 0)) / 864e5) + 1 }
    , s: function (date) { return Math.floor(date.getTime() / 1000) }
    , C: function (date) { return Math.floor(date.getUTCFullYear() / 100) }
    , N: function (date) { return date.getTime() % 1000 * 1000000 }
    , m: function (date) { return date.getUTCMonth() + 1 }
    , Y: function (date) { return date.getUTCFullYear() }
    , y: function (date) { return date.getUTCFullYear() % 100 }
    , H: function (date) { return date.getUTCHours() }
    , M: function (date) { return date.getUTCMinutes() }
    , S: function (date) { return date.getUTCSeconds() }
    , e: function (date) { return date.getUTCDate() }
    , d: function (date) { return date.getUTCDate() }
    , u: function (date) { return date.getUTCDay() || 7 }
    , w: function (date) { return date.getUTCDay() }
    , l: function (date) { return date.getUTCHours() % 12 || 12 }
    , I: function (date) { return date.getUTCHours() % 12 || 12 }
    , k: function (date) { return date.getUTCHours() }
    , Z: function (date) { return this.entry.abbrev }
    , a: function (date) { return this[this.locale].day.abbrev[date.getUTCDay()] }
    , A: function (date) { return this[this.locale].day.full[date.getUTCDay()] }
    , h: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    , b: function (date) { return this[this.locale].month.abbrev[date.getUTCMonth()] }
    , B: function (date) { return this[this.locale].month.full[date.getUTCMonth()] }
    , P: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)].toLowerCase() }
    , p: function (date) { return this[this.locale].meridiem[Math.floor(date.getUTCHours() / 12)] }
    , R: function (date, posix) { return this.convert([ posix, "%H:%M" ]) }
    , T: function (date, posix) { return this.convert([ posix, "%H:%M:%S" ]) }
    , D: function (date, posix) { return this.convert([ posix, "%m/%d/%y" ]) }
    , F: function (date, posix) { return this.convert([ posix, "%Y-%m-%d" ]) }
    , x: function (date, posix) { return this.convert([ posix, this[this.locale].date ]) }
    , r: function (date, posix) { return this.convert([ posix, this[this.locale].time12 || '%I:%M:%S' ]) }
    , X: function (date, posix) { return this.convert([ posix, this[this.locale].time24 ]) }
    , c: function (date, posix) { return this.convert([ posix, this[this.locale].dateTime ]) }
    , convert: convert
    , locale: "en_US"
    , en_US: {
        date: "%m/%d/%Y",
        time24: "%I:%M:%S %p",
        time12: "%I:%M:%S %p",
        dateTime: "%a %d %b %Y %I:%M:%S %p %Z",
        meridiem: [ "AM", "PM" ],
        month: {
          abbrev: "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".split("|"),
          full: "January|February|March|April|May|June|July|August|September|October|November|December".split("|")
        },
        day: {
          abbrev: "Sun|Mon|Tue|Wed|Thu|Fri|Sat".split("|"),
          full: "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday".split("|")
        }
      }
    };
  var UNITS = "Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|year|month|day|hour|minute|second|millisecond"
    , UNIT_RE = new RegExp("^\\s*([+-])(\\d+)\\s+(" + UNITS + ")s?\\s*$", "i")
    , TIME = [ 36e5, 6e4, 1e3, 1 ]
    ;
  UNITS = UNITS.toLowerCase().split("|");

  "delmHMSUWVgCIky".replace(/./g, function (e) { context[e].pad = 2 });

  context.N.pad = 9;
  context.j.pad = 3;

  context.k.style = "_";
  context.l.style = "_";
  context.e.style = "_";

  function weekOfYear (date, startOfWeek) {
    var diff, nyd, weekStart;
    nyd = new Date(Date.UTC(date.getUTCFullYear(), 0));
    diff = Math.floor((date.getTime() - nyd.getTime()) / 864e5);
    if (nyd.getUTCDay() == startOfWeek) {
      weekStart = 0;
    } else {
      weekStart = 7 - nyd.getUTCDay() + startOfWeek;
      if (weekStart == 8) {
        weekStart = 1;
      }
    }
    return diff >= weekStart ? Math.floor((diff - weekStart) / 7) + 1 : 0;
  }

  function isoWeek (date) {
    var nyd, nyy, week;
    nyy = date.getUTCFullYear();
    nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
    week = weekOfYear(date, 1) + (nyd > 1 && nyd <= 4 ? 1 : 0);
    if (!week) {
      nyy = date.getUTCFullYear() - 1;
      nyd = new Date(Date.UTC(nyy, 0)).getUTCDay();
      week = nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29) ? 53 : 52;
      return [week, date.getUTCFullYear() - 1];
    } else if (week == 53 && !(nyd == 4 || (nyd == 3 && new Date(nyy, 1, 29).getDate() == 29))) {
      return [1, date.getUTCFullYear() + 1];
    } else {
      return [week, date.getUTCFullYear()];
    }
  }

  return function () { return context.convert(arguments) };
});

},{}],"underscore":[function(require,module,exports){
//     Underscore.js 1.8.3
//     http://underscorejs.org
//     (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var
    push             = ArrayProto.push,
    slice            = ArrayProto.slice,
    toString         = ObjProto.toString,
    hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind,
    nativeCreate       = Object.create;

  // Naked function reference for surrogate-prototype-swapping.
  var Ctor = function(){};

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

  // Current version.
  _.VERSION = '1.8.3';

  // Internal function that returns an efficient (for current engines) version
  // of the passed-in callback, to be repeatedly applied in other Underscore
  // functions.
  var optimizeCb = function(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount == null ? 3 : argCount) {
      case 1: return function(value) {
        return func.call(context, value);
      };
      case 2: return function(value, other) {
        return func.call(context, value, other);
      };
      case 3: return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
      case 4: return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
    }
    return function() {
      return func.apply(context, arguments);
    };
  };

  // A mostly-internal function to generate callbacks that can be applied
  // to each element in a collection, returning the desired result — either
  // identity, an arbitrary callback, a property matcher, or a property accessor.
  var cb = function(value, context, argCount) {
    if (value == null) return _.identity;
    if (_.isFunction(value)) return optimizeCb(value, context, argCount);
    if (_.isObject(value)) return _.matcher(value);
    return _.property(value);
  };
  _.iteratee = function(value, context) {
    return cb(value, context, Infinity);
  };

  // An internal function for creating assigner functions.
  var createAssigner = function(keysFunc, undefinedOnly) {
    return function(obj) {
      var length = arguments.length;
      if (length < 2 || obj == null) return obj;
      for (var index = 1; index < length; index++) {
        var source = arguments[index],
            keys = keysFunc(source),
            l = keys.length;
        for (var i = 0; i < l; i++) {
          var key = keys[i];
          if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
        }
      }
      return obj;
    };
  };

  // An internal function for creating a new object that inherits from another.
  var baseCreate = function(prototype) {
    if (!_.isObject(prototype)) return {};
    if (nativeCreate) return nativeCreate(prototype);
    Ctor.prototype = prototype;
    var result = new Ctor;
    Ctor.prototype = null;
    return result;
  };

  var property = function(key) {
    return function(obj) {
      return obj == null ? void 0 : obj[key];
    };
  };

  // Helper for collection methods to determine whether a collection
  // should be iterated as an array or as an object
  // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
  // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
  var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
  var getLength = property('length');
  var isArrayLike = function(collection) {
    var length = getLength(collection);
    return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
  };

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles raw objects in addition to array-likes. Treats all
  // sparse array-likes as if they were dense.
  _.each = _.forEach = function(obj, iteratee, context) {
    iteratee = optimizeCb(iteratee, context);
    var i, length;
    if (isArrayLike(obj)) {
      for (i = 0, length = obj.length; i < length; i++) {
        iteratee(obj[i], i, obj);
      }
    } else {
      var keys = _.keys(obj);
      for (i = 0, length = keys.length; i < length; i++) {
        iteratee(obj[keys[i]], keys[i], obj);
      }
    }
    return obj;
  };

  // Return the results of applying the iteratee to each element.
  _.map = _.collect = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length,
        results = Array(length);
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      results[index] = iteratee(obj[currentKey], currentKey, obj);
    }
    return results;
  };

  // Create a reducing function iterating left or right.
  function createReduce(dir) {
    // Optimized iterator function as using arguments.length
    // in the main function will deoptimize the, see #1991.
    function iterator(obj, iteratee, memo, keys, index, length) {
      for (; index >= 0 && index < length; index += dir) {
        var currentKey = keys ? keys[index] : index;
        memo = iteratee(memo, obj[currentKey], currentKey, obj);
      }
      return memo;
    }

    return function(obj, iteratee, memo, context) {
      iteratee = optimizeCb(iteratee, context, 4);
      var keys = !isArrayLike(obj) && _.keys(obj),
          length = (keys || obj).length,
          index = dir > 0 ? 0 : length - 1;
      // Determine the initial value if none is provided.
      if (arguments.length < 3) {
        memo = obj[keys ? keys[index] : index];
        index += dir;
      }
      return iterator(obj, iteratee, memo, keys, index, length);
    };
  }

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`.
  _.reduce = _.foldl = _.inject = createReduce(1);

  // The right-associative version of reduce, also known as `foldr`.
  _.reduceRight = _.foldr = createReduce(-1);

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, predicate, context) {
    var key;
    if (isArrayLike(obj)) {
      key = _.findIndex(obj, predicate, context);
    } else {
      key = _.findKey(obj, predicate, context);
    }
    if (key !== void 0 && key !== -1) return obj[key];
  };

  // Return all the elements that pass a truth test.
  // Aliased as `select`.
  _.filter = _.select = function(obj, predicate, context) {
    var results = [];
    predicate = cb(predicate, context);
    _.each(obj, function(value, index, list) {
      if (predicate(value, index, list)) results.push(value);
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, predicate, context) {
    return _.filter(obj, _.negate(cb(predicate)), context);
  };

  // Determine whether all of the elements match a truth test.
  // Aliased as `all`.
  _.every = _.all = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      if (!predicate(obj[currentKey], currentKey, obj)) return false;
    }
    return true;
  };

  // Determine if at least one element in the object matches a truth test.
  // Aliased as `any`.
  _.some = _.any = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = !isArrayLike(obj) && _.keys(obj),
        length = (keys || obj).length;
    for (var index = 0; index < length; index++) {
      var currentKey = keys ? keys[index] : index;
      if (predicate(obj[currentKey], currentKey, obj)) return true;
    }
    return false;
  };

  // Determine if the array or object contains a given item (using `===`).
  // Aliased as `includes` and `include`.
  _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) {
    if (!isArrayLike(obj)) obj = _.values(obj);
    if (typeof fromIndex != 'number' || guard) fromIndex = 0;
    return _.indexOf(obj, item, fromIndex) >= 0;
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    var isFunc = _.isFunction(method);
    return _.map(obj, function(value) {
      var func = isFunc ? method : value[method];
      return func == null ? func : func.apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, _.property(key));
  };

  // Convenience version of a common use case of `filter`: selecting only objects
  // containing specific `key:value` pairs.
  _.where = function(obj, attrs) {
    return _.filter(obj, _.matcher(attrs));
  };

  // Convenience version of a common use case of `find`: getting the first object
  // containing specific `key:value` pairs.
  _.findWhere = function(obj, attrs) {
    return _.find(obj, _.matcher(attrs));
  };

  // Return the maximum element (or element-based computation).
  _.max = function(obj, iteratee, context) {
    var result = -Infinity, lastComputed = -Infinity,
        value, computed;
    if (iteratee == null && obj != null) {
      obj = isArrayLike(obj) ? obj : _.values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value > result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      _.each(obj, function(value, index, list) {
        computed = iteratee(value, index, list);
        if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
          result = value;
          lastComputed = computed;
        }
      });
    }
    return result;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iteratee, context) {
    var result = Infinity, lastComputed = Infinity,
        value, computed;
    if (iteratee == null && obj != null) {
      obj = isArrayLike(obj) ? obj : _.values(obj);
      for (var i = 0, length = obj.length; i < length; i++) {
        value = obj[i];
        if (value < result) {
          result = value;
        }
      }
    } else {
      iteratee = cb(iteratee, context);
      _.each(obj, function(value, index, list) {
        computed = iteratee(value, index, list);
        if (computed < lastComputed || computed === Infinity && result === Infinity) {
          result = value;
          lastComputed = computed;
        }
      });
    }
    return result;
  };

  // Shuffle a collection, using the modern version of the
  // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
  _.shuffle = function(obj) {
    var set = isArrayLike(obj) ? obj : _.values(obj);
    var length = set.length;
    var shuffled = Array(length);
    for (var index = 0, rand; index < length; index++) {
      rand = _.random(0, index);
      if (rand !== index) shuffled[index] = shuffled[rand];
      shuffled[rand] = set[index];
    }
    return shuffled;
  };

  // Sample **n** random values from a collection.
  // If **n** is not specified, returns a single random element.
  // The internal `guard` argument allows it to work with `map`.
  _.sample = function(obj, n, guard) {
    if (n == null || guard) {
      if (!isArrayLike(obj)) obj = _.values(obj);
      return obj[_.random(obj.length - 1)];
    }
    return _.shuffle(obj).slice(0, Math.max(0, n));
  };

  // Sort the object's values by a criterion produced by an iteratee.
  _.sortBy = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value: value,
        index: index,
        criteria: iteratee(value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria;
      var b = right.criteria;
      if (a !== b) {
        if (a > b || a === void 0) return 1;
        if (a < b || b === void 0) return -1;
      }
      return left.index - right.index;
    }), 'value');
  };

  // An internal function used for aggregate "group by" operations.
  var group = function(behavior) {
    return function(obj, iteratee, context) {
      var result = {};
      iteratee = cb(iteratee, context);
      _.each(obj, function(value, index) {
        var key = iteratee(value, index, obj);
        behavior(result, value, key);
      });
      return result;
    };
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = group(function(result, value, key) {
    if (_.has(result, key)) result[key].push(value); else result[key] = [value];
  });

  // Indexes the object's values by a criterion, similar to `groupBy`, but for
  // when you know that your index values will be unique.
  _.indexBy = group(function(result, value, key) {
    result[key] = value;
  });

  // Counts instances of an object that group by a certain criterion. Pass
  // either a string attribute to count by, or a function that returns the
  // criterion.
  _.countBy = group(function(result, value, key) {
    if (_.has(result, key)) result[key]++; else result[key] = 1;
  });

  // Safely create a real, live array from anything iterable.
  _.toArray = function(obj) {
    if (!obj) return [];
    if (_.isArray(obj)) return slice.call(obj);
    if (isArrayLike(obj)) return _.map(obj, _.identity);
    return _.values(obj);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    if (obj == null) return 0;
    return isArrayLike(obj) ? obj.length : _.keys(obj).length;
  };

  // Split a collection into two arrays: one whose elements all satisfy the given
  // predicate, and one whose elements all do not satisfy the predicate.
  _.partition = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var pass = [], fail = [];
    _.each(obj, function(value, key, obj) {
      (predicate(value, key, obj) ? pass : fail).push(value);
    });
    return [pass, fail];
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head` and `take`. The **guard** check
  // allows it to work with `_.map`.
  _.first = _.head = _.take = function(array, n, guard) {
    if (array == null) return void 0;
    if (n == null || guard) return array[0];
    return _.initial(array, array.length - n);
  };

  // Returns everything but the last entry of the array. Especially useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array.
  _.last = function(array, n, guard) {
    if (array == null) return void 0;
    if (n == null || guard) return array[array.length - 1];
    return _.rest(array, Math.max(0, array.length - n));
  };

  // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
  // Especially useful on the arguments object. Passing an **n** will return
  // the rest N values in the array.
  _.rest = _.tail = _.drop = function(array, n, guard) {
    return slice.call(array, n == null || guard ? 1 : n);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, _.identity);
  };

  // Internal implementation of a recursive `flatten` function.
  var flatten = function(input, shallow, strict, startIndex) {
    var output = [], idx = 0;
    for (var i = startIndex || 0, length = getLength(input); i < length; i++) {
      var value = input[i];
      if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
        //flatten current level of array or arguments object
        if (!shallow) value = flatten(value, shallow, strict);
        var j = 0, len = value.length;
        output.length += len;
        while (j < len) {
          output[idx++] = value[j++];
        }
      } else if (!strict) {
        output[idx++] = value;
      }
    }
    return output;
  };

  // Flatten out an array, either recursively (by default), or just one level.
  _.flatten = function(array, shallow) {
    return flatten(array, shallow, false);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iteratee, context) {
    if (!_.isBoolean(isSorted)) {
      context = iteratee;
      iteratee = isSorted;
      isSorted = false;
    }
    if (iteratee != null) iteratee = cb(iteratee, context);
    var result = [];
    var seen = [];
    for (var i = 0, length = getLength(array); i < length; i++) {
      var value = array[i],
          computed = iteratee ? iteratee(value, i, array) : value;
      if (isSorted) {
        if (!i || seen !== computed) result.push(value);
        seen = computed;
      } else if (iteratee) {
        if (!_.contains(seen, computed)) {
          seen.push(computed);
          result.push(value);
        }
      } else if (!_.contains(result, value)) {
        result.push(value);
      }
    }
    return result;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(flatten(arguments, true, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays.
  _.intersection = function(array) {
    var result = [];
    var argsLength = arguments.length;
    for (var i = 0, length = getLength(array); i < length; i++) {
      var item = array[i];
      if (_.contains(result, item)) continue;
      for (var j = 1; j < argsLength; j++) {
        if (!_.contains(arguments[j], item)) break;
      }
      if (j === argsLength) result.push(item);
    }
    return result;
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = flatten(arguments, true, true, 1);
    return _.filter(array, function(value){
      return !_.contains(rest, value);
    });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    return _.unzip(arguments);
  };

  // Complement of _.zip. Unzip accepts an array of arrays and groups
  // each array's elements on shared indices
  _.unzip = function(array) {
    var length = array && _.max(array, getLength).length || 0;
    var result = Array(length);

    for (var index = 0; index < length; index++) {
      result[index] = _.pluck(array, index);
    }
    return result;
  };

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function(list, values) {
    var result = {};
    for (var i = 0, length = getLength(list); i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

  // Generator function to create the findIndex and findLastIndex functions
  function createPredicateIndexFinder(dir) {
    return function(array, predicate, context) {
      predicate = cb(predicate, context);
      var length = getLength(array);
      var index = dir > 0 ? 0 : length - 1;
      for (; index >= 0 && index < length; index += dir) {
        if (predicate(array[index], index, array)) return index;
      }
      return -1;
    };
  }

  // Returns the first index on an array-like that passes a predicate test
  _.findIndex = createPredicateIndexFinder(1);
  _.findLastIndex = createPredicateIndexFinder(-1);

  // Use a comparator function to figure out the smallest index at which
  // an object should be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iteratee, context) {
    iteratee = cb(iteratee, context, 1);
    var value = iteratee(obj);
    var low = 0, high = getLength(array);
    while (low < high) {
      var mid = Math.floor((low + high) / 2);
      if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
    }
    return low;
  };

  // Generator function to create the indexOf and lastIndexOf functions
  function createIndexFinder(dir, predicateFind, sortedIndex) {
    return function(array, item, idx) {
      var i = 0, length = getLength(array);
      if (typeof idx == 'number') {
        if (dir > 0) {
            i = idx >= 0 ? idx : Math.max(idx + length, i);
        } else {
            length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
        }
      } else if (sortedIndex && idx && length) {
        idx = sortedIndex(array, item);
        return array[idx] === item ? idx : -1;
      }
      if (item !== item) {
        idx = predicateFind(slice.call(array, i, length), _.isNaN);
        return idx >= 0 ? idx + i : -1;
      }
      for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
        if (array[idx] === item) return idx;
      }
      return -1;
    };
  }

  // Return the position of the first occurrence of an item in an array,
  // or -1 if the item is not included in the array.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex);
  _.lastIndexOf = createIndexFinder(-1, _.findLastIndex);

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (stop == null) {
      stop = start || 0;
      start = 0;
    }
    step = step || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var range = Array(length);

    for (var idx = 0; idx < length; idx++, start += step) {
      range[idx] = start;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Determines whether to execute a function as a constructor
  // or a normal function with the provided arguments
  var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
    if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
    var self = baseCreate(sourceFunc.prototype);
    var result = sourceFunc.apply(self, args);
    if (_.isObject(result)) return result;
    return self;
  };

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
  // available.
  _.bind = function(func, context) {
    if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
    var args = slice.call(arguments, 2);
    var bound = function() {
      return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
    };
    return bound;
  };

  // Partially apply a function by creating a version that has had some of its
  // arguments pre-filled, without changing its dynamic `this` context. _ acts
  // as a placeholder, allowing any combination of arguments to be pre-filled.
  _.partial = function(func) {
    var boundArgs = slice.call(arguments, 1);
    var bound = function() {
      var position = 0, length = boundArgs.length;
      var args = Array(length);
      for (var i = 0; i < length; i++) {
        args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
      }
      while (position < arguments.length) args.push(arguments[position++]);
      return executeBound(func, bound, this, this, args);
    };
    return bound;
  };

  // Bind a number of an object's methods to that object. Remaining arguments
  // are the method names to be bound. Useful for ensuring that all callbacks
  // defined on an object belong to it.
  _.bindAll = function(obj) {
    var i, length = arguments.length, key;
    if (length <= 1) throw new Error('bindAll must be passed function names');
    for (i = 1; i < length; i++) {
      key = arguments[i];
      obj[key] = _.bind(obj[key], obj);
    }
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memoize = function(key) {
      var cache = memoize.cache;
      var address = '' + (hasher ? hasher.apply(this, arguments) : key);
      if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
      return cache[address];
    };
    memoize.cache = {};
    return memoize;
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){
      return func.apply(null, args);
    }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = _.partial(_.delay, _, 1);

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time. Normally, the throttled function will run
  // as much as it can, without ever going more than once per `wait` duration;
  // but if you'd like to disable the execution on the leading edge, pass
  // `{leading: false}`. To disable execution on the trailing edge, ditto.
  _.throttle = function(func, wait, options) {
    var context, args, result;
    var timeout = null;
    var previous = 0;
    if (!options) options = {};
    var later = function() {
      previous = options.leading === false ? 0 : _.now();
      timeout = null;
      result = func.apply(context, args);
      if (!timeout) context = args = null;
    };
    return function() {
      var now = _.now();
      if (!previous && options.leading === false) previous = now;
      var remaining = wait - (now - previous);
      context = this;
      args = arguments;
      if (remaining <= 0 || remaining > wait) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = null;
        }
        previous = now;
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      } else if (!timeout && options.trailing !== false) {
        timeout = setTimeout(later, remaining);
      }
      return result;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds. If `immediate` is passed, trigger the function on the
  // leading edge, instead of the trailing.
  _.debounce = function(func, wait, immediate) {
    var timeout, args, context, timestamp, result;

    var later = function() {
      var last = _.now() - timestamp;

      if (last < wait && last >= 0) {
        timeout = setTimeout(later, wait - last);
      } else {
        timeout = null;
        if (!immediate) {
          result = func.apply(context, args);
          if (!timeout) context = args = null;
        }
      }
    };

    return function() {
      context = this;
      args = arguments;
      timestamp = _.now();
      var callNow = immediate && !timeout;
      if (!timeout) timeout = setTimeout(later, wait);
      if (callNow) {
        result = func.apply(context, args);
        context = args = null;
      }

      return result;
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return _.partial(wrapper, func);
  };

  // Returns a negated version of the passed-in predicate.
  _.negate = function(predicate) {
    return function() {
      return !predicate.apply(this, arguments);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var args = arguments;
    var start = args.length - 1;
    return function() {
      var i = start;
      var result = args[start].apply(this, arguments);
      while (i--) result = args[i].call(this, result);
      return result;
    };
  };

  // Returns a function that will only be executed on and after the Nth call.
  _.after = function(times, func) {
    return function() {
      if (--times < 1) {
        return func.apply(this, arguments);
      }
    };
  };

  // Returns a function that will only be executed up to (but not including) the Nth call.
  _.before = function(times, func) {
    var memo;
    return function() {
      if (--times > 0) {
        memo = func.apply(this, arguments);
      }
      if (times <= 1) func = null;
      return memo;
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = _.partial(_.before, 2);

  // Object Functions
  // ----------------

  // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
  var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
  var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
                      'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];

  function collectNonEnumProps(obj, keys) {
    var nonEnumIdx = nonEnumerableProps.length;
    var constructor = obj.constructor;
    var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;

    // Constructor is a special case.
    var prop = 'constructor';
    if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);

    while (nonEnumIdx--) {
      prop = nonEnumerableProps[nonEnumIdx];
      if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
        keys.push(prop);
      }
    }
  }

  // Retrieve the names of an object's own properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = function(obj) {
    if (!_.isObject(obj)) return [];
    if (nativeKeys) return nativeKeys(obj);
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve all the property names of an object.
  _.allKeys = function(obj) {
    if (!_.isObject(obj)) return [];
    var keys = [];
    for (var key in obj) keys.push(key);
    // Ahem, IE < 9.
    if (hasEnumBug) collectNonEnumProps(obj, keys);
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var values = Array(length);
    for (var i = 0; i < length; i++) {
      values[i] = obj[keys[i]];
    }
    return values;
  };

  // Returns the results of applying the iteratee to each element of the object
  // In contrast to _.map it returns an object
  _.mapObject = function(obj, iteratee, context) {
    iteratee = cb(iteratee, context);
    var keys =  _.keys(obj),
          length = keys.length,
          results = {},
          currentKey;
      for (var index = 0; index < length; index++) {
        currentKey = keys[index];
        results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
      }
      return results;
  };

  // Convert an object into a list of `[key, value]` pairs.
  _.pairs = function(obj) {
    var keys = _.keys(obj);
    var length = keys.length;
    var pairs = Array(length);
    for (var i = 0; i < length; i++) {
      pairs[i] = [keys[i], obj[keys[i]]];
    }
    return pairs;
  };

  // Invert the keys and values of an object. The values must be serializable.
  _.invert = function(obj) {
    var result = {};
    var keys = _.keys(obj);
    for (var i = 0, length = keys.length; i < length; i++) {
      result[obj[keys[i]]] = keys[i];
    }
    return result;
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = createAssigner(_.allKeys);

  // Assigns a given object with all the own properties in the passed-in object(s)
  // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
  _.extendOwn = _.assign = createAssigner(_.keys);

  // Returns the first key on an object that passes a predicate test
  _.findKey = function(obj, predicate, context) {
    predicate = cb(predicate, context);
    var keys = _.keys(obj), key;
    for (var i = 0, length = keys.length; i < length; i++) {
      key = keys[i];
      if (predicate(obj[key], key, obj)) return key;
    }
  };

  // Return a copy of the object only containing the whitelisted properties.
  _.pick = function(object, oiteratee, context) {
    var result = {}, obj = object, iteratee, keys;
    if (obj == null) return result;
    if (_.isFunction(oiteratee)) {
      keys = _.allKeys(obj);
      iteratee = optimizeCb(oiteratee, context);
    } else {
      keys = flatten(arguments, false, false, 1);
      iteratee = function(value, key, obj) { return key in obj; };
      obj = Object(obj);
    }
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = keys[i];
      var value = obj[key];
      if (iteratee(value, key, obj)) result[key] = value;
    }
    return result;
  };

   // Return a copy of the object without the blacklisted properties.
  _.omit = function(obj, iteratee, context) {
    if (_.isFunction(iteratee)) {
      iteratee = _.negate(iteratee);
    } else {
      var keys = _.map(flatten(arguments, false, false, 1), String);
      iteratee = function(value, key) {
        return !_.contains(keys, key);
      };
    }
    return _.pick(obj, iteratee, context);
  };

  // Fill in a given object with default properties.
  _.defaults = createAssigner(_.allKeys, true);

  // Creates an object that inherits from the given prototype object.
  // If additional properties are provided then they will be added to the
  // created object.
  _.create = function(prototype, props) {
    var result = baseCreate(prototype);
    if (props) _.extendOwn(result, props);
    return result;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Returns whether an object has a given set of `key:value` pairs.
  _.isMatch = function(object, attrs) {
    var keys = _.keys(attrs), length = keys.length;
    if (object == null) return !length;
    var obj = Object(object);
    for (var i = 0; i < length; i++) {
      var key = keys[i];
      if (attrs[key] !== obj[key] || !(key in obj)) return false;
    }
    return true;
  };


  // Internal recursive comparison function for `isEqual`.
  var eq = function(a, b, aStack, bStack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) return a !== 0 || 1 / a === 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a instanceof _) a = a._wrapped;
    if (b instanceof _) b = b._wrapped;
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className !== toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, regular expressions, dates, and booleans are compared by value.
      case '[object RegExp]':
      // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return '' + a === '' + b;
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive.
        // Object(NaN) is equivalent to NaN
        if (+a !== +a) return +b !== +b;
        // An `egal` comparison is performed for other numeric values.
        return +a === 0 ? 1 / +a === 1 / b : +a === +b;
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a === +b;
    }

    var areArrays = className === '[object Array]';
    if (!areArrays) {
      if (typeof a != 'object' || typeof b != 'object') return false;

      // Objects with different constructors are not equivalent, but `Object`s or `Array`s
      // from different frames are.
      var aCtor = a.constructor, bCtor = b.constructor;
      if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
                               _.isFunction(bCtor) && bCtor instanceof bCtor)
                          && ('constructor' in a && 'constructor' in b)) {
        return false;
      }
    }
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.

    // Initializing stack of traversed objects.
    // It's done here since we only need them for objects and arrays comparison.
    aStack = aStack || [];
    bStack = bStack || [];
    var length = aStack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] === a) return bStack[length] === b;
    }

    // Add the first object to the stack of traversed objects.
    aStack.push(a);
    bStack.push(b);

    // Recursively compare objects and arrays.
    if (areArrays) {
      // Compare array lengths to determine if a deep comparison is necessary.
      length = a.length;
      if (length !== b.length) return false;
      // Deep compare the contents, ignoring non-numeric properties.
      while (length--) {
        if (!eq(a[length], b[length], aStack, bStack)) return false;
      }
    } else {
      // Deep compare objects.
      var keys = _.keys(a), key;
      length = keys.length;
      // Ensure that both objects contain the same number of properties before comparing deep equality.
      if (_.keys(b).length !== length) return false;
      while (length--) {
        // Deep compare each member
        key = keys[length];
        if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop();
    bStack.pop();
    return true;
  };

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (obj == null) return true;
    if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
    return _.keys(obj).length === 0;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType === 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) === '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    var type = typeof obj;
    return type === 'function' || type === 'object' && !!obj;
  };

  // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
  _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) {
    _['is' + name] = function(obj) {
      return toString.call(obj) === '[object ' + name + ']';
    };
  });

  // Define a fallback version of the method in browsers (ahem, IE < 9), where
  // there isn't any inspectable "Arguments" type.
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return _.has(obj, 'callee');
    };
  }

  // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
  // IE 11 (#1621), and in Safari 8 (#1929).
  if (typeof /./ != 'function' && typeof Int8Array != 'object') {
    _.isFunction = function(obj) {
      return typeof obj == 'function' || false;
    };
  }

  // Is a given object a finite number?
  _.isFinite = function(obj) {
    return isFinite(obj) && !isNaN(parseFloat(obj));
  };

  // Is the given value `NaN`? (NaN is the only number which does not equal itself).
  _.isNaN = function(obj) {
    return _.isNumber(obj) && obj !== +obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Shortcut function for checking if an object has a given property directly
  // on itself (in other words, not on a prototype).
  _.has = function(obj, key) {
    return obj != null && hasOwnProperty.call(obj, key);
  };

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

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iteratees.
  _.identity = function(value) {
    return value;
  };

  // Predicate-generating functions. Often useful outside of Underscore.
  _.constant = function(value) {
    return function() {
      return value;
    };
  };

  _.noop = function(){};

  _.property = property;

  // Generates a function for a given object that returns a given property.
  _.propertyOf = function(obj) {
    return obj == null ? function(){} : function(key) {
      return obj[key];
    };
  };

  // Returns a predicate for checking whether an object has a given set of
  // `key:value` pairs.
  _.matcher = _.matches = function(attrs) {
    attrs = _.extendOwn({}, attrs);
    return function(obj) {
      return _.isMatch(obj, attrs);
    };
  };

  // Run a function **n** times.
  _.times = function(n, iteratee, context) {
    var accum = Array(Math.max(0, n));
    iteratee = optimizeCb(iteratee, context, 1);
    for (var i = 0; i < n; i++) accum[i] = iteratee(i);
    return accum;
  };

  // Return a random integer between min and max (inclusive).
  _.random = function(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
  };

  // A (possibly faster) way to get the current timestamp as an integer.
  _.now = Date.now || function() {
    return new Date().getTime();
  };

   // List of HTML entities for escaping.
  var escapeMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#x27;',
    '`': '&#x60;'
  };
  var unescapeMap = _.invert(escapeMap);

  // Functions for escaping and unescaping strings to/from HTML interpolation.
  var createEscaper = function(map) {
    var escaper = function(match) {
      return map[match];
    };
    // Regexes for identifying a key that needs to be escaped
    var source = '(?:' + _.keys(map).join('|') + ')';
    var testRegexp = RegExp(source);
    var replaceRegexp = RegExp(source, 'g');
    return function(string) {
      string = string == null ? '' : '' + string;
      return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
    };
  };
  _.escape = createEscaper(escapeMap);
  _.unescape = createEscaper(unescapeMap);

  // If the value of the named `property` is a function then invoke it with the
  // `object` as context; otherwise, return it.
  _.result = function(object, property, fallback) {
    var value = object == null ? void 0 : object[property];
    if (value === void 0) {
      value = fallback;
    }
    return _.isFunction(value) ? value.call(object) : value;
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = ++idCounter + '';
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /(.)^/;

  // Certain characters need to be escaped so that they can be put into a
  // string literal.
  var escapes = {
    "'":      "'",
    '\\':     '\\',
    '\r':     'r',
    '\n':     'n',
    '\u2028': 'u2028',
    '\u2029': 'u2029'
  };

  var escaper = /\\|'|\r|\n|\u2028|\u2029/g;

  var escapeChar = function(match) {
    return '\\' + escapes[match];
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  // NB: `oldSettings` only exists for backwards compatibility.
  _.template = function(text, settings, oldSettings) {
    if (!settings && oldSettings) settings = oldSettings;
    settings = _.defaults({}, settings, _.templateSettings);

    // Combine delimiters into one regular expression via alternation.
    var matcher = RegExp([
      (settings.escape || noMatch).source,
      (settings.interpolate || noMatch).source,
      (settings.evaluate || noMatch).source
    ].join('|') + '|$', 'g');

    // Compile the template source, escaping string literals appropriately.
    var index = 0;
    var source = "__p+='";
    text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
      source += text.slice(index, offset).replace(escaper, escapeChar);
      index = offset + match.length;

      if (escape) {
        source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
      } else if (interpolate) {
        source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
      } else if (evaluate) {
        source += "';\n" + evaluate + "\n__p+='";
      }

      // Adobe VMs need the match returned to produce the correct offest.
      return match;
    });
    source += "';\n";

    // If a variable is not specified, place data values in local scope.
    if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';

    source = "var __t,__p='',__j=Array.prototype.join," +
      "print=function(){__p+=__j.call(arguments,'');};\n" +
      source + 'return __p;\n';

    try {
      var render = new Function(settings.variable || 'obj', '_', source);
    } catch (e) {
      e.source = source;
      throw e;
    }

    var template = function(data) {
      return render.call(this, data, _);
    };

    // Provide the compiled source as a convenience for precompilation.
    var argument = settings.variable || 'obj';
    template.source = 'function(' + argument + '){\n' + source + '}';

    return template;
  };

  // Add a "chain" function. Start chaining a wrapped Underscore object.
  _.chain = function(obj) {
    var instance = _(obj);
    instance._chain = true;
    return instance;
  };

  // OOP
  // ---------------
  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.

  // Helper function to continue chaining intermediate results.
  var result = function(instance, obj) {
    return instance._chain ? _(obj).chain() : obj;
  };

  // Add your own custom functions to the Underscore object.
  _.mixin = function(obj) {
    _.each(_.functions(obj), function(name) {
      var func = _[name] = obj[name];
      _.prototype[name] = function() {
        var args = [this._wrapped];
        push.apply(args, arguments);
        return result(this, func.apply(_, args));
      };
    });
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      var obj = this._wrapped;
      method.apply(obj, arguments);
      if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
      return result(this, obj);
    };
  });

  // Add all accessor Array functions to the wrapper.
  _.each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    _.prototype[name] = function() {
      return result(this, method.apply(this._wrapped, arguments));
    };
  });

  // Extracts the result from a wrapped and chained object.
  _.prototype.value = function() {
    return this._wrapped;
  };

  // Provide unwrapping proxy for some methods used in engine operations
  // such as arithmetic and JSON stringification.
  _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;

  _.prototype.toString = function() {
    return '' + this._wrapped;
  };

  // AMD registration happens at the end for compatibility with AMD loaders
  // that may not enforce next-turn semantics on modules. Even though general
  // practice for AMD registration is to be anonymous, underscore registers
  // as a named module because, like jQuery, it is a base library that is
  // popular enough to be bundled in a third party lib, but not be part of
  // an AMD load request. Those cases could generate an error when an
  // anonymous define() is called outside of a loader request.
  if (typeof define === 'function' && define.amd) {
    define('underscore', [], function() {
      return _;
    });
  }
}.call(this));

},{}],"bootstrap/dropdown":[function(require,module,exports){
var $ = require("jquery");

/* ========================================================================
 * Bootstrap: dropdown.js v3.1.1
 * http://getbootstrap.com/javascript/#dropdowns
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

'use strict';

// DROPDOWN CLASS DEFINITION
// =========================

var backdrop = '.bk-bs-dropdown-backdrop'
var toggle   = '[data-bk-bs-toggle=dropdown]'
var Dropdown = function (element) {
  $(element).on('click.bk-bs.dropdown', this.toggle)
}

Dropdown.prototype.toggle = function (e) {
  var $this = $(this)

  if ($this.is('.bk-bs-disabled, :disabled')) return

  var $parent  = getParent($this)
  var isActive = $parent.hasClass('bk-bs-open')

  clearMenus()

  if (!isActive) {
    if ('ontouchstart' in document.documentElement && !$parent.closest('.bk-bs-navbar-nav').length) {
      // if mobile we use a backdrop because click events don't delegate
      $('<div class="bk-bs-dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
    }

    var relatedTarget = { relatedTarget: this }
    $parent.trigger(e = $.Event('show.bk-bs.dropdown', relatedTarget))

    if (e.isDefaultPrevented()) return

    $parent
      .toggleClass('bk-bs-open')
      .trigger('shown.bk-bs.dropdown', relatedTarget)

    $this.focus()
  }

  return false
}

Dropdown.prototype.keydown = function (e) {
  if (!/(38|40|27)/.test(e.keyCode)) return

  var $this = $(this)

  e.preventDefault()
  e.stopPropagation()

  if ($this.is('.bk-bs-disabled, :disabled')) return

  var $parent  = getParent($this)
  var isActive = $parent.hasClass('bk-bs-open')

  if (!isActive || (isActive && e.keyCode == 27)) {
    if (e.which == 27) $parent.find(toggle).focus()
    return $this.click()
  }

  var desc = ' li:not(.bk-bs-divider):visible a'
  var $items = $parent.find('[role=menu]' + desc + ', [role=listbox]' + desc)

  if (!$items.length) return

  var index = $items.index($items.filter(':focus'))

  if (e.keyCode == 38 && index > 0)                 index--                        // up
  if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
  if (!~index)                                      index = 0

  $items.eq(index).focus()
}

function clearMenus(e) {
  $(backdrop).remove()
  $(toggle).each(function () {
    var $parent = getParent($(this))
    var relatedTarget = { relatedTarget: this }
    if (!$parent.hasClass('bk-bs-open')) return
    $parent.trigger(e = $.Event('hide.bk-bs.dropdown', relatedTarget))
    if (e.isDefaultPrevented()) return
    $parent.removeClass('bk-bs-open').trigger('hidden.bk-bs.dropdown', relatedTarget)
  })
}

function getParent($this) {
  var selector = $this.attr('data-bk-bs-target')

  if (!selector) {
    selector = $this.attr('href')
    selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
  }

  var $parent = selector && $(selector)

  return $parent && $parent.length ? $parent : $this.parent()
}


// DROPDOWN PLUGIN DEFINITION
// ==========================

var old = $.fn.dropdown

$.fn.dropdown = function (option) {
  return this.each(function () {
    var $this = $(this)
    var data  = $this.data('bk-bs.dropdown')

    if (!data) $this.data('bk-bs.dropdown', (data = new Dropdown(this)))
    if (typeof option == 'string') data[option].call($this)
  })
}

$.fn.dropdown.Constructor = Dropdown


// DROPDOWN NO CONFLICT
// ====================

$.fn.dropdown.noConflict = function () {
  $.fn.dropdown = old
  return this
}


// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================

$(document)
  .on('click.bk-bs.dropdown.data-api', clearMenus)
  .on('click.bk-bs.dropdown.data-api', '.bk-bs-dropdown form', function (e) { e.stopPropagation() })
  .on('click.bk-bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
  .on('keydown.bk-bs.dropdown.data-api', toggle + ', [role=menu], [role=listbox]', Dropdown.prototype.keydown)

},{"jquery":"jquery"}],"gear_utils":[function(require,module,exports){
/*==========================================================================*
  Filename: gearUtils-04.js
  By: Dr A.R.Collins

  JavaScript involute gear drawing utilities.
  Requires:
  'involuteBezCoeffs' can stand alone,
  'createGearTooth' and 'createIntGearTooth' generate draw commands for use
  in Cango graphics library but may be simply converted for use in SVG.

  Kindly give credit to Dr A.R.Collins <http://www.arc.id.au/>
  Report bugs to tony at arc.id.au

  Date   |Description                                                   |By
  --------------------------------------------------------------------------
  20Feb13 First public release                                           ARC
  21Feb13 Clarified variable names of start and end parameters           ARC
  06Mar13 Fixed Rf and filletAngle calculations                          ARC
  25Jun13 Code tidy for JSLint, use strict                               ARC
 *==========================================================================*/

  // exposed globals
  var involuteBezCoeffs, createGearTooth, createIntGearTooth;

(function()
{
  "use strict";
/* ----------------------------------------------------------
 * involuteBezCoeffs
 *
 * JavaScript calculation of Bezier coefficients for
 * Higuchi et al. approximation to an involute.
 * ref: YNU Digital Eng Lab Memorandum 05-1
 *
 * Parameters:
 * module - sets the size of teeth (see gear design texts)
 * numTeeth - number of teeth on the gear
 * pressure angle - angle in degrees, usually 14.5 or 20
 * order - the order of the Bezier curve to be fitted [3, 4, 5, ..]
 * fstart - fraction of distance along tooth profile to start
 * fstop - fraction of distance along profile to stop
 *-----------------------------------------------------------*/
involuteBezCoeffs = function(module, numTeeth, pressureAngle, order, fstart, fstop)
{
  var PI = Math.PI,
      Rpitch = module*numTeeth/2,       // pitch circle radius
      phi = pressureAngle || 20,        // pressure angle
      Rb = Rpitch*Math.cos(phi*PI/180), // base circle radius
      Ra = Rpitch+module,               // addendum radius (outer radius)
      p = order || 3,                   // order of Bezier approximation
      ta = Math.sqrt(Ra*Ra-Rb*Rb)/Rb,   // involute angle at addendum
      stop = fstop || 1,
      start = 0.01,
      te, ts,
      bzCoeffs = [],
      i, bcoeff;

  function chebyExpnCoeffs(j, func)
  {
    var N = 50,      // a suitably large number  N>>p
        c = 0,
        k;

    for (k=1; k<=N; k++)
    {
      c += func(Math.cos(PI*(k-0.5)/N)) * Math.cos(PI*j*(k-0.5)/N);
    }
    return 2*c/N;
  }

  function chebyPolyCoeffs(p, func)
  {
    var coeffs = [],
        fnCoeff = [],
        T = [[], []],
        i, j, k, pwr;

    // populate 1st 2 rows of T
    for (i=0; i<p+1; i++)
    {
      T[0][i] = 0;
      T[1][i] = 0;
    }
    T[0][0] = 1;
    T[1][1] = 1;
    /* now generate the Chebyshev polynomial coefficient using
       formula T(k+1) = 2xT(k) - T(k-1) which yields
    T = [ [ 1,  0,  0,  0,  0,  0],    // T0(x) =  +1
          [ 0,  1,  0,  0,  0,  0],    // T1(x) =   0  +x
          [-1,  0,  2,  0,  0,  0],    // T2(x) =  -1  0  +2xx
          [ 0, -3,  0,  4,  0,  0],    // T3(x) =   0 -3x    0   +4xxx
          [ 1,  0, -8,  0,  8,  0],    // T4(x) =  +1  0  -8xx       0  +8xxxx
          [ 0,  5,  0,-20,  0, 16],    // T5(x) =   0  5x    0  -20xxx       0  +16xxxxx
          ...                     ];
    */
    for (k=1; k<p+1; k++)
    {
      T[k+1] = [0];
      for (j=0; j<T[k].length-1; j++)
      {
        T[k+1][j+1] = 2*T[k][j];
      }
      for (j=0; j<T[k-1].length; j++)
      {
        T[k+1][j] -= T[k-1][j];
      }
    }
    // convert the chebyshev function series into a simple polynomial
    // and collect like terms, out T polynomial coefficients
    for (k=0; k<=p; k++)
    {
      fnCoeff[k] = chebyExpnCoeffs(k, func);
      coeffs[k] = 0;
    }
    for (k=0; k<=p; k++)
    {
      for (pwr=0; pwr<=p; pwr++)    // loop thru powers of x
      {
        coeffs[pwr] += fnCoeff[k]*T[k][pwr];
      }
    }
    coeffs[0] -= chebyExpnCoeffs(0, func)/2;  // fix the 0th coeff

    return coeffs;
  }

  // Equation of involute using the Bezier parameter t as variable
  function involuteXbez(t)
  {
    // map t (0 <= t <= 1) onto x (where -1 <= x <= 1)
    var x = t*2-1;
    //map theta (where ts <= theta <= te) from x (-1 <=x <= 1)
    var theta = x*(te-ts)/2 + (ts + te)/2;
    return Rb*(Math.cos(theta)+theta*Math.sin(theta));
  }

  function involuteYbez(t)
  {
    // map t (0 <= t <= 1) onto x (where -1 <= x <= 1)
    var x = t*2-1;
    //map theta (where ts <= theta <= te) from x (-1 <=x <= 1)
    var theta = x*(te-ts)/2 + (ts + te)/2;
    return Rb*(Math.sin(theta)-theta*Math.cos(theta));
  }

  function binom(n, k)
  {
    var coeff = 1;
    var i;
    for (i = n-k+1; i <= n; i++)
    {
      coeff *= i;
    }
    for (i = 1; i <= k; i++)
    {
      coeff /= i;
    }

    return coeff;
  }

  function bezCoeff(i, func)
  {
    // generate the polynomial coeffs in one go
    var polyCoeffs = chebyPolyCoeffs(p, func),
        bc, j;

    for (bc=0, j=0; j<=i; j++)
    {
      bc += binom(i,j)*polyCoeffs[j]/binom(p,j);
    }
    return bc;
  }

  if ((fstart !== undefined)&&(fstart<stop))
  {
    start = fstart;
  }
  te = Math.sqrt(stop)*ta;          // involute angle, theta, at end of approx
  ts = Math.sqrt(start)*ta;         // involute angle, theta, at start of approx
  // calc Bezier coeffs
  for (i=0; i<=p; i++)
  {
    bcoeff = {};
    bcoeff.x = bezCoeff(i, involuteXbez);
    bcoeff.y = bezCoeff(i, involuteYbez);
    bzCoeffs.push(bcoeff);
  }

  return bzCoeffs;
};

/*----------------------------------------------------------
  createGearTooth
  Create an array of drawing commands and their coordinates
  to draw a single spur gear tooth based on a circle
  involute using the metric gear standards.

  Requires Cango graphics library Rev 2.08 or later
 ----------------------------------------------------------*/
createGearTooth = function(module, teeth, pressureAngle)
{
  function genInvolutePolar(Rb, R)  // Rb = base circle radius
  {
    // returns the involute angle as function of radius R.
    return (Math.sqrt(R*R - Rb*Rb)/Rb) - Math.acos(Rb/R);
  }

  function rotate(pt, rads)  // rotate pt by rads radians about origin
  {
    var sinA = Math.sin(rads);
    var cosA = Math.cos(rads);
    return {x: pt.x*cosA - pt.y*sinA,
            y: pt.x*sinA + pt.y*cosA};
  }

  function toCartesian(radius, angle)   // convert polar coords to cartesian
  {
    return {x: radius*Math.cos(angle),
            y: radius*Math.sin(angle)};
  }
  // ****** external gear specifications
  var m = module,                                     // Module = mm of pitch diameter per tooth
      Z = teeth,                                      // Number of teeth
      phi = pressureAngle || 20,                      // pressure angle (degrees)
      addendum = m,                                   // distance from pitch circle to tip circle
      dedendum = 1.25*m,                              // pitch circle to root, sets clearance
      clearance = dedendum - addendum,
      // Calculate radii
      Rpitch = Z*m/2,                                 // pitch circle radius
      Rb = Rpitch*Math.cos(phi*Math.PI/180),          // base circle radius
      Ra = Rpitch + addendum,                         // tip (addendum) circle radius
      Rroot = Rpitch - dedendum,                      // root circle radius
      fRad = 1.5*clearance,                           // fillet radius, max 1.5*clearance
      Rf,                                             // radius at top of fillet
      // ****** calculate angles (all in radians)
      pitchAngle = 2*Math.PI/Z,                       // angle subtended by whole tooth (rads)
      baseToPitchAngle = genInvolutePolar(Rb, Rpitch),
      pitchToFilletAngle = baseToPitchAngle,          // profile starts at base circle
      filletAngle = Math.atan(fRad/(fRad+Rroot)),     // radians
      fe, fs, fm,
      dedBz, addBz, inv, invR,
      fillet, filletR, filletNext,
      rootR, rootNext,
      pt, i, data;

  Rf = Math.sqrt((Rroot+fRad)*(Rroot+fRad)-(fRad*fRad)); // radius at top of fillet
  if (Rb < Rf)
  {
    Rf = Rroot+clearance;
  }
  if (Rf > Rb)                   // start profile at top of fillet (if its greater)
  {
    pitchToFilletAngle -= genInvolutePolar(Rb, Rf);
  }
  // ****** generate Higuchi involute approximation
  fe = 1;                    // fraction of profile length at end of approx
  fs = 0.01;                 // fraction of length offset from base to avoid singularity
  if (Rf > Rb)
  {
    fs = (Rf*Rf-Rb*Rb)/(Ra*Ra-Rb*Rb);  // offset start to top of fillet
  }
  // approximate in 2 sections, split 25% along the involute
  fm = fs+(fe-fs)/4;         // fraction of length at junction (25% along profile)
  dedBz = involuteBezCoeffs(m, Z, phi, 3, fs, fm);
  addBz = involuteBezCoeffs(m, Z, phi, 3, fm, fe);
  // join the 2 sets of coeffs (skip duplicate mid point)
  inv = dedBz.concat(addBz.slice(1));
  //create the back profile of tooth (mirror image)
  invR = [];                // involute profile along back of tooth
  for (i=0; i<inv.length; i++)
  {
    // rotate all points to put pitch point at y = 0
    pt = rotate(inv[i], -baseToPitchAngle-pitchAngle/4);
    inv[i] = pt;
    // generate the back of tooth profile nodes, mirror coords in X axis
    invR[i] = {x:pt.x, y:-pt.y};
  }
  // ****** calculate section junction points R=back of tooth, Next=front of next tooth)
  fillet = toCartesian(Rf, -pitchAngle/4-pitchToFilletAngle); // top of fillet
  filletR = {x:fillet.x, y:-fillet.y};   // flip to make same point on back of tooth
  rootR = toCartesian(Rroot, pitchAngle/4+pitchToFilletAngle+filletAngle);
  rootNext = toCartesian(Rroot, 3*pitchAngle/4-pitchToFilletAngle-filletAngle);
  filletNext = rotate(fillet, pitchAngle);  // top of fillet, front of next tooth
  // ****** create the drawing command data array for the tooth
  data = [];
  data.push("M", fillet.x, fillet.y);           // start at top of fillet
  if (Rf < Rb)
  {
    data.push("L", inv[0].x, inv[0].y);         // line from fillet up to base circle
  }
  data.push("C", inv[1].x, inv[1].y, inv[2].x, inv[2].y, inv[3].x, inv[3].y,
                 inv[4].x, inv[4].y, inv[5].x, inv[5].y, inv[6].x, inv[6].y);
  data.push("A", Ra, Ra, 0, 0, 0, invR[6].x, invR[6].y); // arc across addendum circle
  data.push("C", invR[5].x, invR[5].y, invR[4].x, invR[4].y, invR[3].x, invR[3].y,
                 invR[2].x, invR[2].y, invR[1].x, invR[1].y, invR[0].x, invR[0].y);
  if (Rf < Rb)
  {
    data.push("L", filletR.x, filletR.y);       // line down to top of fillet
  }
  if (rootNext.y > rootR.y)    // is there a section of root circle between fillets?
  {
    data.push("A", fRad, fRad, 0, 0, 1, rootR.x, rootR.y);// back fillet
    data.push("A", Rroot, Rroot, 0, 0, 0, rootNext.x, rootNext.y); // root circle arc
  }
  data.push("A", fRad, fRad, 0, 0, 1, filletNext.x, filletNext.y);

  return data;  // return an array of Cango (SVG) format draw commands
};

/*----------------------------------------------------------
  createIntGearTooth
  Create an array of drawing commands and their coordinates
  to draw a single internal (ring)gear tooth based on a
  circle involute using the metric gear standards.

  Requires Cango graphics library Rev 2.08 or later
 ----------------------------------------------------------*/
createIntGearTooth = function(module, teeth, pressureAngle)
{
  // ****** gear specifications
  var m = module,                               // Module = mm of pitch diameter per tooth
      Z = teeth,                                // Number of teeth
      phi = pressureAngle || 20,                // pressure angle (degrees)
      addendum = 0.6*m,                         // pitch circle to tip circle (ref G.M.Maitra)
      dedendum = 1.25*m,                        // pitch circle to root radius, sets clearance
      // Calculate radii
      Rpitch = Z*m/2,                           // pitch radius
      Rb = Rpitch*Math.cos(phi*Math.PI/180),    // base radius
      Ra = Rpitch - addendum,                   // addendum radius
      Rroot = Rpitch + dedendum,                // root radius
      clearance = 0.25*m,                       // gear dedendum - pinion addendum
      Rf = Rroot - clearance,                   // radius of top of fillet (end of profile)
      fRad = 1.5*clearance,                     // fillet radius, 1 .. 1.5*clearance
      pitchAngle,                               // angle between teeth (rads)
      baseToPitchAngle,
      tipToPitchAngle,
      pitchToFilletAngle,
      filletAngle,
      fe, fs, fm,
      addBz, dedBz,
      inv, invR,
      pt, i, data,
      fillet, filletNext,
      tip, tipR,
      rootR, rootNext;

  function genInvolutePolar(Rb, R)  // Rb = base circle radius
  {
    // returns the involute angle as function of radius R.
    return (Math.sqrt(R*R - Rb*Rb)/Rb) - Math.acos(Rb/R);
  }

  function rotate(pt, rads)  // rotate pt by rads radians about origin
  {
    var sinA = Math.sin(rads);
    var cosA = Math.cos(rads);
    return {x: pt.x*cosA - pt.y*sinA,
            y: pt.x*sinA + pt.y*cosA};
  }

  function toCartesian(radius, angle)   // convert polar coords to cartesian
  {
    return {x: radius*Math.cos(angle),
            y: radius*Math.sin(angle)};
  }

  // ****** calculate subtended angles
  pitchAngle = 2*Math.PI/Z;                       // angle between teeth (rads)
  baseToPitchAngle = genInvolutePolar(Rb, Rpitch);
  tipToPitchAngle = baseToPitchAngle;             // profile starts from base circle
  if (Ra > Rb)
  {
    tipToPitchAngle -= genInvolutePolar(Rb, Ra);  // start profile from addendum
  }
  pitchToFilletAngle = genInvolutePolar(Rb, Rf) - baseToPitchAngle;
  filletAngle = 1.414*clearance/Rf;               // to make fillet tangential to root
  // ****** generate Higuchi involute approximation
  fe = 1;                   // fraction of involute length at end of approx (fillet circle)
  fs = 0.01;                 // fraction of length offset from base to avoid singularity
  if (Ra > Rb)
  {
    fs = (Ra*Ra-Rb*Rb)/(Rf*Rf-Rb*Rb);    // start profile from addendum (tip circle)
  }
  // approximate in 2 sections, split 25% along the profile
  fm = fs+(fe-fs)/4;        //
  addBz = involuteBezCoeffs(m, Z, phi, 3, fs, fm);
  dedBz = involuteBezCoeffs(m, Z, phi, 3, fm, fe);
  // join the 2 sets of coeffs (skip duplicate mid point)
  invR = addBz.concat(dedBz.slice(1));
  //create the front profile of tooth (mirror image)
  inv = [];         // back involute profile
  for (i=0; i<invR.length; i++)
  {
    // rotate involute to put center of tooth at y = 0
    pt = rotate(invR[i], pitchAngle/4-baseToPitchAngle);
    invR[i] = pt;
    // generate the back of tooth profile, flip Y coords
    inv[i] = {x:pt.x, y:-pt.y};
  }
  // ****** calculate coords of section junctions
  fillet = {x:inv[6].x, y:inv[6].y};    // top of fillet, front of tooth
  tip = toCartesian(Ra, -pitchAngle/4+tipToPitchAngle);  // tip, front of tooth
  tipR = {x:tip.x, y:-tip.y};  // addendum, back of tooth
  rootR = toCartesian(Rroot, pitchAngle/4+pitchToFilletAngle+filletAngle);
  rootNext = toCartesian(Rroot, 3*pitchAngle/4-pitchToFilletAngle-filletAngle);
  filletNext = rotate(fillet, pitchAngle);  // top of fillet, front of next tooth
  // ****** create the drawing command data array for the tooth
  data = [];
  data.push("M", inv[6].x, inv[6].y);  // start at top of front profile
  data.push("C", inv[5].x, inv[5].y, inv[4].x, inv[4].y, inv[3].x, inv[3].y,
                 inv[2].x, inv[2].y, inv[1].x, inv[1].y, inv[0].x, inv[0].y);
  if (Ra < Rb)
  {
    data.push("L", tip.x, tip.y);  // line from end of involute to addendum (tip)
  }
  data.push("A", Ra, Ra, 0, 0, 0, tipR.x, tipR.y); // arc across tip circle
  if (Ra < Rb)
  {
    data.push("L", invR[0].x, invR[0].y);  // line from addendum to start of involute
  }
  data.push("C", invR[1].x, invR[1].y, invR[2].x, invR[2].y, invR[3].x, invR[3].y,
                 invR[4].x, invR[4].y, invR[5].x, invR[5].y, invR[6].x, invR[6].y);
  if (rootR.y < rootNext.y)    // there is a section of root circle between fillets
  {
    data.push("A", fRad, fRad, 0, 0, 0, rootR.x, rootR.y); // fillet on back of tooth
    data.push("A", Rroot, Rroot, 0, 0, 0, rootNext.x, rootNext.y); // root circle arc
  }
  data.push("A", fRad, fRad, 0, 0, 0, filletNext.x, filletNext.y); // fillet on next

  return data;  // return an array of Cango (SVG) format draw commands
};

}());

module.exports = {
  create_gear_tooth: createGearTooth,
  create_internal_gear_tooth: createIntGearTooth
};

},{}],"gloo2":[function(require,module,exports){
(function (global){
/* Do not edit, autogenerated by flexx.pyscript */

(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else if (typeof exports !== 'undefined') {
        // Node or CommonJS
        module.exports = factory();
        if (typeof window === 'undefined') {
            root.gloo2 = module.exports;  // also create global module in Node
        }
    } else {
        // Browser globals (root is window)
        root.gloo2 = factory();
    }
}(this, function () {
    var _pyfunc_add = function (a, b) { // nargs: 2
        if (Array.isArray(a) && Array.isArray(b)) {
            return a.concat(b);
        } return a + b;
    };
    var _pyfunc_all = function (x) { // nargs: 1
        for (var i=0; i<x.length; i++) {
            if (!_pyfunc_truthy(x[i])){return false;}
        } return true;
    };
    var _pyfunc_contains = function contains (a, b) { // nargs: 2
        if (b == null) {
        } else if (Array.isArray(b)) {
            for (var i=0; i<b.length; i++) {if (_pyfunc_equals(a, b[i]))
                                               return true;}
            return false;
        } else if (b.constructor === Object) {
            for (var k in b) {if (a == k) return true;}
            return false;
        } else if (b.constructor == String) {
            return b.indexOf(a) >= 0;
        } var e = Error('Not a container: ' + b); e.name='TypeError'; throw e;
    };
    var _pyfunc_equals = function equals (a, b) { // nargs: 2
        if (a == null || b == null) {
        } else if (Array.isArray(a) && Array.isArray(b)) {
            var i = 0, iseq = a.length == b.length;
            while (iseq && i < a.length) {iseq = equals(a[i], b[i]); i+=1;}
            return iseq;
        } else if (a.constructor === Object && b.constructor === Object) {
            var akeys = Object.keys(a), bkeys = Object.keys(b);
            akeys.sort(); bkeys.sort();
            var i=0, k, iseq = equals(akeys, bkeys);
            while (iseq && i < akeys.length) {k=akeys[i]; iseq = equals(a[k], b[k]); i+=1;}
            return iseq;
        } return a == b;
    };
    var _pyfunc_instantiate = function (ob, args) { // nargs: 2
        if ((typeof ob === "undefined") ||
                (typeof window !== "undefined" && window === ob) ||
                (typeof global !== "undefined" && global === ob))
                {throw "Class constructor is called as a function.";}
        for (var name in ob) {
            if (Object[name] === undefined &&
                typeof ob[name] === 'function' && !ob[name].nobind) {
                ob[name] = ob[name].bind(ob);
            }
        }
        if (ob.__init__) {
            ob.__init__.apply(ob, args);
        }
    };
    var _pyfunc_mult = function (a, b) { // nargs: 2
        if ((typeof a === 'number') + (typeof b === 'number') === 1) {
            if (a.constructor === String) return _pymeth_repeat.call(a, b);
            if (b.constructor === String) return _pymeth_repeat.call(b, a);
            if (Array.isArray(b)) {var t=a; a=b; b=t;}
            if (Array.isArray(a)) {
                var res = []; for (var i=0; i<b; i++) res = res.concat(a);
                return res;
            }
        } return a * b;
    };
    var _pyfunc_range = function (start, end, step) {
    var i, res = [];
        var val = start;
        var n = (end - start) / step;
        for (i=0; i<n; i++) {
            res.push(val);
            val += step;
        }
        return res;
    };
    var _pyfunc_truthy = function (v) {
        if (v === null || typeof v !== "object") {return v;}
        else if (v.length !== undefined) {return v.length ? v : false;}
        else if (v.byteLength !== undefined) {return v.byteLength ? v : false;}
        else if (v.constructor !== Object) {return true;}
        else {return Object.getOwnPropertyNames(v).length ? v : false;}
    };
    var _pymeth_append = function (x) { // nargs: 1
        if (!Array.isArray(this)) return this.append.apply(this, arguments);
        this.push(x);
    };
    var _pymeth_get = function (key, d) { // nargs: 1 2
        if (this.constructor !== Object) return this.get.apply(this, arguments);
        if (this[key] !== undefined) {return this[key];}
        else if (d !== undefined) {return d;}
        else {return null;}
    };
    var _pymeth_keys = function () { // nargs: 0
        if (typeof this['keys'] === 'function') return this.keys.apply(this, arguments);
        return Object.keys(this);
    };
    var _pymeth_lstrip = function (chars) { // nargs: 0 1
        if (this.constructor !== String) return this.lstrip.apply(this, arguments);
        chars = (chars === undefined) ? ' \t\r\n' : chars;
        for (var i=0; i<this.length; i++) {
            if (chars.indexOf(this[i]) < 0) return this.slice(i);
        } return '';
    };
    var _pymeth_remove = function (x) { // nargs: 1
        if (!Array.isArray(this)) return this.remove.apply(this, arguments);
        for (var i=0; i<this.length; i++) {
            if (_pyfunc_equals(this[i], x)) {this.splice(i, 1); return;}
        }
        var e = Error(x); e.name='ValueError'; throw e;
    };
    var _pymeth_repeat = function(count) { // nargs: 0
        if (this.repeat) return this.repeat(count);
        if (count < 1) return '';
        var result = '', pattern = this.valueOf();
        while (count > 1) {
            if (count & 1) result += pattern;
            count >>= 1, pattern += pattern;
        }
        return result + pattern;
    };
    var _pymeth_startswith = function (x) { // nargs: 1
        if (this.constructor !== String) return this.startswith.apply(this, arguments);
        return this.indexOf(x) == 0;
    };
    var Buffer, GlooObject, IndexBuffer, Program, Texture2D, Texture3DLike, VertexBuffer, __version__, check_error, console;
    // PyScript module for gloo2.js - lightweight object oriented GL.

    { /* if this_is_js() */
    console = window.console;
    }
    __version__ = "0.3";
    check_error = function (gl, when) {
        var e, err, err_3, errors, msg, stub1_seq, stub2_itr;
        when = (when === undefined) ? "periodic check": when;
        // Check this from time to time to detect GL errors.
        // 
        //     Parameters
        //     ----------
        //     when : str
        //         Shown in the exception to help the developer determine when
        //         this check was done.
        errors = [];
        while (true) {
            err = gl.getError();
            if ((_pyfunc_equals(err, gl.NO_ERROR) || (_pyfunc_truthy(errors) && _pyfunc_equals(err, errors[errors.length -1])))) {
                break;
            }
            _pymeth_append.call(errors, err);
        }
        if (errors.length) {
            msg = "";
            stub1_seq = errors;
            if ((typeof stub1_seq === "object") && (!Array.isArray(stub1_seq))) {
                stub1_seq = Object.keys(stub1_seq);
            }
            for (stub2_itr = 0; stub2_itr < stub1_seq.length; stub2_itr += 1) {
                e = stub1_seq[stub2_itr];
                msg=_pyfunc_add(msg, e)
            }
            err_3 = new Error('RuntimeError:' + ("OpenGL got errors (" + when + "): " + msg + "")); err_3.name = "RuntimeError"; throw err_3;
        }
        return null;
    };

    GlooObject = function () {
        // Abstract base class for all Gloo classes.
        _pyfunc_instantiate(this, arguments);
    }
    GlooObject.prototype._base_class = Object;
    GlooObject.prototype._class_name = "GlooObject";
    
    GlooObject.prototype.__init__ = function (gl) {
        // Init by passing the webgl context object.
        this._gl = gl;
        this.handle = null;
        this._create();
        if (!(this.handle !== null)) {throw "AssertionError: " + "this.handle !== null";}
        return null;
    };

    GlooObject.prototype._create = function () {
        var err_2;
        err_2 = new Error('NotImplementedError:' + ""); err_2.name = "NotImplementedError"; throw err_2;
        return null;
    };


    Program = function () {
        // The program is the central component to connect gloo objects and shaders.
        _pyfunc_instantiate(this, arguments);
    }
    Program.prototype = Object.create(GlooObject.prototype);
    Program.prototype._base_class = GlooObject.prototype;
    Program.prototype._class_name = "Program";
    
    Program.prototype.UTYPEMAP = {"float": "uniform1fv", "vec2": "uniform2fv", "vec3": "uniform3fv", "vec4": "uniform4fv", "int": "uniform1iv", "ivec2": "uniform2iv", "ivec3": "uniform3iv", "ivec4": "uniform4iv", "bool": "uniform1iv", "bvec2": "uniform2iv", "bvec3": "uniform3iv", "bvec4": "uniform4iv", "mat2": "uniformMatrix2fv", "mat3": "uniformMatrix3fv", "mat4": "uniformMatrix4fv", "sampler1D": "uniform1i", "sampler2D": "uniform1i", "sampler3D": "uniform1i"};
    Program.prototype.ATYPEMAP = {"float": "vertexAttrib1f", "vec2": "vertexAttrib2f", "vec3": "vertexAttrib3f", "vec4": "vertexAttrib4f"};
    Program.prototype.ATYPEINFO = {"float": [1, 5126], "vec2": [2, 5126], "vec3": [3, 5126], "vec4": [4, 5126]};
    Program.prototype._create = function () {
        this.handle = this._gl.createProgram();
        this.locations = {};
        this._unset_variables = [];
        this._validated = false;
        this._samplers = {};
        this._attributes = {};
        this._known_invalid = [];
        return null;
    };

    Program.prototype.delete = function () {
        // Delete the program.
        this._gl.deleteProgram(this.handle);
        return null;
    };

    Program.prototype.activate = function () {
        // Activate the program.
        this._gl.useProgram(this.handle);
        return null;
    };

    Program.prototype.deactivate = function () {
        // Disable the program.
        this._gl.useProgram(0);
        return null;
    };

    Program.prototype.set_shaders = function (vert, frag) {
        var code, err_3, err_4, errors, frag_handle, gl, handle, i, status, stub3_, tmp, type_, vert_handle;
        // Set GLSL code for the vertex and fragment shader.
        // 
        // This function takes care of setting the shading code and
        // compiling+linking it into a working program object that is ready
        // to use.
        // 
        // Parameters
        // ----------
        // vert : str
        //     GLSL code for the vertex shader.
        // frag : str
        //     GLSL code for the fragment shader.
        gl = this._gl;
        this._linked = false;
        vert_handle = gl.createShader(gl.VERTEX_SHADER);
        frag_handle = gl.createShader(gl.FRAGMENT_SHADER);
        tmp = [[vert, vert_handle, "vertex"], [frag, frag_handle, "fragment"]];
        for (i = 0; i < 2; i += 1) {
            stub3_ = tmp[i];
            code = stub3_[0];handle = stub3_[1];type_ = stub3_[2];
            gl.shaderSource(handle, code);
            gl.compileShader(handle);
            status = gl.getShaderParameter(handle, gl.COMPILE_STATUS);
            if ((!_pyfunc_truthy(status))) {
                errors = gl.getShaderInfoLog(handle);
                err_4 = new Error('RuntimeError:' + (_pyfunc_add((("errors in " + type_) + " shader:\n"), errors))); err_4.name = "RuntimeError"; throw err_4;
            }
        }
        gl.attachShader(this.handle, vert_handle);
        gl.attachShader(this.handle, frag_handle);
        gl.linkProgram(this.handle);
        if ((!_pyfunc_truthy(gl.getProgramParameter(this.handle, gl.LINK_STATUS)))) {
            err_3 = new Error('RuntimeError:' + ("Program link error:\n" + gl.getProgramInfoLog(this.handle))); err_3.name = "RuntimeError"; throw err_3;
        }
        this._unset_variables = this._get_active_attributes_and_uniforms();
        gl.detachShader(this.handle, vert_handle);
        gl.detachShader(this.handle, frag_handle);
        gl.deleteShader(vert_handle);
        gl.deleteShader(frag_handle);
        this._known_invalid = [];
        this._linked = true;
        return null;
    };

    Program.prototype._get_active_attributes_and_uniforms = function () {
        var attributes, ca, container, count, cu, getActive, getLocation, gl, i, info, j, m, name, regex, stub4_, stub5_seq, stub6_itr, uniforms, x;
        // Retrieve active attributes and uniforms to be able to check that
        // all uniforms/attributes are set by the user.
        gl = this._gl;
        this.locations = {};
        regex = new window.RegExp("(\\w+)\\s*(\\[(\\d+)\\])\\s*");
        cu = gl.getProgramParameter(this.handle, gl.ACTIVE_UNIFORMS);
        ca = gl.getProgramParameter(this.handle, gl.ACTIVE_ATTRIBUTES);
        attributes = [];
        uniforms = [];
        stub5_seq = [[attributes, ca, gl.getActiveAttrib, gl.getAttribLocation], [uniforms, cu, gl.getActiveUniform, gl.getUniformLocation]];
        if ((typeof stub5_seq === "object") && (!Array.isArray(stub5_seq))) {
            stub5_seq = Object.keys(stub5_seq);
        }
        for (stub6_itr = 0; stub6_itr < stub5_seq.length; stub6_itr += 1) {
            x = stub5_seq[stub6_itr];
            stub4_ = x;
            container = stub4_[0];count = stub4_[1];getActive = stub4_[2];getLocation = stub4_[3];
            for (i = 0; i < count; i += 1) {
                info = getActive.call(gl, this.handle, i);
                name = info.name;
                m = name.match(regex);
                if (_pyfunc_truthy(m)) {
                    name = m[1];
                    for (j = 0; j < info.size; j += 1) {
                        _pymeth_append.call(container, (["" + name + "[" + j + "]", info.type]));
                    }
                } else {
                    _pymeth_append.call(container, [name, info.type]);
                }
                this.locations[name] = getLocation.call(gl, this.handle, name);
            }
        }
        return _pyfunc_add(((function list_comprehenson () {var res = [];var v, iter0, i0;iter0 = attributes;if ((typeof iter0 === "object") && (!Array.isArray(iter0))) {iter0 = Object.keys(iter0);}for (i0=0; i0<iter0.length; i0++) {v = iter0[i0];{res.push(v[0]);}}return res;}).apply(this)), ((function list_comprehenson () {var res = [];var v, iter0, i0;iter0 = uniforms;if ((typeof iter0 === "object") && (!Array.isArray(iter0))) {iter0 = Object.keys(iter0);}for (i0=0; i0<iter0.length; i0++) {v = iter0[i0];{res.push(v[0]);}}return res;}).apply(this)));
    };

    Program.prototype.set_texture = function (name, value) {
        var err_3, handle, unit;
        // Set a texture sampler.
        // 
        // A texture is a 2 dimensional grid of colors/intensities that
        // can be applied to a face (or used for other means by providing
        // a regular grid of data).
        // 
        // Parameters
        // ----------
        // name : str
        //     The name by which the texture is known in the GLSL code.
        // value : Texture2D
        //     The gloo Texture2D object to bind.
        if ((!_pyfunc_truthy(this._linked))) {
            err_3 = new Error('RuntimeError:' + "Cannot set uniform when program has no code"); err_3.name = "RuntimeError"; throw err_3;
        }
        handle = _pymeth_get.call(this.locations, name, (-1));
        if (_pyfunc_truthy(handle < 0)) {
            if ((!_pyfunc_contains(name, this._known_invalid))) {
                _pymeth_append.call(this._known_invalid, name);
                console.log("Variable " + name + " is not an active texture");
            }
            return null;
        }
        if (_pyfunc_contains(name, this._unset_variables)) {
            _pymeth_remove.call(this._unset_variables, name);
        }
        this.activate();
        if (true) {
            unit = _pymeth_keys.call(this._samplers).length;
            if (_pyfunc_contains(name, this._samplers)) {
                unit = this._samplers[name][this._samplers[name].length -1];
            }
            this._samplers[name] = [value._target, value.handle, unit];
            this._gl.uniform1i(handle, unit);
        }
        return null;
    };

    Program.prototype.set_uniform = function (name, type_, value) {
        var a_type, count, err_3, funcname, handle, j, name_;
        // Set a uniform value.
        // 
        // A uniform is a value that is global to both the vertex and
        // fragment shader.
        // 
        // Parameters
        // ----------
        // name : str
        //     The name by which the uniform is known in the GLSL code.
        // type_ : str
        //     The type of the uniform, e.g. 'float', 'vec2', etc.
        // value : list of scalars
        //     The value for the uniform. Should be a list even for type float.
        if ((!_pyfunc_truthy(this._linked))) {
            err_3 = new Error('RuntimeError:' + "Cannot set uniform when program has no code"); err_3.name = "RuntimeError"; throw err_3;
        }
        handle = _pymeth_get.call(this.locations, name, (-1));
        if (_pyfunc_truthy(handle < 0)) {
            if ((!_pyfunc_contains(name, this._known_invalid))) {
                _pymeth_append.call(this._known_invalid, name);
                console.log("Variable " + name + " is not an active uniform");
            }
            return null;
        }
        if (_pyfunc_contains(name, this._unset_variables)) {
            _pymeth_remove.call(this._unset_variables, name);
        }
        count = 1;
        if ((!_pymeth_startswith.call(type_, "mat"))) {
            a_type = _pymeth_get.call({"int": "float", "bool": "float"}, type_, _pymeth_lstrip.call(type_, "ib"));
            count = Math.floor(value.length/(this.ATYPEINFO[a_type][0]));
        }
        if (_pyfunc_truthy(count > 1)) {
            for (j = 0; j < count; j += 1) {
                if ((_pyfunc_contains(("" + name + "[" + j + "]"), this._unset_variables))) {
                    name_ = "" + name + "[" + j + "]";
                    if (_pyfunc_contains(name_, this._unset_variables)) {
                        _pymeth_remove.call(this._unset_variables, name_);
                    }
                }
            }
        }
        funcname = this.UTYPEMAP[type_];
        this.activate();
        if (_pymeth_startswith.call(type_, "mat")) {
            this._gl[funcname](handle, false, value);
        } else {
            this._gl[funcname](handle, value);
        }
        return null;
    };

    Program.prototype.set_attribute = function (name, type_, value, stride, offset) {
        var args, err_3, funcname, gtype, handle, is_vbo, size, stub7_;
        stride = (stride === undefined) ? 0: stride;
        offset = (offset === undefined) ? 0: offset;
        // Set an attribute value. 
        // 
        // An attribute represents per-vertex data and can only be used
        // in the vertex shader.
        // 
        // Parameters
        // ----------
        // name : str
        //     The name by which the attribute is known in the GLSL code.
        // type_ : str
        //     The type of the attribute, e.g. 'float', 'vec2', etc.
        // value : VertexBuffer, array
        //     If value is a VertexBuffer, it is used (with stride and offset)
        //     for the vertex data. If value is an array, its used to set
        //     the value of all vertices (similar to a uniform).
        // stide : int, default 0
        //     The stride to "sample" the vertex data inside the buffer. Unless
        //     multiple vertex data are packed into a single buffer, this should
        //     be zero.
        // offset : int, default 0
        //     The offset to "sample" the vertex data inside the buffer. Unless
        //     multiple vertex data are packed into a single buffer, or only
        //     a part of the data must be used, this should probably be zero.
        if ((!_pyfunc_truthy(this._linked))) {
            err_3 = new Error('RuntimeError:' + "Cannot set attribute when program has no code"); err_3.name = "RuntimeError"; throw err_3;
        }
        is_vbo = value instanceof VertexBuffer;
        handle = _pymeth_get.call(this.locations, name, (-1));
        if (_pyfunc_truthy(handle < 0)) {
            if ((!_pyfunc_contains(name, this._known_invalid))) {
                _pymeth_append.call(this._known_invalid, name);
                if ((_pyfunc_truthy(is_vbo) && _pyfunc_truthy(offset > 0))) {
                } else {
                    console.log("Variable " + name + " is not an active attribute");
                }
            }
            return null;
        }
        if (_pyfunc_contains(name, this._unset_variables)) {
            _pymeth_remove.call(this._unset_variables, name);
        }
        this.activate();
        if ((!_pyfunc_truthy(is_vbo))) {
            funcname = this.ATYPEMAP[type_];
            this._attributes[name] = [0, handle, funcname, value];
        } else {
            stub7_ = this.ATYPEINFO[type_];
            size = stub7_[0];gtype = stub7_[1];
            funcname = "vertexAttribPointer";
            args = [size, gtype, this._gl.FALSE, stride, offset];
            this._attributes[name] = [value.handle, handle, funcname, args];
        }
        return null;
    };

    Program.prototype._pre_draw = function () {
        var args, attr_handle, funcname, stub10_, stub11_seq, stub8_, stub9_seq, tex_handle, tex_target, unit, vbo_handle, x;
        // Prepare for drawing.
        this.activate();
        stub9_seq = this._samplers;
        for (x in stub9_seq) {
            if (!stub9_seq.hasOwnProperty(x)){ continue; }
            x = stub9_seq[x];
            stub8_ = x;
            tex_target = stub8_[0];tex_handle = stub8_[1];unit = stub8_[2];
            this._gl.activeTexture(_pyfunc_add(this._gl.TEXTURE0, unit));
            this._gl.bindTexture(tex_target, tex_handle);
        }
        stub11_seq = this._attributes;
        for (x in stub11_seq) {
            if (!stub11_seq.hasOwnProperty(x)){ continue; }
            x = stub11_seq[x];
            stub10_ = x;
            vbo_handle = stub10_[0];attr_handle = stub10_[1];funcname = stub10_[2];args = stub10_[3];
            if (_pyfunc_truthy(vbo_handle)) {
                this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo_handle);
                this._gl.enableVertexAttribArray(attr_handle);
                this._gl[funcname].apply(this._gl, [].concat([attr_handle], args));
            } else {
                this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
                this._gl.disableVertexAttribArray(attr_handle);
                this._gl[funcname].apply(this._gl, [].concat([attr_handle], args));
            }
        }
        if ((!_pyfunc_truthy(this._validated))) {
            this._validated = true;
            this._validate();
        }
        return null;
    };

    Program.prototype._validate = function () {
        var err_3;
        if (this._unset_variables.length) {
            console.log("Program has unset variables: " + this._unset_variables + "");
        }
        this._gl.validateProgram(this.handle);
        if ((!_pyfunc_truthy(this._gl.getProgramParameter(this.handle, this._gl.VALIDATE_STATUS)))) {
            console.log(this._gl.getProgramInfoLog(this.handle));
            err_3 = new Error('RuntimeError:' + "Program validation error"); err_3.name = "RuntimeError"; throw err_3;
        }
        return null;
    };

    Program.prototype.draw = function (mode, selection) {
        var count, err_3, first, gtype, stub12_;
        // Draw the current visualization defined by the program.
        // 
        // Parameters
        // ----------
        // mode : GL enum
        //     Can be POINTS, LINES, LINE_LOOP, LINE_STRIP, LINE_FAN, TRIANGLES
        // selection : 2-element tuple or IndexBuffer
        //     The selection to draw, specified either as (first, count) or an
        //     IndexBuffer object.
        if ((!_pyfunc_truthy(this._linked))) {
            err_3 = new Error('RuntimeError:' + "Cannot draw program if code has not been set"); err_3.name = "RuntimeError"; throw err_3;
        }
        check_error(this._gl, "before draw");
        if (_pyfunc_truthy(selection instanceof IndexBuffer)) {
            this._pre_draw();
            selection.activate();
            count = selection._buffer_size / 2;
            gtype = this._gl.UNSIGNED_SHORT;
            this._gl.drawElements(mode, count, gtype, 0);
            selection.deactivate();
        } else {
            stub12_ = selection;
            first = stub12_[0];count = stub12_[1];
            if (_pyfunc_truthy(count)) {
                this._pre_draw();
                this._gl.drawArrays(mode, first, count);
            }
        }
        check_error(this._gl, "after draw");
        return null;
    };


    Buffer = function () {
        // Base buffer class for vertex data or index data.
        _pyfunc_instantiate(this, arguments);
    }
    Buffer.prototype = Object.create(GlooObject.prototype);
    Buffer.prototype._base_class = GlooObject.prototype;
    Buffer.prototype._class_name = "Buffer";
    
    Buffer.prototype._target = null;
    Buffer.prototype._usage = 35048;
    Buffer.prototype._create = function () {
        this.handle = this._gl.createBuffer();
        this._buffer_size = 0;
        return null;
    };

    Buffer.prototype.delete = function () {
        // Delete the buffer.
        this._gl.deleteBuffer(this.handle);
        return null;
    };

    Buffer.prototype.activate = function () {
        // Activete the buffer.
        this._gl.bindBuffer(this._target, this.handle);
        return null;
    };

    Buffer.prototype.deactivate = function () {
        // Disable the buffer.
        this._gl.bindBuffer(this._target, null);
        return null;
    };

    Buffer.prototype.set_size = function (nbytes) {
        // Set the size of the buffer in bytes.
        // 
        // Parameters
        // ----------
        // nbytes : int
        //     The number of bytes that the buffer needs to hold.
        if ((!_pyfunc_equals(nbytes, this._buffer_size))) {
            this.activate();
            this._gl.bufferData(this._target, nbytes, this._usage);
            this._buffer_size = nbytes;
        }
        return null;
    };

    Buffer.prototype.set_data = function (offset, data) {
        // Set the buffer data.
        // 
        // Parameters
        // ----------
        // offset : int
        //     The offset in bytes for the new data.
        // data : typed array
        //     The data to upload.
        this.activate();
        this._gl.bufferSubData(this._target, offset, data);
        return null;
    };


    VertexBuffer = function () {
        // A buffer for vertex data.
        _pyfunc_instantiate(this, arguments);
    }
    VertexBuffer.prototype = Object.create(Buffer.prototype);
    VertexBuffer.prototype._base_class = Buffer.prototype;
    VertexBuffer.prototype._class_name = "VertexBuffer";
    
    VertexBuffer.prototype._target = 34962;

    IndexBuffer = function () {
        // A buffer for index data.
        _pyfunc_instantiate(this, arguments);
    }
    IndexBuffer.prototype = Object.create(Buffer.prototype);
    IndexBuffer.prototype._base_class = Buffer.prototype;
    IndexBuffer.prototype._class_name = "IndexBuffer";
    
    IndexBuffer.prototype._target = 34963;

    Texture2D = function () {
        // A 2 dimensional regular grid.
        _pyfunc_instantiate(this, arguments);
    }
    Texture2D.prototype = Object.create(GlooObject.prototype);
    Texture2D.prototype._base_class = GlooObject.prototype;
    Texture2D.prototype._class_name = "Texture2D";
    
    Texture2D.prototype._target = 3553;
    Texture2D.prototype._types = {"Int8Array": 5120, "Uint8Array": 5121, "Int16Array": 5122, "Uint16Array": 5123, "Int32Array": 5124, "Uint32Array": 5125, "Float32Array": 5126};
    Texture2D.prototype._create = function () {
        this.handle = this._gl.createTexture();
        this._shape_format = null;
        return null;
    };

    Texture2D.prototype.delete = function () {
        // Delete the texture.
        this._gl.deleteTexture(this.handle);
        return null;
    };

    Texture2D.prototype.activate = function () {
        // Activate the texture.
        this._gl.bindTexture(this._target, this.handle);
        return null;
    };

    Texture2D.prototype.deactivate = function () {
        // Disable the texture.
        this._gl.bindTexture(this._target, 0);
        return null;
    };

    Texture2D.prototype._get_alignment = function (width) {
        var alignment, alignments, stub13_seq, stub14_itr;
        // Determines a textures byte alignment. If the width isn't a
        //         power of 2 we need to adjust the byte alignment of the image.
        //         The image height is unimportant.
        // 
        //         www.opengl.org/wiki/Common_Mistakes#Texture_upload_and_pixel_reads
        alignments = [4, 8, 2, 1];
        stub13_seq = alignments;
        if ((typeof stub13_seq === "object") && (!Array.isArray(stub13_seq))) {
            stub13_seq = Object.keys(stub13_seq);
        }
        for (stub14_itr = 0; stub14_itr < stub13_seq.length; stub14_itr += 1) {
            alignment = stub13_seq[stub14_itr];
            if ((_pyfunc_equals((width % alignment), 0))) {
                return alignment;
            }
        }
        return null;
    };

    Texture2D.prototype.set_wrapping = function (wrap_s, wrap_t) {
        // Set the texture wrapping mode.
        // 
        // Parameters
        // ----------
        // wrap_s : GL enum
        //     The mode to wrap the x dimension. Valid values are REPEAT
        //     CLAMP_TO_EDGE MIRRORED_REPEAT
        // wrap_t : GL enum
        //     The mode to wrap the y dimension. Same options as for wrap_s.
        this.activate();
        this._gl.texParameterf(this._target, this._gl.TEXTURE_WRAP_S, wrap_s);
        this._gl.texParameterf(this._target, this._gl.TEXTURE_WRAP_T, wrap_t);
        return null;
    };

    Texture2D.prototype.set_interpolation = function (min, mag) {
        // Set the texture interpolation mode
        // 
        // Parameters
        // ----------
        // min : GL enum
        //     The interpolation mode when minifying (i.e. zoomed out). Valid
        //     values are LINEAR and NEAREST.
        // max : GL enum
        //     The interpolation mode when magnifying (i.e. zoomed in). Valid
        //     values are LINEAR, NEAREST, NEAREST_MIPMAP_NEAREST,
        //     LINEAR_MIPMAP_NEAREST, NEAREST_MIPMAP_LINEAR, LINEAR_MIPMAP_LINEAR.
        this.activate();
        this._gl.texParameterf(this._target, this._gl.TEXTURE_MIN_FILTER, min);
        this._gl.texParameterf(this._target, this._gl.TEXTURE_MAG_FILTER, mag);
        return null;
    };

    Texture2D.prototype.set_size = function (shape, format) {
        var height, stub15_, width;
        // Set the size of the 2D texture.
        // 
        // Parameters
        // ----------
        // shape : tuple of ints
        //     The shape of the data to upload
        // format : GL enum
        //     The format of the texture data. Can be LUMINANCE, LUMINANCE_ALPHA,
        //     RGB, and RGBA.
        stub15_ = shape;
        height = stub15_[0];width = stub15_[1];
        if ((!_pyfunc_equals([height, width, format], this._shape_format))) {
            this._shape_format = [height, width, format];
            this.activate();
            this._gl.texImage2D(this._target, 0, format, width, height, 0, format, this._gl.UNSIGNED_BYTE, null);
        }
        this.u_shape = [height, width];
        return null;
    };

    Texture2D.prototype.set_data = function (offset, shape, data) {
        var _, alignment, err_3, format, gtype, height, stub16_, stub17_, width, x, y;
        // Set the 2D texture data.
        // 
        // Parameters
        // ----------
        // offset : tuple of ints
        //     Offset in pixels for each dimension.
        // shape : tuple of ints
        //     The shape of the data to upload
        // data : typed array
        //     The actual pixel data. Can be of any type, but on the GPU the
        //     dat is stored in 8 bit precision.
        if (_pyfunc_equals(shape.length, 2)) {
            shape = [shape[0], shape[1], 1];
        }
        this.activate();
        format = this._shape_format[2];
        stub16_ = shape;
        height = stub16_[0];width = stub16_[1];_ = stub16_[2];
        stub17_ = offset;
        y = stub17_[0];x = stub17_[1];
        gtype = _pymeth_get.call(this._types, data.constructor.name, null);
        if ((gtype === null)) {
            err_3 = new Error('ValueError:' + ("Type " + data.constructor.name + " not allowed for texture")); err_3.name = "ValueError"; throw err_3;
        }
        alignment = this._get_alignment(_pyfunc_mult(shape[shape.length -2], shape[shape.length -1]));
        if ((!_pyfunc_equals(alignment, 4))) {
            this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, alignment);
        }
        this._gl.texSubImage2D(this._target, 0, x, y, width, height, format, gtype, data);
        if ((!_pyfunc_equals(alignment, 4))) {
            this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 4);
        }
        return null;
    };


    Texture3DLike = function () {
        // A 2D texture with support to simulate a 3D texture.
        // 
        // To use this class, use set_size() and set_data() as if it was a 3D
        // texture. Add the GLSL_SAMPLE_NEAREST or GLSL_SAMPLE_LINEAR to the
        // shader to add the sample3D() function that can be used instead of
        // texture2D(). This function needs ``shape`` and ``tiles`` arguments
        // which can be set via uniforms, using the ``u_shape`` and ``u_tiles``
        // attributes of this object.
        _pyfunc_instantiate(this, arguments);
    }
    Texture3DLike.prototype = Object.create(Texture2D.prototype);
    Texture3DLike.prototype._base_class = Texture2D.prototype;
    Texture3DLike.prototype._class_name = "Texture3DLike";
    
    Texture3DLike.prototype.GLSL_SAMPLE_NEAREST = "\n        vec4 sample3D(sampler2D tex, vec3 texcoord, vec3 shape, vec2 tiles) {\n            shape.xyz = shape.zyx;  // silly row-major convention\n            float nrows = tiles.y, ncols = tiles.x;\n            // Don't let adjacent frames be interpolated into this one\n            texcoord.x = min(texcoord.x * shape.x, shape.x - 0.5);\n            texcoord.x = max(0.5, texcoord.x) / shape.x;\n            texcoord.y = min(texcoord.y * shape.y, shape.y - 0.5);\n            texcoord.y = max(0.5, texcoord.y) / shape.y;\n\n            float zindex = floor(texcoord.z * shape.z);\n\n            // Do a lookup in the 2D texture\n            float u = (mod(zindex, ncols) + texcoord.x) / ncols;\n            float v = (floor(zindex / ncols) + texcoord.y) / nrows;\n\n            return texture2D(tex, vec2(u,v));\n        }\n    ";
    Texture3DLike.prototype.GLSL_SAMPLE_LINEAR = "\n        vec4 sample3D(sampler2D tex, vec3 texcoord, vec3 shape, vec2 tiles) {\n            shape.xyz = shape.zyx;  // silly row-major convention\n            float nrows = tiles.y, ncols = tiles.x;\n            // Don't let adjacent frames be interpolated into this one\n            texcoord.x = min(texcoord.x * shape.x, shape.x - 0.5);\n            texcoord.x = max(0.5, texcoord.x) / shape.x;\n            texcoord.y = min(texcoord.y * shape.y, shape.y - 0.5);\n            texcoord.y = max(0.5, texcoord.y) / shape.y;\n\n            float z = texcoord.z * shape.z;\n            float zindex1 = floor(z);\n            float u1 = (mod(zindex1, ncols) + texcoord.x) / ncols;\n            float v1 = (floor(zindex1 / ncols) + texcoord.y) / nrows;\n\n            float zindex2 = zindex1 + 1.0;\n            float u2 = (mod(zindex2, ncols) + texcoord.x) / ncols;\n            float v2 = (floor(zindex2 / ncols) + texcoord.y) / nrows;\n\n            vec4 s1 = texture2D(tex, vec2(u1, v1));\n            vec4 s2 = texture2D(tex, vec2(u2, v2));\n\n            return s1 * (zindex2 - z) + s2 * (z - zindex1);\n        }\n    ";
    Texture3DLike.prototype._get_tile_info = function (shape) {
        var err_3, max_size, ncols, nrows;
        max_size = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
        nrows = Math.floor(max_size/shape[1]);
        nrows = Math.min(nrows, shape[0]);
        ncols = window.Math.ceil(shape[0] / nrows);
        if (_pyfunc_truthy(_pyfunc_mult(ncols, shape[2]) > max_size)) {
            err_3 = new Error('RuntimeError:' + ("Cannot fit 3D data with shape " + shape + " onto simulated 2D texture.")); err_3.name = "RuntimeError"; throw err_3;
        }
        return [nrows, ncols];
    };

    Texture3DLike.prototype.set_size = function (shape, format) {
        var ncols, nrows, sim_shape, stub18_;
        // Set the size of the 3D texture.
        // 
        // Parameters
        // ----------
        // shape : tuple of ints
        //     The shape of the data to upload
        // format : GL enum
        //     The format of the texture data. Can be LUMINANCE, LUMINANCE_ALPHA,
        //     RGB, and RGBA.
        stub18_ = this._get_tile_info(shape);
        nrows = stub18_[0];ncols = stub18_[1];
        sim_shape = [_pyfunc_mult(shape[1], nrows), _pyfunc_mult(shape[2], ncols)];
        Texture3DLike.prototype._base_class.set_size.call(this, sim_shape, format);
        this.u_shape = [shape[0], shape[1], shape[2]];
        this.u_tiles = [ncols, nrows];
        return null;
    };

    Texture3DLike.prototype.set_data = function (offset, shape, data) {
        var Type, col, elements_per_tile, err_3, ncols, nrows, row, sim_shape, stub19_, stub20_, tile, z, zeros;
        // Set the 3D texture data.
        // 
        // Parameters
        // ----------
        // offset : tuple of ints
        //     Offset in pixels for each dimension.
        // shape : tuple of ints
        //     The shape of the data to upload
        // data : typed array
        //     The actual pixel data. Can be of any type, but on the GPU the
        //     dat is stored in 8 bit precision.
        if (_pyfunc_equals(shape.length, 3)) {
            shape = [shape[0], shape[1], shape[2], 1];
        }
        if ((!(_pyfunc_all(((function list_comprehenson () {var res = [];var i, iter0, i0;iter0 = offset;if ((typeof iter0 === "object") && (!Array.isArray(iter0))) {iter0 = Object.keys(iter0);}for (i0=0; i0<iter0.length; i0++) {i = iter0[i0];{res.push(_pyfunc_equals(i, 0));}}return res;}).apply(this)))))) {
            err_3 = new Error('ValueError:' + "Texture3DLike does not support nonzero offset (for now)"); err_3.name = "ValueError"; throw err_3;
        }
        stub19_ = this._get_tile_info(shape);
        nrows = stub19_[0];ncols = stub19_[1];
        sim_shape = [_pyfunc_mult(shape[1], nrows), _pyfunc_mult(shape[2], ncols), shape[3]];
        if (_pyfunc_equals(ncols, 1)) {
            Texture3DLike.prototype._base_class.set_data.call(this, [0, 0], sim_shape, data);
        } else {
            Type = data.constructor;
            zeros = new Type(_pyfunc_mult(_pyfunc_mult(sim_shape[0], sim_shape[1]), sim_shape[2]));
            Texture3DLike.prototype._base_class.set_data.call(this, [0, 0], sim_shape, zeros);
            for (z = 0; z < shape[0]; z += 1) {
                stub20_ = [Math.floor(z/ncols), z % ncols];
                row = stub20_[0];col = stub20_[1];
                elements_per_tile = Math.floor(data.length/shape[0]);
                tile = data.slice(_pyfunc_mult(z, elements_per_tile),_pyfunc_mult((z + 1), elements_per_tile));
                Texture3DLike.prototype._base_class.set_data.call(this, [_pyfunc_mult(row, shape[1]), _pyfunc_mult(col, shape[2])], shape.slice(1), tile);
            }
        }
        return null;
    };


    return {"Buffer": Buffer, "GlooObject": GlooObject, "IndexBuffer": IndexBuffer, "Program": Program, "Texture2D": Texture2D, "Texture3DLike": Texture3DLike, "VertexBuffer": VertexBuffer, "check_error": check_error, "console": console};
}));

}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})

},{}],"kiwi":[function(require,module,exports){
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
var tsu;
(function (tsu) {






    /**
    * An iterator for an array of items.
    */
    var ArrayIterator = (function () {
        /*
        * Construct a new ArrayIterator.
        *
        * @param array The array of items to iterate.
        * @param [index] The index at which to start iteration.
        */
        function ArrayIterator(array, index) {
            if (typeof index === "undefined") { index = 0; }
            this._array = array;
            this._index = Math.max(0, Math.min(index, array.length));
        }
        /**
        * Returns the next item from the iterator or undefined.
        */
        ArrayIterator.prototype.__next__ = function () {
            return this._array[this._index++];
        };

        /**
        * Returns this same iterator.
        */
        ArrayIterator.prototype.__iter__ = function () {
            return this;
        };
        return ArrayIterator;
    })();
    tsu.ArrayIterator = ArrayIterator;

    /**
    * A reverse iterator for an array of items.
    */
    var ReverseArrayIterator = (function () {
        /**
        * Construct a new ReverseArrayIterator.
        *
        * @param array The array of items to iterate.
        * @param [index] The index at which to start iteration.
        */
        function ReverseArrayIterator(array, index) {
            if (typeof index === "undefined") { index = array.length; }
            this._array = array;
            this._index = Math.max(0, Math.min(index, array.length));
        }
        /**
        * Returns the next item from the iterator or undefined.
        */
        ReverseArrayIterator.prototype.__next__ = function () {
            return this._array[--this._index];
        };

        /**
        * Returns this same iterator.
        */
        ReverseArrayIterator.prototype.__iter__ = function () {
            return this;
        };
        return ReverseArrayIterator;
    })();
    tsu.ReverseArrayIterator = ReverseArrayIterator;



    function iter(object) {
        if (object instanceof Array) {
            return new ArrayIterator(object);
        }
        return object.__iter__();
    }
    tsu.iter = iter;



    function reversed(object) {
        if (object instanceof Array) {
            return new ReverseArrayIterator(object);
        }
        return object.__reversed__();
    }
    tsu.reversed = reversed;

    /**
    * Returns the next value from an iterator, or undefined.
    */
    function next(iterator) {
        return iterator.__next__();
    }
    tsu.next = next;



    function asArray(object) {
        if (object instanceof Array) {
            return object.slice();
        }
        var value;
        var array = [];
        var it = object.__iter__();
        while ((value = it.__next__()) !== undefined) {
            array.push(value);
        }
        return array;
    }
    tsu.asArray = asArray;



    function forEach(object, callback) {
        if (object instanceof Array) {
            for (var i = 0, n = object.length; i < n; ++i) {
                if (callback(object[i]) === false) {
                    return;
                }
            }
        } else {
            var value;
            var it = object.__iter__();
            while ((value = it.__next__()) !== undefined) {
                if (callback(value) === false) {
                    return;
                }
            }
        }
    }
    tsu.forEach = forEach;



    function map(object, callback) {
        var result = [];
        if (object instanceof Array) {
            for (var i = 0, n = object.length; i < n; ++i) {
                result.push(callback(object[i]));
            }
        } else {
            var value;
            var it = object.__iter__();
            while ((value = it.__next__()) !== undefined) {
                result.push(callback(value));
            }
        }
        return result;
    }
    tsu.map = map;



    function filter(object, callback) {
        var value;
        var result = [];
        if (object instanceof Array) {
            for (var i = 0, n = object.length; i < n; ++i) {
                value = object[i];
                if (callback(value)) {
                    result.push(value);
                }
            }
        } else {
            var it = object.__iter__();
            while ((value = it.__next__()) !== undefined) {
                if (callback(value)) {
                    result.push(value);
                }
            }
        }
        return result;
    }
    tsu.filter = filter;
})(tsu || (tsu = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
var tsu;
(function (tsu) {


    /**
    * A class which defines a generic pair object.
    */
    var Pair = (function () {
        /**
        * Construct a new Pair object.
        *
        * @param first The first item of the pair.
        * @param second The second item of the pair.
        */
        function Pair(first, second) {
            this.first = first;
            this.second = second;
        }
        /**
        * Create a copy of the pair.
        */
        Pair.prototype.copy = function () {
            return new Pair(this.first, this.second);
        };
        return Pair;
    })();
    tsu.Pair = Pair;
})(tsu || (tsu = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="iterator.ts"/>
/// <reference path="utility.ts"/>
var tsu;
(function (tsu) {
    /**
    * Perform a lower bound search on a sorted array.
    *
    * @param array The array of sorted items to search.
    * @param value The value to located in the array.
    * @param compare The value comparison function.
    * @returns The index of the first element in the array which
    *          compares greater than or equal to the given value.
    */
    function lowerBound(array, value, compare) {
        var begin = 0;
        var n = array.length;
        var half;
        var middle;
        while (n > 0) {
            half = n >> 1;
            middle = begin + half;
            if (compare(array[middle], value) < 0) {
                begin = middle + 1;
                n -= half + 1;
            } else {
                n = half;
            }
        }
        return begin;
    }
    tsu.lowerBound = lowerBound;

    /**
    * Perform a binary search on a sorted array.
    *
    * @param array The array of sorted items to search.
    * @param value The value to located in the array.
    * @param compare The value comparison function.
    * @returns The index of the found item, or -1.
    */
    function binarySearch(array, value, compare) {
        var index = lowerBound(array, value, compare);
        if (index === array.length) {
            return -1;
        }
        var item = array[index];
        if (compare(item, value) !== 0) {
            return -1;
        }
        return index;
    }
    tsu.binarySearch = binarySearch;

    /**
    * Perform a binary find on a sorted array.
    *
    * @param array The array of sorted items to search.
    * @param value The value to located in the array.
    * @param compare The value comparison function.
    * @returns The found item in the array, or undefined.
    */
    function binaryFind(array, value, compare) {
        var index = lowerBound(array, value, compare);
        if (index === array.length) {
            return undefined;
        }
        var item = array[index];
        if (compare(item, value) !== 0) {
            return undefined;
        }
        return item;
    }
    tsu.binaryFind = binaryFind;



    function asSet(items, compare) {
        var array = tsu.asArray(items);
        var n = array.length;
        if (n <= 1) {
            return array;
        }
        array.sort(compare);
        var result = [array[0]];
        for (var i = 1, j = 0; i < n; ++i) {
            var item = array[i];
            if (compare(result[j], item) !== 0) {
                result.push(item);
                ++j;
            }
        }
        return result;
    }
    tsu.asSet = asSet;

    /**
    * Test whether a two sorted arrays sets are disjoint.
    *
    * @param first The first sorted array set.
    * @param second The second sorted array set.
    * @param compare The value comparison function.
    * @returns true if the sets are disjoint, false otherwise.
    */
    function setIsDisjoint(first, second, compare) {
        var i = 0, j = 0;
        var len1 = first.length;
        var len2 = second.length;
        while (i < len1 && j < len2) {
            var v = compare(first[i], second[j]);
            if (v < 0) {
                ++i;
            } else if (v > 0) {
                ++j;
            } else {
                return false;
            }
        }
        return true;
    }
    tsu.setIsDisjoint = setIsDisjoint;

    /**
    * Test whether one sorted array set is the subset of another.
    *
    * @param first The potential subset.
    * @param second The potential superset.
    * @param compare The value comparison function.
    * @returns true if the first set is a subset of the second.
    */
    function setIsSubset(first, second, compare) {
        var len1 = first.length;
        var len2 = second.length;
        if (len1 > len2) {
            return false;
        }
        var i = 0, j = 0;
        while (i < len1 && j < len2) {
            var v = compare(first[i], second[j]);
            if (v < 0) {
                return false;
            } else if (v > 0) {
                ++j;
            } else {
                ++i;
                ++j;
            }
        }
        if (i < len1) {
            return false;
        }
        return true;
    }
    tsu.setIsSubset = setIsSubset;

    /**
    * Create the set union of two sorted set arrays.
    var j = 0;
    *
    * @param first The first sorted array set.
    * @param second The second sorted array set.
    * @param compare The value comparison function.
    * @returns The set union of the two arrays.
    */
    function setUnion(first, second, compare) {
        var i = 0, j = 0;
        var len1 = first.length;
        var len2 = second.length;
        var merged = [];
        while (i < len1 && j < len2) {
            var a = first[i];
            var b = second[j];
            var v = compare(a, b);
            if (v < 0) {
                merged.push(a);
                ++i;
            } else if (v > 0) {
                merged.push(b);
                ++j;
            } else {
                merged.push(a);
                ++i;
                ++j;
            }
        }
        while (i < len1) {
            merged.push(first[i]);
            ++i;
        }
        while (j < len2) {
            merged.push(second[j]);
            ++j;
        }
        return merged;
    }
    tsu.setUnion = setUnion;

    /**
    * Create a set intersection of two sorted set arrays.
    *
    * @param first The first sorted array set.
    * @param second The second sorted array set.
    * @param compare The value comparison function.
    * @returns The set intersection of the two arrays.
    */
    function setIntersection(first, second, compare) {
        var i = 0, j = 0;
        var len1 = first.length;
        var len2 = second.length;
        var merged = [];
        while (i < len1 && j < len2) {
            var a = first[i];
            var b = second[j];
            var v = compare(a, b);
            if (v < 0) {
                ++i;
            } else if (v > 0) {
                ++j;
            } else {
                merged.push(a);
                ++i;
                ++j;
            }
        }
        return merged;
    }
    tsu.setIntersection = setIntersection;

    /**
    * Create a set difference of two sorted set arrays.
    *
    * @param first The first sorted array set.
    * @param second The second sorted array set.
    * @param compare The value comparison function.
    * @returns The set difference of the two arrays.
    */
    function setDifference(first, second, compare) {
        var i = 0, j = 0;
        var len1 = first.length;
        var len2 = second.length;
        var merged = [];
        while (i < len1 && j < len2) {
            var a = first[i];
            var b = second[j];
            var v = compare(a, b);
            if (v < 0) {
                merged.push(a);
                ++i;
            } else if (v > 0) {
                ++j;
            } else {
                ++i;
                ++j;
            }
        }
        while (i < len1) {
            merged.push(first[i]);
            ++i;
        }
        return merged;
    }
    tsu.setDifference = setDifference;

    /**
    * Create a set symmetric difference of two sorted set arrays.
    *
    * @param first The first sorted array set.
    * @param second The second sorted array set.
    * @param compare The value comparison function.
    * @returns The set symmetric difference of the two arrays.
    */
    function setSymmetricDifference(first, second, compare) {
        var i = 0, j = 0;
        var len1 = first.length;
        var len2 = second.length;
        var merged = [];
        while (i < len1 && j < len2) {
            var a = first[i];
            var b = second[j];
            var v = compare(a, b);
            if (v < 0) {
                merged.push(a);
                ++i;
            } else if (v > 0) {
                merged.push(b);
                ++j;
            } else {
                ++i;
                ++j;
            }
        }
        while (i < len1) {
            merged.push(first[i]);
            ++i;
        }
        while (j < len2) {
            merged.push(second[j]);
            ++j;
        }
        return merged;
    }
    tsu.setSymmetricDifference = setSymmetricDifference;
})(tsu || (tsu = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="iterator.ts"/>
var tsu;
(function (tsu) {
    /**
    * A base class for implementing array-based data structures.
    *
    * @class
    */
    var ArrayBase = (function () {
        function ArrayBase() {
            /*
            * The internal data array.
            *
            * @protected
            */
            this._array = [];
        }
        /**
        * Returns the number of items in the array.
        */
        ArrayBase.prototype.size = function () {
            return this._array.length;
        };

        /**
        * Returns true if the array is empty.
        */
        ArrayBase.prototype.empty = function () {
            return this._array.length === 0;
        };

        /**
        * Returns the item at the given array index.
        *
        * @param index The integer index of the desired item.
        */
        ArrayBase.prototype.itemAt = function (index) {
            return this._array[index];
        };

        /**
        * Removes and returns the item at the given index.
        *
        * @param index The integer index of the desired item.
        */
        ArrayBase.prototype.takeAt = function (index) {
            return this._array.splice(index, 1)[0];
        };

        /**
        * Clear the internal contents of array.
        */
        ArrayBase.prototype.clear = function () {
            this._array = [];
        };

        /**
        * Swap this array's contents with another array.
        *
        * @param other The array base to use for the swap.
        */
        ArrayBase.prototype.swap = function (other) {
            var array = this._array;
            this._array = other._array;
            other._array = array;
        };

        /**
        * Returns an iterator over the array of items.
        */
        ArrayBase.prototype.__iter__ = function () {
            return tsu.iter(this._array);
        };

        /**
        * Returns a reverse iterator over the array of items.
        */
        ArrayBase.prototype.__reversed__ = function () {
            return tsu.reversed(this._array);
        };
        return ArrayBase;
    })();
    tsu.ArrayBase = ArrayBase;
})(tsu || (tsu = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
/// <reference path="algorithm.ts"/>
/// <reference path="array_base.ts"/>
/// <reference path="iterator.ts"/>
/// <reference path="utility.ts"/>
var tsu;
(function (tsu) {
    /**
    * A mapping container build on a sorted array.
    *
    * @class
    */
    var AssociativeArray = (function (_super) {
        __extends(AssociativeArray, _super);
        /**
        * Construct a new AssociativeArray.
        *
        * @param compare The key comparison function.
        */
        function AssociativeArray(compare) {
            _super.call(this);
            this._compare = compare;
            this._wrapped = wrapCompare(compare);
        }
        /**
        * Returns the key comparison function used by this array.
        */
        AssociativeArray.prototype.comparitor = function () {
            return this._compare;
        };

        /**
        * Return the array index of the given key, or -1.
        *
        * @param key The key to locate in the array.
        */
        AssociativeArray.prototype.indexOf = function (key) {
            return tsu.binarySearch(this._array, key, this._wrapped);
        };

        /**
        * Returns true if the key is in the array, false otherwise.
        *
        * @param key The key to locate in the array.
        */
        AssociativeArray.prototype.contains = function (key) {
            return tsu.binarySearch(this._array, key, this._wrapped) >= 0;
        };

        /**
        * Returns the pair associated with the given key, or undefined.
        *
        * @param key The key to locate in the array.
        */
        AssociativeArray.prototype.find = function (key) {
            return tsu.binaryFind(this._array, key, this._wrapped);
        };

        /**
        * Returns the pair associated with the key if it exists.
        *
        * If the key does not exist, a new pair will be created and
        * inserted using the value created by the given factory.
        *
        * @param key The key to locate in the array.
        * @param factory The function which creates the default value.
        */
        AssociativeArray.prototype.setDefault = function (key, factory) {
            var array = this._array;
            var index = tsu.lowerBound(array, key, this._wrapped);
            if (index === array.length) {
                var pair = new tsu.Pair(key, factory());
                array.push(pair);
                return pair;
            }
            var currPair = array[index];
            if (this._compare(currPair.first, key) !== 0) {
                var pair = new tsu.Pair(key, factory());
                array.splice(index, 0, pair);
                return pair;
            }
            return currPair;
        };

        /**
        * Insert the pair into the array and return the pair.
        *
        * This will overwrite any existing entry in the array.
        *
        * @param key The key portion of the pair.
        * @param value The value portion of the pair.
        */
        AssociativeArray.prototype.insert = function (key, value) {
            var array = this._array;
            var index = tsu.lowerBound(array, key, this._wrapped);
            if (index === array.length) {
                var pair = new tsu.Pair(key, value);
                array.push(pair);
                return pair;
            }
            var currPair = array[index];
            if (this._compare(currPair.first, key) !== 0) {
                var pair = new tsu.Pair(key, value);
                array.splice(index, 0, pair);
                return pair;
            }
            currPair.second = value;
            return currPair;
        };

        AssociativeArray.prototype.update = function (object) {
            var _this = this;
            if (object instanceof AssociativeArray) {
                var obj = object;
                this._array = merge(this._array, obj._array, this._compare);
            } else {
                tsu.forEach(object, function (pair) {
                    _this.insert(pair.first, pair.second);
                });
            }
        };

        /**
        * Removes and returns the pair for the given key, or undefined.
        *
        * @param key The key to remove from the map.
        */
        AssociativeArray.prototype.erase = function (key) {
            var array = this._array;
            var index = tsu.binarySearch(array, key, this._wrapped);
            if (index < 0) {
                return undefined;
            }
            return array.splice(index, 1)[0];
        };

        /**
        * Create a copy of this associative array.
        */
        AssociativeArray.prototype.copy = function () {
            var theCopy = new AssociativeArray(this._compare);
            var copyArray = theCopy._array;
            var thisArray = this._array;
            for (var i = 0, n = thisArray.length; i < n; ++i) {
                copyArray.push(thisArray[i].copy());
            }
            return theCopy;
        };
        return AssociativeArray;
    })(tsu.ArrayBase);
    tsu.AssociativeArray = AssociativeArray;

    /**
    * An internal which wraps a comparison key function.
    */
    function wrapCompare(cmp) {
        return function (pair, value) {
            return cmp(pair.first, value);
        };
    }

    /**
    * An internal function which merges two ordered pair arrays.
    */
    function merge(first, second, compare) {
        var i = 0, j = 0;
        var len1 = first.length;
        var len2 = second.length;
        var merged = [];
        while (i < len1 && j < len2) {
            var a = first[i];
            var b = second[j];
            var v = compare(a.first, b.first);
            if (v < 0) {
                merged.push(a.copy());
                ++i;
            } else if (v > 0) {
                merged.push(b.copy());
                ++j;
            } else {
                merged.push(b.copy());
                ++i;
                ++j;
            }
        }
        while (i < len1) {
            merged.push(first[i].copy());
            ++i;
        }
        while (j < len2) {
            merged.push(second[j].copy());
            ++j;
        }
        return merged;
    }
})(tsu || (tsu = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="algorithm.ts"/>
/// <reference path="array_base.ts"/>
/// <reference path="iterator.ts"/>
/// <reference path="utility.ts"/>
var tsu;
(function (tsu) {
    /**
    * A set container built on a sorted array.
    *
    * @class
    */
    var UniqueArray = (function (_super) {
        __extends(UniqueArray, _super);
        /**
        * Construct a new UniqueArray.
        *
        * @param compare The item comparison function.
        */
        function UniqueArray(compare) {
            _super.call(this);
            this._compare = compare;
        }
        /**
        * Returns the comparison function for this array.
        */
        UniqueArray.prototype.comparitor = function () {
            return this._compare;
        };

        /**
        * Return the array index of the given item, or -1.
        *
        * @param item The item to locate in the array.
        */
        UniqueArray.prototype.indexOf = function (item) {
            return tsu.binarySearch(this._array, item, this._compare);
        };

        /**
        * Returns true if the item is in the array, false otherwise.
        *
        * @param item The item to locate in the array.
        */
        UniqueArray.prototype.contains = function (item) {
            return tsu.binarySearch(this._array, item, this._compare) >= 0;
        };

        /**
        * Insert an item into the array.
        *
        * Returns true if the item is new to the set, false otherwise.
        *
        * @param item The item to insert into the array.
        */
        UniqueArray.prototype.insert = function (item) {
            var array = this._array;
            var index = tsu.lowerBound(array, item, this._compare);
            if (index === array.length) {
                array.push(item);
                return true;
            }
            if (this._compare(array[index], item) !== 0) {
                array.splice(index, 0, item);
                return true;
            }
            return false;
        };

        /**
        * Remove an item from the array.
        *
        * Returns true if the item was removed, false otherwise.
        *
        * @param item The item to remove from the array.
        */
        UniqueArray.prototype.erase = function (item) {
            var array = this._array;
            var index = tsu.binarySearch(array, item, this._compare);
            if (index < 0) {
                return false;
            }
            array.splice(index, 1);
            return true;
        };

        /**
        * Create a copy of this unique array.
        */
        UniqueArray.prototype.copy = function () {
            var theCopy = new UniqueArray(this._compare);
            theCopy._array = this._array.slice();
            return theCopy;
        };

        UniqueArray.prototype.isDisjoint = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            return tsu.setIsDisjoint(this._array, other, cmp);
        };

        UniqueArray.prototype.isSubset = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            return tsu.setIsSubset(this._array, other, cmp);
        };

        UniqueArray.prototype.isSuperset = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            return tsu.setIsSubset(other, this._array, cmp);
        };

        UniqueArray.prototype.union = function (object) {
            var cmp = this._compare;
            var res = new UniqueArray(cmp);
            var other = toSet(object, cmp);
            res._array = tsu.setUnion(this._array, other, cmp);
            return res;
        };

        UniqueArray.prototype.intersection = function (object) {
            var cmp = this._compare;
            var res = new UniqueArray(cmp);
            var other = toSet(object, cmp);
            res._array = tsu.setIntersection(this._array, other, cmp);
            return res;
        };

        UniqueArray.prototype.difference = function (object) {
            var cmp = this._compare;
            var res = new UniqueArray(cmp);
            var other = toSet(object, cmp);
            res._array = tsu.setDifference(this._array, other, cmp);
            return res;
        };

        UniqueArray.prototype.symmetricDifference = function (object) {
            var cmp = this._compare;
            var res = new UniqueArray(cmp);
            var other = toSet(object, cmp);
            res._array = tsu.setSymmetricDifference(this._array, other, cmp);
            return res;
        };

        UniqueArray.prototype.unionUpdate = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            this._array = tsu.setUnion(this._array, other, cmp);
        };

        UniqueArray.prototype.intersectionUpdate = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            this._array = tsu.setIntersection(this._array, other, cmp);
        };

        UniqueArray.prototype.differenceUpdate = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            this._array = tsu.setDifference(this._array, other, cmp);
        };

        UniqueArray.prototype.symmetricDifferenceUpdate = function (object) {
            var cmp = this._compare;
            var other = toSet(object, cmp);
            this._array = tsu.setSymmetricDifference(this._array, other, cmp);
        };
        return UniqueArray;
    })(tsu.ArrayBase);
    tsu.UniqueArray = UniqueArray;



    function toSet(arg, cmp) {
        if (arg instanceof UniqueArray) {
            return arg._array;
        }
        return tsu.asSet(arg, cmp);
    }
})(tsu || (tsu = {}));

/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="algorithm.ts"/>
/// <reference path="array_base.ts"/>
/// <reference path="associative_array.ts"/>
/// <reference path="iterator.ts"/>
/// <reference path="unique_array.ts"/>
/// <reference path="utility.ts"/>

/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
// <reference path="expression.ts">
// <reference path="strength.ts">
var kiwi;
(function (kiwi) {
    /**
    * An enum defining the linear constraint operators.
    */
    (function (Operator) {
        Operator[Operator["Le"] = 0] = "Le";
        Operator[Operator["Ge"] = 1] = "Ge";
        Operator[Operator["Eq"] = 2] = "Eq";
    })(kiwi.Operator || (kiwi.Operator = {}));
    var Operator = kiwi.Operator;

    /**
    * A linear constraint equation.
    *
    * A constraint equation is composed of an expression, an operator,
    * and a strength. The RHS of the equation is implicitly zero.
    *
    * @class
    */
    var Constraint = (function () {
        /**
        * Construct a new Constraint.
        *
        * @param expression The constraint expression.
        * @param operator The equation operator.
        * @param strength The strength of the constraint.
        */
        function Constraint(expression, operator, strength) {
            if (typeof strength === "undefined") { strength = kiwi.Strength.required; }
            this._id = CnId++;
            this._operator = operator;
            this._expression = expression;
            this._strength = kiwi.Strength.clip(strength);
        }
        /**
        * A static constraint comparison function.
        */
        Constraint.Compare = function (a, b) {
            return a.id() - b.id();
        };

        /**
        * Returns the unique id number of the constraint.
        */
        Constraint.prototype.id = function () {
            return this._id;
        };

        /**
        * Returns the expression of the constraint.
        */
        Constraint.prototype.expression = function () {
            return this._expression;
        };

        /**
        * Returns the relational operator of the constraint.
        */
        Constraint.prototype.op = function () {
            return this._operator;
        };

        /**
        * Returns the strength of the constraint.
        */
        Constraint.prototype.strength = function () {
            return this._strength;
        };
        return Constraint;
    })();
    kiwi.Constraint = Constraint;

    /**
    * The internal constraint id counter.
    */
    var CnId = 0;
})(kiwi || (kiwi = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="../thirdparty/tsu.d.ts"/>
var kiwi;
(function (kiwi) {
    function createMap(compare) {
        return new tsu.AssociativeArray(compare);
    }
    kiwi.createMap = createMap;
})(kiwi || (kiwi = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
var kiwi;
(function (kiwi) {
    /**
    * The primary user constraint variable.
    *
    * @class
    */
    var Variable = (function () {
        /**
        * Construct a new Variable
        *
        * @param [name] The name to associated with the variable.
        */
        function Variable(name) {
            if (typeof name === "undefined") { name = ""; }
            this._value = 0.0;
            this._context = null;
            this._id = VarId++;
            this._name = name;
        }
        /**
        * A static variable comparison function.
        */
        Variable.Compare = function (a, b) {
            return a.id() - b.id();
        };

        /**
        * Returns the unique id number of the variable.
        */
        Variable.prototype.id = function () {
            return this._id;
        };

        /**
        * Returns the name of the variable.
        */
        Variable.prototype.name = function () {
            return this._name;
        };

        /**
        * Set the name of the variable.
        */
        Variable.prototype.setName = function (name) {
            this._name = name;
        };

        /**
        * Returns the user context object of the variable.
        */
        Variable.prototype.context = function () {
            return this._context;
        };

        /**
        * Set the user context object of the variable.
        */
        Variable.prototype.setContext = function (context) {
            this._context = context;
        };

        /**
        * Returns the value of the variable.
        */
        Variable.prototype.value = function () {
            return this._value;
        };

        /**
        * Set the value of the variable.
        */
        Variable.prototype.setValue = function (value) {
            this._value = value;
        };
        return Variable;
    })();
    kiwi.Variable = Variable;

    /**
    * The internal variable id counter.
    */
    var VarId = 0;
})(kiwi || (kiwi = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="../thirdparty/tsu.d.ts"/>
/// <reference path="maptype.ts"/>
/// <reference path="variable.ts"/>
var kiwi;
(function (kiwi) {
    /**
    * An expression of variable terms and a constant.
    *
    * @class
    */
    var Expression = (function () {
        function Expression() {
            var parsed = parseArgs(arguments);
            this._terms = parsed.terms;
            this._constant = parsed.constant;
        }
        /**
        * Returns the mapping of terms in the expression.
        *
        * This *must* be treated as const.
        */
        Expression.prototype.terms = function () {
            return this._terms;
        };

        /**
        * Returns the constant of the expression.
        */
        Expression.prototype.constant = function () {
            return this._constant;
        };

        /**
        * Returns the computed value of the expression.
        */
        Expression.prototype.value = function () {
            var result = this._constant;
            tsu.forEach(this._terms, function (pair) {
                result += pair.first.value() * pair.second;
            });
            return result;
        };
        return Expression;
    })();
    kiwi.Expression = Expression;



    /**
    * An internal argument parsing function.
    */
    function parseArgs(args) {
        var constant = 0.0;
        var factory = function () {
            return 0.0;
        };
        var terms = kiwi.createMap(kiwi.Variable.Compare);
        for (var i = 0, n = args.length; i < n; ++i) {
            var item = args[i];
            if (typeof item === "number") {
                constant += item;
            } else if (item instanceof kiwi.Variable) {
                terms.setDefault(item, factory).second += 1.0;
            } else if (item instanceof Array) {
                if (item.length !== 2) {
                    throw new Error("array must have length 2");
                }
                var value = item[0];
                var variable = item[1];
                if (typeof value !== "number") {
                    throw new Error("array item 0 must be a number");
                }
                if (!(variable instanceof kiwi.Variable)) {
                    throw new Error("array item 1 must be a variable");
                }
                terms.setDefault(variable, factory).second += value;
            } else {
                throw new Error("invalid Expression argument: " + item);
            }
        }
        return { terms: terms, constant: constant };
    }
})(kiwi || (kiwi = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
var kiwi;
(function (kiwi) {
    (function (Strength) {
        /**
        * Create a new symbolic strength.
        */
        function create(a, b, c, w) {
            if (typeof w === "undefined") { w = 1.0; }
            var result = 0.0;
            result += Math.max(0.0, Math.min(1000.0, a * w)) * 1000000.0;
            result += Math.max(0.0, Math.min(1000.0, b * w)) * 1000.0;
            result += Math.max(0.0, Math.min(1000.0, c * w));
            return result;
        }
        Strength.create = create;

        /**
        * The 'required' symbolic strength.
        */
        Strength.required = create(1000.0, 1000.0, 1000.0);

        /**
        * The 'strong' symbolic strength.
        */
        Strength.strong = create(1.0, 0.0, 0.0);

        /**
        * The 'medium' symbolic strength.
        */
        Strength.medium = create(0.0, 1.0, 0.0);

        /**
        * The 'weak' symbolic strength.
        */
        Strength.weak = create(0.0, 0.0, 1.0);

        /**
        * Clip a symbolic strength to the allowed min and max.
        */
        function clip(value) {
            return Math.max(0.0, Math.min(Strength.required, value));
        }
        Strength.clip = clip;
    })(kiwi.Strength || (kiwi.Strength = {}));
    var Strength = kiwi.Strength;
})(kiwi || (kiwi = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="../thirdparty/tsu.d.ts"/>
/// <reference path="constraint.ts"/>
/// <reference path="expression.ts"/>
/// <reference path="maptype.ts"/>
/// <reference path="strength.ts"/>
/// <reference path="variable.ts"/>
var kiwi;
(function (kiwi) {
    /**
    * The constraint solver class.
    *
    * @class
    */
    var Solver = (function () {
        /**
        * Construct a new Solver.
        */
        function Solver() {
            this._cnMap = createCnMap();
            this._rowMap = createRowMap();
            this._varMap = createVarMap();
            this._editMap = createEditMap();
            this._infeasibleRows = [];
            this._objective = new Row();
            this._artificial = null;
            this._idTick = 0;
        }
        /**
        * Add a constraint to the solver.
        */
        Solver.prototype.addConstraint = function (constraint) {
            var cnPair = this._cnMap.find(constraint);
            if (cnPair !== undefined) {
                throw new Error("duplicate constraint");
            }

            // Creating a row causes symbols to be reserved for the variables
            // in the constraint. If this method exits with an exception,
            // then its possible those variables will linger in the var map.
            // Since its likely that those variables will be used in other
            // constraints and since exceptional conditions are uncommon,
            // i'm not too worried about aggressive cleanup of the var map.
            var data = this._createRow(constraint);
            var row = data.row;
            var tag = data.tag;
            var subject = this._chooseSubject(row, tag);

            // If chooseSubject couldnt find a valid entering symbol, one
            // last option is available if the entire row is composed of
            // dummy variables. If the constant of the row is zero, then
            // this represents redundant constraints and the new dummy
            // marker can enter the basis. If the constant is non-zero,
            // then it represents an unsatisfiable constraint.
            if (subject.type() === 0 /* Invalid */ && row.allDummies()) {
                if (!nearZero(row.constant())) {
                    throw new Error("unsatisfiable constraint");
                } else {
                    subject = tag.marker;
                }
            }

            // If an entering symbol still isn't found, then the row must
            // be added using an artificial variable. If that fails, then
            // the row represents an unsatisfiable constraint.
            if (subject.type() === 0 /* Invalid */) {
                if (!this._addWithArtificialVariable(row)) {
                    var names = ""
                    for (var i=0, item; item = constraint._expression._terms._array[i]; i++) {
                        names += item.first._name;
                        names += ", "
                    }
                    var human_operator = ['LE', 'GE', 'EQ'];
                    throw new Error("Unsatisfiable constraint [" + names.slice(0, -2) + "] operator: " + human_operator[constraint._operator]);
                }
            } else {
                row.solveFor(subject);
                this._substitute(subject, row);
                this._rowMap.insert(subject, row);
            }

            this._cnMap.insert(constraint, tag);

            // Optimizing after each constraint is added performs less
            // aggregate work due to a smaller average system size. It
            // also ensures the solver remains in a consistent state.
            this._optimize(this._objective);
        };

        /**
        * Remove a constraint from the solver.
        */
        Solver.prototype.removeConstraint = function (constraint) {
            var cnPair = this._cnMap.erase(constraint);
            if (cnPair === undefined) {
                throw new Error("unknown constraint");
            }

            // Remove the error effects from the objective function
            // *before* pivoting, or substitutions into the objective
            // will lead to incorrect solver results.
            this._removeConstraintEffects(constraint, cnPair.second);

            // If the marker is basic, simply drop the row. Otherwise,
            // pivot the marker into the basis and then drop the row.
            var marker = cnPair.second.marker;
            var rowPair = this._rowMap.erase(marker);
            if (rowPair === undefined) {
                var leaving = this._getMarkerLeavingSymbol(marker);
                if (leaving.type() === 0 /* Invalid */) {
                    throw new Error("failed to find leaving row");
                }
                rowPair = this._rowMap.erase(leaving);
                rowPair.second.solveForEx(leaving, marker);
                this._substitute(marker, rowPair.second);
            }

            // Optimizing after each constraint is removed ensures that the
            // solver remains consistent. It makes the solver api easier to
            // use at a small tradeoff for speed.
            this._optimize(this._objective);
        };

        /**
        * Test whether the solver contains the constraint.
        */
        Solver.prototype.hasConstraint = function (constraint) {
            return this._cnMap.contains(constraint);
        };

        /**
        * Add an edit variable to the solver.
        */
        Solver.prototype.addEditVariable = function (variable, strength) {
            var editPair = this._editMap.find(variable);
            if (editPair !== undefined) {
                throw new Error("duplicate edit variable");
            }
            strength = kiwi.Strength.clip(strength);
            if (strength === kiwi.Strength.required) {
                throw new Error("bad required strength");
            }
            var expr = new kiwi.Expression(variable);
            var cn = new kiwi.Constraint(expr, 2 /* Eq */, strength);
            this.addConstraint(cn);
            var tag = this._cnMap.find(cn).second;
            var info = { tag: tag, constraint: cn, constant: 0.0 };
            this._editMap.insert(variable, info);
        };

        /**
        * Remove an edit variable from the solver.
        */
        Solver.prototype.removeEditVariable = function (variable) {
            var editPair = this._editMap.erase(variable);
            if (editPair === undefined) {
                throw new Error("unknown edit variable");
            }
            this.removeConstraint(editPair.second.constraint);
        };

        /**
        * Test whether the solver contains the edit variable.
        */
        Solver.prototype.hasEditVariable = function (variable) {
            return this._editMap.contains(variable);
        };

        /**
        * Suggest the value of an edit variable.
        */
        Solver.prototype.suggestValue = function (variable, value) {
            var editPair = this._editMap.find(variable);
            if (editPair === undefined) {
                throw new Error("unknown edit variable");
            }

            var rows = this._rowMap;
            var info = editPair.second;
            var delta = value - info.constant;
            info.constant = value;

            // Check first if the positive error variable is basic.
            var marker = info.tag.marker;
            var rowPair = rows.find(marker);
            if (rowPair !== undefined) {
                if (rowPair.second.add(-delta) < 0.0) {
                    this._infeasibleRows.push(marker);
                }
                this._dualOptimize();
                return;
            }

            // Check next if the negative error variable is basic.
            var other = info.tag.other;
            var rowPair = rows.find(other);
            if (rowPair !== undefined) {
                if (rowPair.second.add(delta) < 0.0) {
                    this._infeasibleRows.push(other);
                }
                this._dualOptimize();
                return;
            }

            for (var i = 0, n = rows.size(); i < n; ++i) {
                var rowPair = rows.itemAt(i);
                var row = rowPair.second;
                var coeff = row.coefficientFor(marker);
                if (coeff !== 0.0 && row.add(delta * coeff) < 0.0 && rowPair.first.type() !== 1 /* External */) {
                    this._infeasibleRows.push(rowPair.first);
                }
            }
            this._dualOptimize();
        };

        /**
        * Update the values of the variables.
        */
        Solver.prototype.updateVariables = function () {
            var vars = this._varMap;
            var rows = this._rowMap;
            for (var i = 0, n = vars.size(); i < n; ++i) {
                var pair = vars.itemAt(i);
                var rowPair = rows.find(pair.second);
                if (rowPair !== undefined) {
                    pair.first.setValue(rowPair.second.constant());
                } else {
                    pair.first.setValue(0.0);
                }
            }
        };

        /**
        * Get the symbol for the given variable.
        *
        * If a symbol does not exist for the variable, one will be created.
        */
        Solver.prototype._getVarSymbol = function (variable) {
            var _this = this;
            var factory = function () {
                return _this._makeSymbol(1 /* External */);
            };
            return this._varMap.setDefault(variable, factory).second;
        };

        /**
        * Create a new Row object for the given constraint.
        *
        * The terms in the constraint will be converted to cells in the row.
        * Any term in the constraint with a coefficient of zero is ignored.
        * This method uses the `_getVarSymbol` method to get the symbol for
        * the variables added to the row. If the symbol for a given cell
        * variable is basic, the cell variable will be substituted with the
        * basic row.
        *
        * The necessary slack and error variables will be added to the row.
        * If the constant for the row is negative, the sign for the row
        * will be inverted so the constant becomes positive.
        *
        * Returns the created Row and the tag for tracking the constraint.
        */
        Solver.prototype._createRow = function (constraint) {
            var expr = constraint.expression();
            var row = new Row(expr.constant());

            // Substitute the current basic variables into the row.
            var terms = expr.terms();
            for (var i = 0, n = terms.size(); i < n; ++i) {
                var termPair = terms.itemAt(i);
                if (!nearZero(termPair.second)) {
                    var symbol = this._getVarSymbol(termPair.first);
                    var basicPair = this._rowMap.find(symbol);
                    if (basicPair !== undefined) {
                        row.insertRow(basicPair.second, termPair.second);
                    } else {
                        row.insertSymbol(symbol, termPair.second);
                    }
                }
            }

            // Add the necessary slack, error, and dummy variables.
            var objective = this._objective;
            var strength = constraint.strength();
            var tag = { marker: INVALID_SYMBOL, other: INVALID_SYMBOL };
            switch (constraint.op()) {
                case 0 /* Le */:
                case 1 /* Ge */: {
                    var coeff = constraint.op() === 0 /* Le */ ? 1.0 : -1.0;
                    var slack = this._makeSymbol(2 /* Slack */);
                    tag.marker = slack;
                    row.insertSymbol(slack, coeff);
                    if (strength < kiwi.Strength.required) {
                        var error = this._makeSymbol(3 /* Error */);
                        tag.other = error;
                        row.insertSymbol(error, -coeff);
                        objective.insertSymbol(error, strength);
                    }
                    break;
                }
                case 2 /* Eq */: {
                    if (strength < kiwi.Strength.required) {
                        var errplus = this._makeSymbol(3 /* Error */);
                        var errminus = this._makeSymbol(3 /* Error */);
                        tag.marker = errplus;
                        tag.other = errminus;
                        row.insertSymbol(errplus, -1.0); // v = eplus - eminus
                        row.insertSymbol(errminus, 1.0); // v - eplus + eminus = 0
                        objective.insertSymbol(errplus, strength);
                        objective.insertSymbol(errminus, strength);
                    } else {
                        var dummy = this._makeSymbol(4 /* Dummy */);
                        tag.marker = dummy;
                        row.insertSymbol(dummy);
                    }
                    break;
                }
            }

            // Ensure the row has a positive constant.
            if (row.constant() < 0.0) {
                row.reverseSign();
            }

            return { row: row, tag: tag };
        };

        /**
        * Choose the subject for solving for the row.
        *
        * This method will choose the best subject for using as the solve
        * target for the row. An invalid symbol will be returned if there
        * is no valid target.
        *
        * The symbols are chosen according to the following precedence:
        *
        * 1) The first symbol representing an external variable.
        * 2) A negative slack or error tag variable.
        *
        * If a subject cannot be found, an invalid symbol will be returned.
        */
        Solver.prototype._chooseSubject = function (row, tag) {
            var cells = row.cells();
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                if (pair.first.type() === 1 /* External */) {
                    return pair.first;
                }
            }
            var type = tag.marker.type();
            if (type === 2 /* Slack */ || type === 3 /* Error */) {
                if (row.coefficientFor(tag.marker) < 0.0) {
                    return tag.marker;
                }
            }
            type = tag.other.type();
            if (type === 2 /* Slack */ || type === 3 /* Error */) {
                if (row.coefficientFor(tag.other) < 0.0) {
                    return tag.other;
                }
            }
            return INVALID_SYMBOL;
        };

        /**
        * Add the row to the tableau using an artificial variable.
        *
        * This will return false if the constraint cannot be satisfied.
        */
        Solver.prototype._addWithArtificialVariable = function (row) {
            // Create and add the artificial variable to the tableau.
            var art = this._makeSymbol(2 /* Slack */);
            this._rowMap.insert(art, row.copy());
            this._artificial = row.copy();

            // Optimize the artificial objective. This is successful
            // only if the artificial objective is optimized to zero.
            this._optimize(this._artificial);
            var success = nearZero(this._artificial.constant());
            this._artificial = null;

            // If the artificial variable is basic, pivot the row so that
            // it becomes non-basic. If the row is constant, exit early.
            var pair = this._rowMap.erase(art);
            if (pair !== undefined) {
                var basicRow = pair.second;
                if (basicRow.isConstant()) {
                    return success;
                }
                var entering = this._anyPivotableSymbol(basicRow);
                if (entering.type() === 0 /* Invalid */) {
                    return false;
                }
                basicRow.solveForEx(art, entering);
                this._substitute(entering, basicRow);
                this._rowMap.insert(entering, basicRow);
            }

            // Remove the artificial variable from the tableau.
            var rows = this._rowMap;
            for (var i = 0, n = rows.size(); i < n; ++i) {
                rows.itemAt(i).second.removeSymbol(art);
            }
            this._objective.removeSymbol(art);
            return success;
        };

        /**
        * Substitute the parametric symbol with the given row.
        *
        * This method will substitute all instances of the parametric symbol
        * in the tableau and the objective function with the given row.
        */
        Solver.prototype._substitute = function (symbol, row) {
            var rows = this._rowMap;
            for (var i = 0, n = rows.size(); i < n; ++i) {
                var pair = rows.itemAt(i);
                pair.second.substitute(symbol, row);
                if (pair.second.constant() < 0.0 && pair.first.type() !== 1 /* External */) {
                    this._infeasibleRows.push(pair.first);
                }
            }
            this._objective.substitute(symbol, row);
            if (this._artificial) {
                this._artificial.substitute(symbol, row);
            }
        };

        /**
        * Optimize the system for the given objective function.
        *
        * This method performs iterations of Phase 2 of the simplex method
        * until the objective function reaches a minimum.
        */
        Solver.prototype._optimize = function (objective) {
            while (true) {
                var entering = this._getEnteringSymbol(objective);
                if (entering.type() === 0 /* Invalid */) {
                    return;
                }
                var leaving = this._getLeavingSymbol(entering);
                if (leaving.type() === 0 /* Invalid */) {
                    throw new Error("the objective is unbounded");
                }

                // pivot the entering symbol into the basis
                var row = this._rowMap.erase(leaving).second;
                row.solveForEx(leaving, entering);
                this._substitute(entering, row);
                this._rowMap.insert(entering, row);
            }
        };

        /**
        * Optimize the system using the dual of the simplex method.
        *
        * The current state of the system should be such that the objective
        * function is optimal, but not feasible. This method will perform
        * an iteration of the dual simplex method to make the solution both
        * optimal and feasible.
        */
        Solver.prototype._dualOptimize = function () {
            var rows = this._rowMap;
            var infeasible = this._infeasibleRows;
            while (infeasible.length !== 0) {
                var leaving = infeasible.pop();
                var pair = rows.find(leaving);
                if (pair !== undefined && pair.second.constant() < 0.0) {
                    var entering = this._getDualEnteringSymbol(pair.second);
                    if (entering.type() === 0 /* Invalid */) {
                        throw new Error("dual optimize failed");
                    }

                    // pivot the entering symbol into the basis
                    var row = pair.second;
                    rows.erase(leaving);
                    row.solveForEx(leaving, entering);
                    this._substitute(entering, row);
                    rows.insert(entering, row);
                }
            }
        };

        /**
        * Compute the entering variable for a pivot operation.
        *
        * This method will return first symbol in the objective function which
        * is non-dummy and has a coefficient less than zero. If no symbol meets
        * the criteria, it means the objective function is at a minimum, and an
        * invalid symbol is returned.
        */
        Solver.prototype._getEnteringSymbol = function (objective) {
            var cells = objective.cells();
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                var symbol = pair.first;
                if (pair.second < 0.0 && symbol.type() !== 4 /* Dummy */) {
                    return symbol;
                }
            }
            return INVALID_SYMBOL;
        };

        /**
        * Compute the entering symbol for the dual optimize operation.
        *
        * This method will return the symbol in the row which has a positive
        * coefficient and yields the minimum ratio for its respective symbol
        * in the objective function. The provided row *must* be infeasible.
        * If no symbol is found which meats the criteria, an invalid symbol
        * is returned.
        */
        Solver.prototype._getDualEnteringSymbol = function (row) {
            var ratio = Number.MAX_VALUE;
            var entering = INVALID_SYMBOL;
            var cells = row.cells();
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                var symbol = pair.first;
                var c = pair.second;
                if (c > 0.0 && symbol.type() !== 4 /* Dummy */) {
                    var coeff = this._objective.coefficientFor(symbol);
                    var r = coeff / c;
                    if (r < ratio) {
                        ratio = r;
                        entering = symbol;
                    }
                }
            }
            return entering;
        };

        /**
        * Compute the symbol for pivot exit row.
        *
        * This method will return the symbol for the exit row in the row
        * map. If no appropriate exit symbol is found, an invalid symbol
        * will be returned. This indicates that the objective function is
        * unbounded.
        */
        Solver.prototype._getLeavingSymbol = function (entering) {
            var ratio = Number.MAX_VALUE;
            var found = INVALID_SYMBOL;
            var rows = this._rowMap;
            for (var i = 0, n = rows.size(); i < n; ++i) {
                var pair = rows.itemAt(i);
                var symbol = pair.first;
                if (symbol.type() !== 1 /* External */) {
                    var row = pair.second;
                    var temp = row.coefficientFor(entering);
                    if (temp < 0.0) {
                        var temp_ratio = -row.constant() / temp;
                        if (temp_ratio < ratio) {
                            ratio = temp_ratio;
                            found = symbol;
                        }
                    }
                }
            }
            return found;
        };

        /**
        * Compute the leaving symbol for a marker variable.
        *
        * This method will return a symbol corresponding to a basic row
        * which holds the given marker variable. The row will be chosen
        * according to the following precedence:
        *
        * 1) The row with a restricted basic varible and a negative coefficient
        *    for the marker with the smallest ratio of -constant / coefficient.
        *
        * 2) The row with a restricted basic variable and the smallest ratio
        *    of constant / coefficient.
        *
        * 3) The last unrestricted row which contains the marker.
        *
        * If the marker does not exist in any row, an invalid symbol will be
        * returned. This indicates an internal solver error since the marker
        * *should* exist somewhere in the tableau.
        */
        Solver.prototype._getMarkerLeavingSymbol = function (marker) {
            var dmax = Number.MAX_VALUE;
            var r1 = dmax;
            var r2 = dmax;
            var invalid = INVALID_SYMBOL;
            var first = invalid;
            var second = invalid;
            var third = invalid;
            var rows = this._rowMap;
            for (var i = 0, n = rows.size(); i < n; ++i) {
                var pair = rows.itemAt(i);
                var row = pair.second;
                var c = row.coefficientFor(marker);
                if (c === 0.0) {
                    continue;
                }
                var symbol = pair.first;
                if (symbol.type() === 1 /* External */) {
                    third = symbol;
                } else if (c < 0.0) {
                    var r = -row.constant() / c;
                    if (r < r1) {
                        r1 = r;
                        first = symbol;
                    }
                } else {
                    var r = row.constant() / c;
                    if (r < r2) {
                        r2 = r;
                        second = symbol;
                    }
                }
            }
            if (first !== invalid) {
                return first;
            }
            if (second !== invalid) {
                return second;
            }
            return third;
        };

        /**
        * Remove the effects of a constraint on the objective function.
        */
        Solver.prototype._removeConstraintEffects = function (cn, tag) {
            if (tag.marker.type() === 3 /* Error */) {
                this._removeMarkerEffects(tag.marker, cn.strength());
            }
            if (tag.other.type() === 3 /* Error */) {
                this._removeMarkerEffects(tag.other, cn.strength());
            }
        };

        /**
        * Remove the effects of an error marker on the objective function.
        */
        Solver.prototype._removeMarkerEffects = function (marker, strength) {
            var pair = this._rowMap.find(marker);
            if (pair !== undefined) {
                this._objective.insertRow(pair.second, -strength);
            } else {
                this._objective.insertSymbol(marker, -strength);
            }
        };

        /**
        * Get the first Slack or Error symbol in the row.
        *
        * If no such symbol is present, an invalid symbol will be returned.
        */
        Solver.prototype._anyPivotableSymbol = function (row) {
            var cells = row.cells();
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                var type = pair.first.type();
                if (type === 2 /* Slack */ || type === 3 /* Error */) {
                    return pair.first;
                }
            }
            return INVALID_SYMBOL;
        };

        /**
        * Returns a new Symbol of the given type.
        */
        Solver.prototype._makeSymbol = function (type) {
            return new Symbol(type, this._idTick++);
        };
        return Solver;
    })();
    kiwi.Solver = Solver;

    /**
    * Test whether a value is approximately zero.
    */
    function nearZero(value) {
        var eps = 1.0e-8;
        return value < 0.0 ? -value < eps : value < eps;
    }







    /**
    * An internal function for creating a constraint map.
    */
    function createCnMap() {
        return kiwi.createMap(kiwi.Constraint.Compare);
    }

    /**
    * An internal function for creating a row map.
    */
    function createRowMap() {
        return kiwi.createMap(Symbol.Compare);
    }

    /**
    * An internal function for creating a variable map.
    */
    function createVarMap() {
        return kiwi.createMap(kiwi.Variable.Compare);
    }

    /**
    * An internal function for creating an edit map.
    */
    function createEditMap() {
        return kiwi.createMap(kiwi.Variable.Compare);
    }

    /**
    * An enum defining the available symbol types.
    */
    var SymbolType;
    (function (SymbolType) {
        SymbolType[SymbolType["Invalid"] = 0] = "Invalid";
        SymbolType[SymbolType["External"] = 1] = "External";
        SymbolType[SymbolType["Slack"] = 2] = "Slack";
        SymbolType[SymbolType["Error"] = 3] = "Error";
        SymbolType[SymbolType["Dummy"] = 4] = "Dummy";
    })(SymbolType || (SymbolType = {}));

    /**
    * An internal class representing a symbol in the solver.
    */
    var Symbol = (function () {
        /**
        * Construct a new Symbol
        *
        * @param [type] The type of the symbol.
        * @param [id] The unique id number of the symbol.
        */
        function Symbol(type, id) {
            this._id = id;
            this._type = type;
        }
        /**
        * The static Symbol comparison function.
        */
        Symbol.Compare = function (a, b) {
            return a.id() - b.id();
        };

        /**
        * Returns the unique id number of the symbol.
        */
        Symbol.prototype.id = function () {
            return this._id;
        };

        /**
        * Returns the type of the symbol.
        */
        Symbol.prototype.type = function () {
            return this._type;
        };
        return Symbol;
    })();

    /**
    * A static invalid symbol
    */
    var INVALID_SYMBOL = new Symbol(0 /* Invalid */, -1);

    /**
    * An internal row class used by the solver.
    */
    var Row = (function () {
        /**
        * Construct a new Row.
        */
        function Row(constant) {
            if (typeof constant === "undefined") { constant = 0.0; }
            this._cellMap = kiwi.createMap(Symbol.Compare);
            this._constant = constant;
        }
        /**
        * Returns the mapping of symbols to coefficients.
        */
        Row.prototype.cells = function () {
            return this._cellMap;
        };

        /**
        * Returns the constant for the row.
        */
        Row.prototype.constant = function () {
            return this._constant;
        };

        /**
        * Returns true if the row is a constant value.
        */
        Row.prototype.isConstant = function () {
            return this._cellMap.empty();
        };

        /**
        * Returns true if the Row has all dummy symbols.
        */
        Row.prototype.allDummies = function () {
            var cells = this._cellMap;
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                if (pair.first.type() !== 4 /* Dummy */) {
                    return false;
                }
            }
            return true;
        };

        /**
        * Create a copy of the row.
        */
        Row.prototype.copy = function () {
            var theCopy = new Row(this._constant);
            theCopy._cellMap = this._cellMap.copy();
            return theCopy;
        };

        /**
        * Add a constant value to the row constant.
        *
        * Returns the new value of the constant.
        */
        Row.prototype.add = function (value) {
            return this._constant += value;
        };

        /**
        * Insert the symbol into the row with the given coefficient.
        *
        * If the symbol already exists in the row, the coefficient
        * will be added to the existing coefficient. If the resulting
        * coefficient is zero, the symbol will be removed from the row.
        */
        Row.prototype.insertSymbol = function (symbol, coefficient) {
            if (typeof coefficient === "undefined") { coefficient = 1.0; }
            var pair = this._cellMap.setDefault(symbol, function () {
                return 0.0;
            });
            if (nearZero(pair.second += coefficient)) {
                this._cellMap.erase(symbol);
            }
        };

        /**
        * Insert a row into this row with a given coefficient.
        *
        * The constant and the cells of the other row will be
        * multiplied by the coefficient and added to this row. Any
        * cell with a resulting coefficient of zero will be removed
        * from the row.
        */
        Row.prototype.insertRow = function (other, coefficient) {
            if (typeof coefficient === "undefined") { coefficient = 1.0; }
            this._constant += other._constant * coefficient;
            var cells = other._cellMap;
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                this.insertSymbol(pair.first, pair.second * coefficient);
            }
        };

        /**
        * Remove a symbol from the row.
        */
        Row.prototype.removeSymbol = function (symbol) {
            this._cellMap.erase(symbol);
        };

        /**
        * Reverse the sign of the constant and cells in the row.
        */
        Row.prototype.reverseSign = function () {
            this._constant = -this._constant;
            var cells = this._cellMap;
            for (var i = 0, n = cells.size(); i < n; ++i) {
                var pair = cells.itemAt(i);
                pair.second = -pair.second;
            }
        };

        /**
        * Solve the row for the given symbol.
        *
        * This method assumes the row is of the form
        * a * x + b * y + c = 0 and (assuming solve for x) will modify
        * the row to represent the right hand side of
        * x = -b/a * y - c / a. The target symbol will be removed from
        * the row, and the constant and other cells will be multiplied
        * by the negative inverse of the target coefficient.
        *
        * The given symbol *must* exist in the row.
        */
        Row.prototype.solveFor = function (symbol) {
            var cells = this._cellMap;
            var pair = cells.erase(symbol);
            var coeff = -1.0 / pair.second;
            this._constant *= coeff;
            for (var i = 0, n = cells.size(); i < n; ++i) {
                cells.itemAt(i).second *= coeff;
            }
        };

        /**
        * Solve the row for the given symbols.
        *
        * This method assumes the row is of the form
        * x = b * y + c and will solve the row such that
        * y = x / b - c / b. The rhs symbol will be removed from the
        * row, the lhs added, and the result divided by the negative
        * inverse of the rhs coefficient.
        *
        * The lhs symbol *must not* exist in the row, and the rhs
        * symbol must* exist in the row.
        */
        Row.prototype.solveForEx = function (lhs, rhs) {
            this.insertSymbol(lhs, -1.0);
            this.solveFor(rhs);
        };

        /**
        * Returns the coefficient for the given symbol.
        */
        Row.prototype.coefficientFor = function (symbol) {
            var pair = this._cellMap.find(symbol);
            return pair !== undefined ? pair.second : 0.0;
        };

        /**
        * Substitute a symbol with the data from another row.
        *
        * Given a row of the form a * x + b and a substitution of the
        * form x = 3 * y + c the row will be updated to reflect the
        * expression 3 * a * y + a * c + b.
        *
        * If the symbol does not exist in the row, this is a no-op.
        */
        Row.prototype.substitute = function (symbol, row) {
            var pair = this._cellMap.erase(symbol);
            if (pair !== undefined) {
                this.insertRow(row, pair.second);
            }
        };
        return Row;
    })();
})(kiwi || (kiwi = {}));
/*-----------------------------------------------------------------------------
| Copyright (c) 2014, Nucleic Development Team.
|
| Distributed under the terms of the Modified BSD License.
|
| The full license is in the file COPYING.txt, distributed with this software.
|----------------------------------------------------------------------------*/
/// <reference path="constraint.ts"/>
/// <reference path="expression.ts"/>
/// <reference path="maptype.ts"/>
/// <reference path="solver.ts"/>
/// <reference path="strength.ts"/>
/// <reference path="variable.ts"/>

module.exports = kiwi

},{}]},{},["main"])

 })()/*
Copyright (c) 2012, Continuum Analytics, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

Neither the name of Continuum Analytics nor the names of any contributors
may be used to endorse or promote products derived from this software 
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
THE POSSIBILITY OF SUCH DAMAGE.
*/

//# sourceMappingURL=bokeh.js.map
