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;
})
({"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("./models/index");

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
};

},{"./core/logging":"core/logging","./core/util/underscore":"core/util/underscore","./models/index":"models/index","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, 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, 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, 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;
    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;
    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;
      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"}],"core/backbone":[function(require,module,exports){
//     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

var _ = require('underscore');
var $ = require('jquery');

var Events = require('./events').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.
var Model = function(attributes, options) {
  var attrs = attributes || {};
  options || (options = {});
  this.attributes = {};
  this.setv(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,

  // Initialize is an empty function by default. Override it with your own
  // initialization logic.
  initialize: function(){},

  // Get the value of an attribute.
  getv: function(attr) {
    return this.attributes[attr];
  },

  // 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.
  setv: 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 = {});

    // Extract attributes and options.
    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];
      }
      current[attr] = val;
    }

    // Trigger all relevant attribute changes.
    if (!silent) {
      if (changes.length) this._pending = true;
      for (var i = 0; i < changes.length; i++) {
        this.trigger('change:' + changes[i], this, current[changes[i]]);
      }
    }

    // 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) {
        this._pending = false;
        this.trigger('change', this);
      }
    }
    this._pending = false;
    this._changing = false;
    return this;
  },

  destroy: function() {
    this.stopListening();
    this.trigger('destroy', this);
  },

  // Create a new model with identical attributes to this one.
  clone: function() {
    return new this.constructor(this.attributes);
  }
});

// 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 = function(options) {
  _.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', '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 $ ? el : $(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.id, 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.id);
    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.id, 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);
  }

});

Model.getter = View.getter = function(name, get) {
  Object.defineProperty(this.prototype, name, { get: get });
};

Model.getters = View.getters = function(specs) {
  for (var name in specs) {
    this.getter(name, specs[name]);
  }
};

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

},{"./events":"core/events","jquery":"jquery","underscore":"underscore"}],"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.toString = function() {
    return this.model.type + ".View(" + this.id + ")";
  };

  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);
  };

  return BokehView;

})(Backbone.View);

module.exports = BokehView;

},{"./backbone":"core/backbone","underscore":"underscore"}],"core/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"}],"core/enums":[function(require,module,exports){
module.exports = {
  AngleUnits: ["deg", "rad"],
  Dimension: ["width", "height"],
  Dimensions: ["width", "height", "both"],
  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"],
  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/events":[function(require,module,exports){
//     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

var _ = require('underscore');

// 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 = {};

// 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;
  }
};

module.exports = {
  Events: Events
};

},{"underscore":"underscore"}],"core/has_props":[function(require,module,exports){
var $, Backbone, HasProps, _, array_max, logger, p, 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");

p = require("./properties");

array_max = require("./util/math").array_max;

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) {
            throw new Error("attempted to redefine attribute '" + _this.name + "." + name + "'");
          }
          Object.defineProperty(_this.prototype, name, {
            get: function() {
              return this.getv(name);
            },
            set: function(value) {
              return this.setv(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.define({
    id: [p.Any]
  });

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

  function HasProps(attributes, options) {
    var attrs, default_value, name, ref, ref1, type;
    this.document = null;
    attrs = attributes || {};
    if (!options) {
      options = {};
    }
    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
      });
    }
    this._set_after_defaults = {};
    this.setv(attrs, options);
    this.changed = {};
    this._computed = {};
    if (attrs.id == null) {
      this.id = _.uniqueId(this.type);
    }
    if (!options.defer_initialization) {
      this.initialize.apply(this, arguments);
    }
  }

  HasProps.prototype.setv = 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 (this.props[prop_name] == null) {
        throw new Error("property " + this.type + "." + 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.getv(key);
      }
      HasProps.__super__.setv.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.getv(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_computed(prop_name);
          firechange = new_val !== old_val;
        }
        if (firechange) {
          _this.trigger('change:' + prop_name, _this, _this._get_computed(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.set = function(key, value, options) {
    logger.warn("HasProps.set('prop_name', value) is deprecated, use HasProps.prop_name = value instead");
    return this.setv(key, value, options);
  };

  HasProps.prototype.get = function(prop_name) {
    logger.warn("HasProps.get('prop_name') is deprecated, use HasProps.prop_name instead");
    return this.getv(prop_name);
  };

  HasProps.prototype.getv = function(prop_name) {
    if (this.props[prop_name] == null) {
      throw new Error("property " + this.type + "." + prop_name + " wasn't declared");
    } else {
      return HasProps.__super__.getv.call(this, prop_name);
    }
  };

  HasProps.prototype._get_computed = function(prop_name) {
    var computed, getter, prop_spec;
    prop_spec = this._computed[prop_name];
    if (prop_spec == null) {
      throw new Error("computed property " + this.type + "." + prop_name + " wasn't declared");
    }
    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.attribute_is_serializable = function(attr) {
    var prop;
    prop = this.props[attr];
    if (prop == null) {
      throw new Error(this.type + ".attribute_is_serializable('" + attr + "'): " + attr + " wasn't declared");
    } else {
      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._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_);
    }
  };

  HasProps.prototype.materialize_dataspecs = function(source) {
    var data, name, prop, ref;
    data = {};
    ref = this.properties;
    for (name in ref) {
      prop = ref[name];
      if (!prop.dataspec) {
        continue;
      }
      if ((prop.optional || false) && prop.spec.value === null && (!(name in this._set_after_defaults))) {
        continue;
      }
      data["_" + name] = prop.array(source);
      if (prop instanceof p.Distance) {
        data["max_" + name] = array_max(data["_" + name]);
      }
    }
    return data;
  };

  return HasProps;

})(Backbone.Model);

module.exports = HasProps;

},{"./backbone":"core/backbone","./logging":"core/logging","./properties":"core/properties","./property_mixins":"core/property_mixins","./util/math":"core/util/math","./util/refs":"core/util/refs","jquery":"jquery","underscore":"underscore"}],"core/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'] = {};
  }

  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;
  };

  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
};

},{}],"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);
    return this._bottom = new Variable("bottom " + this.id);
  };

  LayoutCanvas.getters({
    height: function() {
      return this._height.value();
    },
    width: function() {
      return this._width.value();
    },
    right: function() {
      return this._right.value();
    },
    left: function() {
      return this._left.value();
    },
    top: function() {
      return this._top.value();
    },
    bottom: function() {
      return this._bottom.value();
    }
  });

  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 [];
  };

  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.model.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.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) {
    SidePanel.__super__.initialize.call(this, attrs, options);
    switch (this.side) {
      case "above":
        this._dim = 0;
        this._normals = [0, -1];
        this._size = this._height;
        return this._anchor = this._bottom;
      case "below":
        this._dim = 0;
        this._normals = [0, 1];
        this._size = this._height;
        return this._anchor = this._top;
      case "left":
        this._dim = 1;
        this._normals = [-1, 0];
        this._size = this._width;
        return this._anchor = this._right;
      case "right":
        this._dim = 1;
        this._normals = [1, 0];
        this._size = this._width;
        return this._anchor = this._left;
      default:
        return logger.error("unrecognized side: '" + this.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.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.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 Constraint, Events, Expression, Operator, Solver, Strength, Variable, _, _constrainer, _weak_constrainer, kiwi;

_ = require("underscore");

kiwi = require("kiwi");

Events = require("../events").Events;

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() {
  _.extend(Solver.prototype, Events);

  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;

})();

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
};

},{"../events":"core/events","kiwi":"kiwi","underscore":"underscore"}],"core/logging":[function(require,module,exports){
var LogLevel, Logger, _, _loggers, _method_factory, logger, noop, set_log_level,
  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');

noop = function() {};

_method_factory = function(method_name, logger_name) {
  if (console[method_name] != null) {
    return console[method_name].bind(console, logger_name);
  } else if (console.log != null) {
    return console.log.bind(console, logger_name);
  } else {
    return noop;
  }
};

_loggers = {};

LogLevel = (function() {
  function LogLevel(name, level) {
    this.name = name;
    this.level = level;
  }

  return LogLevel;

})();

Logger = (function() {
  Logger.TRACE = new LogLevel("trace", 0);

  Logger.DEBUG = new LogLevel("debug", 1);

  Logger.INFO = new LogLevel("info", 2);

  Logger.WARN = new LogLevel("warn", 6);

  Logger.ERROR = new LogLevel("error", 7);

  Logger.FATAL = new LogLevel("fatal", 8);

  Logger.OFF = new LogLevel("off", 9);

  Logger.log_levels = {
    trace: Logger.TRACE,
    debug: Logger.DEBUG,
    info: Logger.INFO,
    warn: Logger.WARN,
    error: Logger.ERROR,
    fatal: Logger.FATAL,
    off: Logger.OFF
  };

  Object.defineProperty(Logger, 'levels', {
    get: function() {
      return Object.keys(Logger.log_levels);
    }
  });

  Logger.get = function(name, level) {
    var logger;
    if (level == null) {
      level = Logger.INFO;
    }
    if (_.isString(name) && name.length > 0) {
      logger = _loggers[name];
      if (logger == null) {
        logger = _loggers[name] = new Logger(name, level);
      }
      return logger;
    } else {
      throw new TypeError("Logger.get() expects a string name and an optional log-level");
    }
  };

  function Logger(name, level) {
    if (level == null) {
      level = Logger.INFO;
    }
    this._name = name;
    this.set_level(level);
  }

  Object.defineProperty(Logger.prototype, 'level', {
    get: function() {
      return this.get_level();
    }
  });

  Logger.prototype.get_level = function() {
    return this._log_level;
  };

  Logger.prototype.set_level = function(log_level) {
    var __, logger_name, method_name, ref, results;
    if (log_level instanceof LogLevel) {
      this._log_level = log_level;
    } else if (_.isString(log_level) && (Logger.log_levels[log_level] != null)) {
      this._log_level = Logger.log_levels[log_level];
    } else {
      throw new Error("Logger.set_level() expects a log-level object or a string name of a log-level");
    }
    logger_name = "[" + this._name + "]";
    ref = Logger.log_levels;
    results = [];
    for (__ in ref) {
      log_level = ref[__];
      if (log_level === Logger.OFF) {
        break;
      } else {
        method_name = log_level.name;
        if (log_level.level < this._log_level.level) {
          results.push(this[method_name] = noop);
        } else {
          results.push(this[method_name] = _method_factory(method_name, logger_name));
        }
      }
    }
    return results;
  };

  return Logger;

})();

logger = Logger.get("bokeh");

set_log_level = function(level) {
  if (indexOf.call(Logger.levels, level) < 0) {
    console.log("[bokeh] unrecognized logging level '" + level + "' passed to Bokeh.set_log_level(), ignoring");
    return console.log("[bokeh] valid log levels are: " + (Logger.levels.join(', ')));
  } else {
    console.log("[bokeh] setting log level to: '" + level + "'");
    return logger.set_level(level);
  }
};

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

},{"underscore":"underscore"}],"core/properties":[function(require,module,exports){
var Anchor, Angle, AngleSpec, AngleUnits, Any, Array, Bool, Color, ColorSpec, Dimension, Dimensions, Direction, DirectionSpec, Distance, DistanceSpec, Distribution, Events, Font, FontSizeSpec, FontStyle, Instance, LegendLocation, LineCap, LineJoin, Location, Number, NumberSpec, Orientation, Percent, 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");

Events = require("./events").Events;

enums = require("./enums");

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

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

Property = (function() {
  _.extend(Property.prototype, Events);

  Property.prototype.dataspec = false;

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

  function Property(arg) {
    this.obj = arg.obj, this.attr = arg.attr, this.default_value = arg.default_value;
    this._init(false);
    this.listenTo(this.obj, "change:" + this.attr, (function(_this) {
      return function() {
        _this._init();
        return _this.obj.trigger("propchange");
      };
    })(this));
  }

  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.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.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.attr;
    if (attr == null) {
      throw new Error("missing property attr");
    }
    attr_value = obj.getv(attr);
    if (_.isUndefined(attr_value)) {
      default_value = this.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.setv(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;

})();

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.obj.id + ", spec: " + (JSON.stringify(this.spec)) + ")";
    };

    Prop.prototype.validate = function(value) {
      if (!pred(value)) {
        throw new Error(name + " property '" + this.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);
}));

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

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

  return Percent;

})(simple_prop("Number", function(x) {
  return (_.isNumber(x) || _.isBoolean(x)) && ((0 <= x && x <= 1.0));
}));

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.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));

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

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

  return Dimensions;

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

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.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,
  Dimensions: Dimensions,
  Direction: Direction,
  Distance: Distance,
  Font: Font,
  FontStyle: FontStyle,
  Instance: Instance,
  LegendLocation: LegendLocation,
  LineCap: LineCap,
  LineJoin: LineJoin,
  Location: Location,
  Number: Number,
  Percent: Percent,
  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","./events":"core/events","./util/color":"core/util/color","./util/svg_colors":"core/util/svg_colors","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/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("./has_props");

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

Selector = require("./selector");

hittest = require("./hittest");

p = require("./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.source;
    if (source !== renderer_view.model.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.source.selected = selector.indices;
      source.trigger('select');
      source.trigger('select-' + renderer_view.model.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.source;
    if (source !== renderer_view.model.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.source.setv({
        inspected: inspector.indices
      }, {
        "silent": true
      });
      source.trigger('inspect', indices, tool, renderer_view, source, data);
      source.trigger("inspect" + renderer_view.model.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.source.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;

},{"./has_props":"core/has_props","./hittest":"core/hittest","./logging":"core/logging","./properties":"core/properties","./selector":"core/selector","underscore":"underscore"}],"core/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("./has_props");

hittest = require("./hittest");

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

p = require("./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.setv('timestamp', new Date(), {
      silent: silent
    });
    this.setv('final', final, {
      silent: silent
    });
    if (append) {
      indices['0d'].indices = _.union(this.indices['0d'].indices, indices['0d'].indices);
      indices['0d'].glyph = this.indices['0d'].glyph || indices['0d'].glyph;
      indices['1d'].indices = _.union(this.indices['1d'].indices, indices['1d'].indices);
      indices['2d'].indices = _.union(this.indices['2d'].indices, indices['2d'].indices);
    }
    return this.setv('indices', indices, {
      silent: silent
    });
  };

  Selector.prototype.clear = function() {
    this.timestamp = new Date();
    this.final = true;
    return this.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;

},{"./has_props":"core/has_props","./hittest":"core/hittest","./logging":"core/logging","./properties":"core/properties","underscore":"underscore"}],"core/ui_events":[function(require,module,exports){
var $, Events, Hammer, UIEvents, _, logger, mousewheel;

_ = require("underscore");

$ = require("jquery");

Hammer = require("hammerjs");

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

Events = require("./events").Events;

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

UIEvents = (function() {
  _.extend(UIEvents.prototype, Events);

  function UIEvents(toolbar, hit_area) {
    this.toolbar = toolbar;
    this.hit_area = hit_area;
    this._configure_hammerjs();
  }

  UIEvents.prototype._configure_hammerjs = function() {
    this.hammer = new Hammer(this.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));
    this.hit_area.mousemove((function(_this) {
      return function(e) {
        return _this._mouse_move(e);
      };
    })(this));
    this.hit_area.mouseenter((function(_this) {
      return function(e) {
        return _this._mouse_enter(e);
      };
    })(this));
    this.hit_area.mouseleave((function(_this) {
      return function(e) {
        return _this._mouse_exit(e);
      };
    })(this));
    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;
    base_event_type = event_type.split(":")[0];
    if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
      if (event_type === 'scroll') {
        base_event_type = 'pinch';
      }
    }
    gestures = this.toolbar.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.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;

})();

module.exports = {
  UIEvents: UIEvents
};

},{"./events":"core/events","./logging":"core/logging","hammerjs":"hammerjs","jquery":"jquery","jquery-mousewheel":"jquery-mousewheel","underscore":"underscore"}],"core/util/bbox":[function(require,module,exports){
var empty, union;

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

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 = 2e308;
  while (len--) {
    val = arr[len];
    if (val < min) {
      min = val;
    }
  }
  return min;
};

array_max = function(arr) {
  var len, max, val;
  len = arr.length;
  max = -2e308;
  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/proj4":[function(require,module,exports){
var proj4;

module.exports = proj4 = require('proj4/lib/core');

proj4.defaultDatum = 'WGS84';

proj4.Proj = require('proj4/lib/Proj');

proj4.WGS84 = new proj4.Proj('WGS84');

proj4.toPoint = require('proj4/lib/common/toPoint');

proj4.defs = require('proj4/lib/defs');

proj4.transform = require('proj4/lib/transform');


/*
projs = [
  require('proj4/lib/projections/tmerc')
  require('proj4/lib/projections/utm')
  require('proj4/lib/projections/sterea')
  require('proj4/lib/projections/stere')
  require('proj4/lib/projections/somerc')
  require('proj4/lib/projections/omerc')
  require('proj4/lib/projections/lcc')
  require('proj4/lib/projections/krovak')
  require('proj4/lib/projections/cass')
  require('proj4/lib/projections/laea')
  require('proj4/lib/projections/aea')
  require('proj4/lib/projections/gnom')
  require('proj4/lib/projections/cea')
  require('proj4/lib/projections/eqc')
  require('proj4/lib/projections/poly')
  require('proj4/lib/projections/nzmg')
  require('proj4/lib/projections/mill')
  require('proj4/lib/projections/sinu')
  require('proj4/lib/projections/moll')
  require('proj4/lib/projections/eqdc')
  require('proj4/lib/projections/vandg')
  require('proj4/lib/projections/aeqd')
]

for proj in projs
  proj4.Proj.projections.add(proj)
 */

},{"proj4/lib/Proj":"proj4/lib/Proj","proj4/lib/common/toPoint":"proj4/lib/common/toPoint","proj4/lib/core":"proj4/lib/core","proj4/lib/defs":"proj4/lib/defs","proj4/lib/transform":"proj4/lib/transform"}],"core/util/projections":[function(require,module,exports){
var proj4, project_xsys, project_xy, toProjection;

proj4 = require("./proj4");

toProjection = proj4.defs('GOOGLE');

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];
};

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 = 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];
};

module.exports = {
  project_xy: project_xy,
  project_xsys: project_xsys
};

},{"./proj4":"core/util/proj4"}],"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/selection":[function(require,module,exports){
var get_indices;

get_indices = function(data_source) {
  var selected;
  selected = data_source.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 = {
  get_indices: get_indices
};

},{}],"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/templating":[function(require,module,exports){
var Numbro, SPrintf, _, _format_number, 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;
};

module.exports = {
  replace_placeholders: replace_placeholders
};

},{"numbro":"numbro","sprintf":"sprintf","underscore":"underscore"}],"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"}],"core/util/zoom":[function(require,module,exports){
var scale_range;

scale_range = function(frame, factor, h_axis, v_axis, center) {
  var end, hr, mapper, name, ref, ref1, ref2, ref3, ref4, ref5, start, sx0, sx1, sy0, sy1, vr, vx, vx_high, vx_low, vy, vy_high, vy_low, xrs, yrs, zoom_info;
  if (h_axis == null) {
    h_axis = true;
  }
  if (v_axis == null) {
    v_axis = true;
  }
  if (center == null) {
    center = null;
  }
  "Utility function for zoom tools to calculate/create the zoom_info object\nof the form required by ``PlotCanvasView.update_range``\n\nParameters:\n  frame : CartesianFrame\n  factor : Number\n  center : object, optional\n    of form {'x': Number, 'y', Number}\n  h_axis : Boolean, optional\n    whether to zoom the horizontal axis (default = true)\n  v_axis : Boolean, optional\n    whether to zoom the horizontal axis (default = true)\n\nReturns:\n  object:";
  hr = frame.h_range;
  vr = frame.v_range;
  if (factor > 0.9) {
    factor = 0.9;
  } else if (factor < -0.9) {
    factor = -0.9;
  }
  ref = [hr.start, hr.end], vx_low = ref[0], vx_high = ref[1];
  ref1 = [vr.start, vr.end], vy_low = ref1[0], vy_high = ref1[1];
  vx = center != null ? center.x : (vx_high + vx_low) / 2.0;
  vy = center != null ? center.y : (vy_high + vy_low) / 2.0;
  if (h_axis) {
    sx0 = vx_low - (vx_low - vx) * factor;
    sx1 = vx_high - (vx_high - vx) * factor;
  } else {
    sx0 = vx_low;
    sx1 = vx_high;
  }
  if (v_axis) {
    sy0 = vy_low - (vy_low - vy) * factor;
    sy1 = vy_high - (vy_high - vy) * factor;
  } else {
    sy0 = vy_low;
    sy1 = vy_high;
  }
  xrs = {};
  ref2 = frame.x_mappers;
  for (name in ref2) {
    mapper = ref2[name];
    ref3 = mapper.v_map_from_target([sx0, sx1]), start = ref3[0], end = ref3[1];
    xrs[name] = {
      start: start,
      end: end
    };
  }
  yrs = {};
  ref4 = frame.y_mappers;
  for (name in ref4) {
    mapper = ref4[name];
    ref5 = mapper.v_map_from_target([sy0, sy1]), start = ref5[0], end = ref5[1];
    yrs[name] = {
      start: start,
      end: end
    };
  }
  zoom_info = {
    xrs: xrs,
    yrs: yrs,
    factor: factor
  };
  return zoom_info;
};

module.exports = {
  scale_range: scale_range
};

},{}],"core/visuals":[function(require,module,exports){
var ContextProperties, Fill, Line, Text, Visuals, _, color2rgba, mixins,
  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");

mixins = require("./property_mixins");

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

ContextProperties = (function() {
  function ContextProperties(obj, prefix) {
    var attr, do_spec, j, len, ref;
    if (prefix == null) {
      prefix = "";
    }
    this.obj = obj;
    this.prefix = prefix;
    this.cache = {};
    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, prop, ref, results;
    ref = this.attrs;
    results = [];
    for (j = 0, len = ref.length; j < len; j++) {
      attr = ref[j];
      prop = this.obj.properties[this.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 prop;
    prop = this.obj.properties[this.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;

})();

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 = (function() {
  function Visuals(model) {
    var cls, j, len, name, prefix, ref, ref1, ref2, spec;
    ref = model.mixins;
    for (j = 0, len = ref.length; j < len; j++) {
      spec = ref[j];
      ref1 = spec.split(":"), name = ref1[0], prefix = (ref2 = ref1[1]) != null ? ref2 : "";
      cls = (function() {
        switch (name) {
          case "line":
            return Line;
          case "fill":
            return Fill;
          case "text":
            return Text;
        }
      })();
      this[prefix + name] = new cls(model, prefix);
    }
  }

  Visuals.prototype.warm_cache = function(source) {
    var name, prop, ref, results;
    ref = this;
    results = [];
    for (name in ref) {
      if (!hasProp.call(ref, name)) continue;
      prop = ref[name];
      if (prop instanceof ContextProperties) {
        results.push(prop.warm_cache(source));
      } else {
        results.push(void 0);
      }
    }
    return results;
  };

  return Visuals;

})();

module.exports = {
  Visuals: Visuals,
  Line: Line,
  Fill: Fill,
  Text: Text
};

},{"./property_mixins":"core/property_mixins","./util/color":"core/util/color","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", (function(_this) {
      return function() {
        return _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(width, height) {
    if (width == null) {
      width = null;
    }
    if (height == null) {
      height = null;
    }
    this._resize(width, height);
    return this._resize(width, height);
  };

  Document.prototype._resize = function(width, height) {
    var j, len, measuring, ref3, root, root_div, target_height, vars;
    if (width == null) {
      width = null;
    }
    if (height == null) {
      height = null;
    }
    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);
      if (_.isNull(width)) {
        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.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.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.setv(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 (py_version.indexOf('-') < 0 && js_version !== py_version) {
      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];
      switch (event_json.kind) {
        case '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.setv((
            obj1 = {},
            obj1["" + attr] = value,
            obj1
          )));
          break;
        case '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));
          break;
        case '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));
          break;
        case 'RootAdded':
          root_id = event_json['model']['id'];
          root_obj = references[root_id];
          results.push(this.add_root(root_obj));
          break;
        case 'RootRemoved':
          root_id = event_json['model']['id'];
          root_obj = references[root_id];
          results.push(this.remove_root(root_obj));
          break;
        case 'TitleChanged':
          results.push(this.set_title(event_json['title']));
          break;
        default:
          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, Document, Promise, RootAddedEvent, RootRemovedEvent, TitleChangedEvent, _, _create_view, _get_session, _handle_notebook_comms, _init_comms, _render_document_to_element, _sessions, _update_comms_callback, 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");

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);
  }
};

_update_comms_callback = function(target, doc, comm) {
  if (target === comm.target_name) {
    return comm.on_msg(_.bind(_handle_notebook_comms, doc));
  }
};

_init_comms = function(target, doc) {
  var comm_manager, e, id, promise, ref2, update_comms;
  if ((typeof Jupyter !== "undefined" && Jupyter !== null) && (Jupyter.notebook.kernel != null)) {
    logger.info("Registering Jupyter comms for target " + target);
    comm_manager = Jupyter.notebook.kernel.comm_manager;
    update_comms = _.partial(_update_comms_callback, target, doc);
    ref2 = comm_manager.comms;
    for (id in ref2) {
      promise = ref2[id];
      promise.then(update_comms);
    }
    try {
      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('Jupyter 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 child, 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);
      child = $('<div>');
      container.append(child);
      elem = child;
    }
    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","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");

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.safely = require("./safely");

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

module.exports = Bokeh;

},{"./base":"base","./core/logging":"core/logging","./embed":"embed","./safely":"safely","./version":"version","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.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.model.source == null) {
      this.model.source = new ColumnDataSource.Model();
    }
    this.canvas = this.plot_model.canvas;
    this.xmapper = this.plot_view.frame.x_mappers[this.model.x_range_name];
    this.ymapper = this.plot_view.frame.y_mappers[this.model.y_range_name];
    return this.set_data(this.model.source);
  };

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

  ArrowView.prototype.set_data = function(source) {
    ArrowView.__super__.set_data.call(this, source);
    return this.visuals.warm_cache(source);
  };

  ArrowView.prototype._map_data = function() {
    var end, start, x_name, y_name;
    if (this.model.start_units === 'data') {
      start = this.plot_view.map_to_screen(this._x_start, this._y_start, x_name = this.model.x_range_name, y_name = this.model.y_range_name);
    } else {
      start = [this.canvas.v_vx_to_sx(this._x_start), this.canvas.v_vy_to_sy(this._y_start)];
    }
    if (this.model.end_units === 'data') {
      end = this.plot_view.map_to_screen(this._x_end, this._y_end, x_name = this.model.x_range_name, y_name = this.model.y_range_name);
    } else {
      end = [this.canvas.v_vx_to_sx(this._x_end), this.canvas.v_vy_to_sy(this._y_end)];
    }
    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.model.end != null) {
      this._draw_arrow_head(this.model.end, this.start, this.end);
    }
    if (this.model.start != null) {
      return this._draw_arrow_head(this.model.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, 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;

Annotation = require("./annotation");

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

Visuals = require("../../core/visuals").Visuals;

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) {
    ArrowHead.__super__.initialize.call(this, options);
    return this.visuals = new Visuals(this);
  };

  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.size, this.size);
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.size, this.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.size, this.size);
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.size, this.size);
      ctx.closePath();
      ctx.fill();
    }
    if (this.visuals.line.doit) {
      this.visuals.line.set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.size, this.size);
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.size, this.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.size, this.size);
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.size, this.size);
      ctx.lineTo(0, 0.5 * this.size);
      ctx.closePath();
      ctx.fill();
    }
    if (this.visuals.line.doit) {
      this.visuals.line.set_vectorize(ctx, i);
      ctx.beginPath();
      ctx.moveTo(0.5 * this.size, this.size);
      ctx.lineTo(0, 0);
      ctx.lineTo(-0.5 * this.size, this.size);
      ctx.lineTo(0, 0.5 * this.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","../../core/visuals":"core/visuals","../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.model.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.model.left == null) && (this.model.right == null) && (this.model.top == null) && (this.model.bottom == null)) {
      this.$el.hide();
      return null;
    }
    this.frame = this.plot_model.frame;
    this.canvas = this.plot_model.canvas;
    this.xmapper = this.plot_view.frame.x_mappers[this.model.x_range_name];
    this.ymapper = this.plot_view.frame.y_mappers[this.model.y_range_name];
    sleft = this.canvas.vx_to_sx(this._calc_dim(this.model.left, this.model.left_units, this.xmapper, this.frame.h_range.start));
    sright = this.canvas.vx_to_sx(this._calc_dim(this.model.right, this.model.right_units, this.xmapper, this.frame.h_range.end));
    sbottom = this.canvas.vy_to_sy(this._calc_dim(this.model.bottom, this.model.bottom_units, this.ymapper, this.frame.v_range.start));
    stop = this.canvas.vy_to_sy(this._calc_dim(this.model.top, this.model.top_units, this.ymapper, this.frame.v_range.end));
    if (this.model.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.model.line_width.value;
    lc = this.model.line_color.value;
    bc = this.model.fill_color.value;
    ba = this.model.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.model.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, dim_units, mapper, frame_extrema) {
    var vdim;
    if (dim != null) {
      if (dim_units === 'data') {
        vdim = mapper.map_to_target(dim);
      } else {
        vdim = 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.setv({
      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/color_bar":[function(require,module,exports){
var Annotation, BasicTickFormatter, BasicTicker, ColorBar, ColorBarView, LONG_DIM_MAX_SCALAR, LONG_DIM_MIN_SCALAR, LinearColorMapper, LinearMapper, LogMapper, Range1d, SHORT_DIM, _, p, text_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");

Annotation = require("./annotation");

BasicTicker = require("../tickers/basic_ticker");

BasicTickFormatter = require("../formatters/basic_tick_formatter");

LinearColorMapper = require("../mappers/linear_color_mapper");

LinearMapper = require("../mappers/linear_mapper");

LogMapper = require("../mappers/log_mapper");

Range1d = require("../ranges/range1d");

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

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

SHORT_DIM = 25;

LONG_DIM_MIN_SCALAR = 0.3;

LONG_DIM_MAX_SCALAR = 0.8;

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

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

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

  ColorBarView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change:visible', this.plot_view.request_render);
    this.listenTo(this.model.ticker, 'change', this.plot_view.request_render);
    this.listenTo(this.model.formatter, 'change', this.plot_view.request_render);
    return this.listenTo(this.model.color_mapper, 'change', function() {
      this._set_canvas_image();
      return this.plot_view.request_render();
    });
  };

  ColorBarView.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
    };
  };

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

  ColorBarView.prototype._set_canvas_image = function() {
    var buf, buf8, canvas, cmap, h, image_ctx, image_data, k, palette, ref, ref1, ref2, ref3, results, w;
    palette = this.model.color_mapper.palette;
    if (this.model.orientation === 'vertical') {
      palette = palette.slice(0).reverse();
    }
    switch (this.model.orientation) {
      case "vertical":
        ref = [1, palette.length], w = ref[0], h = ref[1];
        break;
      case "horizontal":
        ref1 = [palette.length, 1], w = ref1[0], h = ref1[1];
    }
    canvas = document.createElement('canvas');
    ref2 = [w, h], canvas.width = ref2[0], canvas.height = ref2[1];
    image_ctx = canvas.getContext('2d');
    image_data = image_ctx.getImageData(0, 0, w, h);
    cmap = new LinearColorMapper.Model({
      palette: palette
    });
    buf = cmap.v_map_screen((function() {
      results = [];
      for (var k = 0, ref3 = palette.length; 0 <= ref3 ? k < ref3 : k > ref3; 0 <= ref3 ? k++ : k--){ results.push(k); }
      return results;
    }).apply(this));
    buf8 = new Uint8ClampedArray(buf);
    image_data.data.set(buf8);
    image_ctx.putImageData(image_data, 0, 0);
    return this.image = canvas;
  };

  ColorBarView.prototype.compute_legend_dimensions = function() {
    var image_dimensions, image_height, image_width, label_extent, legend_height, legend_width, padding, ref, tick_extent, title_extent;
    image_dimensions = this.model._computed_image_dimensions();
    ref = [image_dimensions.height, image_dimensions.width], image_height = ref[0], image_width = ref[1];
    label_extent = this._get_label_extent();
    title_extent = this.model._title_extent();
    tick_extent = this.model._tick_extent();
    padding = this.model.padding;
    switch (this.model.orientation) {
      case "vertical":
        legend_height = image_height + title_extent + padding * 2;
        legend_width = image_width + tick_extent + label_extent + padding * 2;
        break;
      case "horizontal":
        legend_height = image_height + title_extent + tick_extent + label_extent + padding * 2;
        legend_width = image_width + padding * 2;
    }
    return {
      height: legend_height,
      width: legend_width
    };
  };

  ColorBarView.prototype.compute_legend_location = function() {
    var h_range, legend_dimensions, legend_height, legend_margin, legend_width, location, ref, sx, sy, v_range, x, y;
    legend_dimensions = this.compute_legend_dimensions();
    ref = [legend_dimensions.height, legend_dimensions.width], legend_height = ref[0], legend_width = ref[1];
    legend_margin = this.model.margin;
    location = this.model.location;
    h_range = this.plot_view.frame.h_range;
    v_range = this.plot_view.frame.v_range;
    if (_.isString(location)) {
      switch (location) {
        case 'top_left':
          x = h_range.start + legend_margin;
          y = v_range.end - legend_margin;
          break;
        case 'top_center':
          x = (h_range.end + h_range.start) / 2 - legend_width / 2;
          y = v_range.end - legend_margin;
          break;
        case 'top_right':
          x = h_range.end - legend_margin - legend_width;
          y = v_range.end - legend_margin;
          break;
        case 'right_center':
          x = h_range.end - legend_margin - legend_width;
          y = (v_range.end + v_range.start) / 2 + legend_height / 2;
          break;
        case 'bottom_right':
          x = h_range.end - legend_margin - legend_width;
          y = v_range.start + legend_margin + legend_height;
          break;
        case 'bottom_center':
          x = (h_range.end + h_range.start) / 2 - legend_width / 2;
          y = v_range.start + legend_margin + legend_height;
          break;
        case 'bottom_left':
          x = h_range.start + legend_margin;
          y = v_range.start + legend_margin + legend_height;
          break;
        case 'left_center':
          x = h_range.start + legend_margin;
          y = (v_range.end + v_range.start) / 2 + legend_height / 2;
          break;
        case 'center':
          x = (h_range.end + h_range.start) / 2 - legend_width / 2;
          y = (v_range.end + v_range.start) / 2 + legend_height / 2;
      }
    } else if (_.isArray(location) && location.length === 2) {
      x = location[0], y = location[1];
    }
    sx = this.plot_view.canvas.vx_to_sx(x);
    sy = this.plot_view.canvas.vy_to_sy(y);
    return {
      sx: sx,
      sy: sy
    };
  };

  ColorBarView.prototype.render = function() {
    var ctx, frame_offset, image_offset, location, panel_offset;
    if (this.model.visible === false) {
      return;
    }
    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);
      frame_offset = this._get_frame_offset();
      ctx.translate(frame_offset.x, frame_offset.y);
    }
    location = this.compute_legend_location();
    ctx.translate(location.sx, location.sy);
    this._draw_bbox(ctx);
    image_offset = this._get_image_offset();
    ctx.translate(image_offset.x, image_offset.y);
    this._draw_image(ctx);
    if ((this.model.color_mapper.low != null) && (this.model.color_mapper.high != null)) {
      this._draw_major_ticks(ctx);
      this._draw_minor_ticks(ctx);
      this._draw_major_labels(ctx);
    }
    if (this.model.title) {
      this._draw_title(ctx);
    }
    return ctx.restore();
  };

  ColorBarView.prototype._draw_bbox = function(ctx) {
    var bbox;
    bbox = this.compute_legend_dimensions();
    ctx.save();
    if (this.visuals.background_fill.doit) {
      this.visuals.background_fill.set_value(ctx);
      ctx.fillRect(0, 0, bbox.width, bbox.height);
    }
    if (this.visuals.border_line.doit) {
      this.visuals.border_line.set_value(ctx);
      ctx.strokeRect(0, 0, bbox.width, bbox.height);
    }
    return ctx.restore();
  };

  ColorBarView.prototype._draw_image = function(ctx) {
    var image;
    image = this.model._computed_image_dimensions();
    ctx.save();
    ctx.setImageSmoothingEnabled(false);
    ctx.globalAlpha = this.model.scale_alpha;
    ctx.drawImage(this.image, 0, 0, image.width, image.height);
    if (this.visuals.bar_line.doit) {
      this.visuals.bar_line.set_value(ctx);
      ctx.strokeRect(0, 0, image.width, image.height);
    }
    return ctx.restore();
  };

  ColorBarView.prototype._draw_major_ticks = function(ctx) {
    var i, image, k, nx, ny, ref, ref1, ref2, ref3, sx, sy, tin, tout, x_offset, y_offset;
    if (!this.visuals.major_tick_line.doit) {
      return;
    }
    ref = this.model._normals(), nx = ref[0], ny = ref[1];
    image = this.model._computed_image_dimensions();
    ref1 = [image.width * nx, image.height * ny], x_offset = ref1[0], y_offset = ref1[1];
    ref2 = this.model._tick_coordinates().major, sx = ref2[0], sy = ref2[1];
    tin = this.model.major_tick_in;
    tout = this.model.major_tick_out;
    ctx.save();
    ctx.translate(x_offset, y_offset);
    this.visuals.major_tick_line.set_value(ctx);
    for (i = k = 0, ref3 = sx.length; 0 <= ref3 ? k < ref3 : k > ref3; i = 0 <= ref3 ? ++k : --k) {
      ctx.beginPath();
      ctx.moveTo(Math.round(sx[i] + nx * tout), Math.round(sy[i] + ny * tout));
      ctx.lineTo(Math.round(sx[i] - nx * tin), Math.round(sy[i] - ny * tin));
      ctx.stroke();
    }
    return ctx.restore();
  };

  ColorBarView.prototype._draw_minor_ticks = function(ctx) {
    var i, image, k, nx, ny, ref, ref1, ref2, ref3, sx, sy, tin, tout, x_offset, y_offset;
    if (!this.visuals.minor_tick_line.doit) {
      return;
    }
    ref = this.model._normals(), nx = ref[0], ny = ref[1];
    image = this.model._computed_image_dimensions();
    ref1 = [image.width * nx, image.height * ny], x_offset = ref1[0], y_offset = ref1[1];
    ref2 = this.model._tick_coordinates().minor, sx = ref2[0], sy = ref2[1];
    tin = this.model.minor_tick_in;
    tout = this.model.minor_tick_out;
    ctx.save();
    ctx.translate(x_offset, y_offset);
    this.visuals.minor_tick_line.set_value(ctx);
    for (i = k = 0, ref3 = sx.length; 0 <= ref3 ? k < ref3 : k > ref3; i = 0 <= ref3 ? ++k : --k) {
      ctx.beginPath();
      ctx.moveTo(Math.round(sx[i] + nx * tout), Math.round(sy[i] + ny * tout));
      ctx.lineTo(Math.round(sx[i] - nx * tin), Math.round(sy[i] - ny * tin));
      ctx.stroke();
    }
    return ctx.restore();
  };

  ColorBarView.prototype._draw_major_labels = function(ctx) {
    var formatted_labels, i, image, k, labels, nx, ny, ref, ref1, ref2, ref3, ref4, standoff, sx, sy, x_offset, x_standoff, y_offset, y_standoff;
    if (!this.visuals.major_label_text.doit) {
      return;
    }
    ref = this.model._normals(), nx = ref[0], ny = ref[1];
    image = this.model._computed_image_dimensions();
    ref1 = [image.width * nx, image.height * ny], x_offset = ref1[0], y_offset = ref1[1];
    standoff = this.model.label_standoff + this.model._tick_extent();
    ref2 = [standoff * nx, standoff * ny], x_standoff = ref2[0], y_standoff = ref2[1];
    ref3 = this.model._tick_coordinates().major, sx = ref3[0], sy = ref3[1];
    labels = this.model._tick_coordinates().major_labels;
    formatted_labels = this.model.formatter.doFormat(labels);
    this.visuals.major_label_text.set_value(ctx);
    ctx.save();
    ctx.translate(x_offset + x_standoff, y_offset + y_standoff);
    for (i = k = 0, ref4 = sx.length; 0 <= ref4 ? k < ref4 : k > ref4; i = 0 <= ref4 ? ++k : --k) {
      ctx.fillText(formatted_labels[i], Math.round(sx[i] + nx * this.model.label_standoff), Math.round(sy[i] + ny * this.model.label_standoff));
    }
    return ctx.restore();
  };

  ColorBarView.prototype._draw_title = function(ctx) {
    if (!this.visuals.title_text.doit) {
      return;
    }
    ctx.save();
    this.visuals.title_text.set_value(ctx);
    ctx.fillText(this.model.title, 0, -this.model.title_standoff);
    return ctx.restore();
  };

  ColorBarView.prototype._get_label_extent = function() {
    var ctx, formatted_labels, label, label_extent;
    if ((this.model.color_mapper.low != null) && (this.model.color_mapper.high != null)) {
      ctx = this.plot_view.canvas_view.ctx;
      ctx.save();
      this.visuals.major_label_text.set_value(ctx);
      switch (this.model.orientation) {
        case "vertical":
          formatted_labels = this.model.formatter.doFormat(this.model._tick_coordinates().major_labels);
          label_extent = _.max((function() {
            var k, len, results;
            results = [];
            for (k = 0, len = formatted_labels.length; k < len; k++) {
              label = formatted_labels[k];
              results.push(ctx.measureText(label.toString()).width);
            }
            return results;
          })());
          break;
        case "horizontal":
          label_extent = text_util.get_text_height(this.visuals.major_label_text.font_value()).height;
      }
      label_extent += this.model.label_standoff;
      ctx.restore();
    } else {
      label_extent = 0;
    }
    return label_extent;
  };

  ColorBarView.prototype._get_frame_offset = function() {
    var frame, panel, ref, xoff, yoff;
    ref = [0, 0], xoff = ref[0], yoff = ref[1];
    panel = this.model.panel;
    frame = this.plot_view.frame;
    switch (panel.side) {
      case "left":
      case "right":
        yoff = Math.abs(panel.top - frame.top);
        break;
      case "above":
      case "below":
        xoff = Math.abs(frame.left);
    }
    return {
      x: xoff,
      y: yoff
    };
  };

  ColorBarView.prototype._get_image_offset = function() {
    var x, y;
    x = this.model.padding;
    y = this.model.padding + this.model._title_extent();
    return {
      x: x,
      y: y
    };
  };

  return ColorBarView;

})(Annotation.View);

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

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

  ColorBar.prototype.default_view = ColorBarView;

  ColorBar.prototype.type = 'ColorBar';

  ColorBar.mixins(['text:major_label_', 'text:title_', 'line:major_tick_', 'line:minor_tick_', 'line:border_', 'line:bar_', 'fill:background_']);

  ColorBar.define({
    location: [p.Any, 'top_right'],
    orientation: [p.Orientation, 'vertical'],
    title: [p.String],
    title_standoff: [p.Number, 2],
    height: [p.Any, 'auto'],
    width: [p.Any, 'auto'],
    scale_alpha: [p.Number, 1.0],
    ticker: [
      p.Instance, function() {
        return new BasicTicker.Model();
      }
    ],
    formatter: [
      p.Instance, function() {
        return new BasicTickFormatter.Model();
      }
    ],
    color_mapper: [p.Instance],
    label_standoff: [p.Number, 5],
    margin: [p.Number, 30],
    padding: [p.Number, 10],
    major_tick_in: [p.Number, 5],
    major_tick_out: [p.Number, 0],
    minor_tick_in: [p.Number, 0],
    minor_tick_out: [p.Number, 0]
  });

  ColorBar.override({
    background_fill_color: "#ffffff",
    background_fill_alpha: 0.95,
    bar_line_color: null,
    border_line_color: null,
    major_label_text_align: "center",
    major_label_text_baseline: "middle",
    major_label_text_font_size: "8pt",
    major_tick_line_color: "#ffffff",
    minor_tick_line_color: null,
    title_text_font_size: "10pt",
    title_text_font_style: "italic"
  });

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

  ColorBar.prototype._normals = function() {
    var i, j, ref, ref1;
    if (this.orientation === 'vertical') {
      ref = [1, 0], i = ref[0], j = ref[1];
    } else {
      ref1 = [0, 1], i = ref1[0], j = ref1[1];
    }
    return [i, j];
  };

  ColorBar.prototype._title_extent = function() {
    var font_value, title_extent;
    font_value = this.title_text_font + " " + this.title_text_font_size + " " + this.title_text_font_style;
    title_extent = this.title ? text_util.get_text_height(font_value).height + this.title_standoff : 0;
    return title_extent;
  };

  ColorBar.prototype._tick_extent = function() {
    var tick_extent;
    if ((this.color_mapper.low != null) && (this.color_mapper.high != null)) {
      tick_extent = _.max([this.major_tick_out, this.minor_tick_out]);
    } else {
      tick_extent = 0;
    }
    return tick_extent;
  };

  ColorBar.prototype._computed_image_dimensions = function() {

    /*
    Heuristics to determine ColorBar image dimensions if set to "auto"
    
    Note: Returns the height/width values for the ColorBar's scale image, not
    the dimensions of the entire ColorBar.
    
    If the short dimension (the width of a vertical bar or height of a
    horizontal bar) is set to "auto", the resulting dimension will be set to
    25 px.
    
    For a ColorBar in a side panel with the long dimension (the height of a
    vertical bar or width of a horizontal bar) set to "auto", the
    resulting dimension will be as long as the adjacent frame edge, so that the
    bar "fits" to the plot.
    
    For a ColorBar in the plot frame with the long dimension set to "auto", the
    resulting dimension will be the greater of:
      * The length of the color palette * 25px
      * The parallel frame dimension * 0.30
        (i.e the frame height for a vertical ColorBar)
    But not greater than:
      * The parallel frame dimension * 0.80
     */
    var frame_height, frame_width, height, title_extent, width;
    frame_height = this.plot.plot_canvas.frame.height;
    frame_width = this.plot.plot_canvas.frame.width;
    title_extent = this._title_extent();
    switch (this.orientation) {
      case "vertical":
        if (this.height === 'auto') {
          if (this.panel != null) {
            height = frame_height - 2 * this.padding - title_extent;
          } else {
            height = _.max([this.color_mapper.palette.length * SHORT_DIM, frame_height * LONG_DIM_MIN_SCALAR]);
            height = _.min([height, frame_height * LONG_DIM_MAX_SCALAR - 2 * this.padding - title_extent]);
          }
        } else {
          height = this.height;
        }
        width = this.width === 'auto' ? SHORT_DIM : this.width;
        break;
      case "horizontal":
        height = this.height === 'auto' ? SHORT_DIM : this.height;
        if (this.width === 'auto') {
          if (this.panel != null) {
            width = frame_width - 2 * this.padding;
          } else {
            width = _.max([this.color_mapper.palette.length * SHORT_DIM, frame_width * LONG_DIM_MIN_SCALAR]);
            width = _.min([width, frame_width * LONG_DIM_MAX_SCALAR - 2 * this.padding]);
          }
        } else {
          width = this.width;
        }
    }
    return {
      "height": height,
      "width": width
    };
  };

  ColorBar.prototype._tick_coordinate_mapper = function(scale_length) {

    /*
    Creates and returns a mapper instance that maps the `color_mapper` range
    (low to high) to a screen space range equal to the length of the ColorBar's
    scale image. The mapper is used to calculate the tick coordinates in screen
    coordinates for plotting purposes.
    
    Note: the type of color_mapper has to match the type of mapper (i.e.
    a LinearColorMapper will require a corresponding LinearMapper instance).
     */
    var mapper, mapping;
    mapping = {
      'source_range': new Range1d.Model({
        start: this.color_mapper.low,
        end: this.color_mapper.high
      }),
      'target_range': new Range1d.Model({
        start: 0,
        end: scale_length
      })
    };
    switch (this.color_mapper.type) {
      case "LinearColorMapper":
        mapper = new LinearMapper.Model(mapping);
        break;
      case "LogColorMapper":
        mapper = new LogMapper.Model(mapping);
    }
    return mapper;
  };

  ColorBar.prototype._tick_coordinates = function() {
    var coord, end, i, ii, image_dimensions, j, k, l, major_coords, major_labels, majors, mapper, minor_coords, minors, ref, ref1, ref2, ref3, scale_length, start, ticks;
    image_dimensions = this._computed_image_dimensions();
    switch (this.orientation) {
      case "vertical":
        scale_length = image_dimensions.height;
        break;
      case "horizontal":
        scale_length = image_dimensions.width;
    }
    mapper = this._tick_coordinate_mapper(scale_length);
    ref = this._normals(), i = ref[0], j = ref[1];
    ref1 = [this.color_mapper.low, this.color_mapper.high], start = ref1[0], end = ref1[1];
    ticks = this.ticker.get_ticks(start, end, null, this.ticker.desired_num_ticks);
    majors = ticks.major;
    minors = ticks.minor;
    major_coords = [[], []];
    minor_coords = [[], []];
    for (ii = k = 0, ref2 = majors.length; 0 <= ref2 ? k < ref2 : k > ref2; ii = 0 <= ref2 ? ++k : --k) {
      if (majors[ii] < start || majors[ii] > end) {
        continue;
      }
      major_coords[i].push(majors[ii]);
      major_coords[j].push(0);
    }
    for (ii = l = 0, ref3 = minors.length; 0 <= ref3 ? l < ref3 : l > ref3; ii = 0 <= ref3 ? ++l : --l) {
      if (minors[ii] < start || minors[ii] > end) {
        continue;
      }
      minor_coords[i].push(minors[ii]);
      minor_coords[j].push(0);
    }
    major_labels = major_coords[i].slice(0);
    major_coords[i] = mapper.v_map_to_target(major_coords[i]);
    minor_coords[i] = mapper.v_map_to_target(minor_coords[i]);
    if (this.orientation === 'vertical') {
      major_coords[i] = new Float64Array((function() {
        var len, m, ref4, results;
        ref4 = major_coords[i];
        results = [];
        for (m = 0, len = ref4.length; m < len; m++) {
          coord = ref4[m];
          results.push(scale_length - coord);
        }
        return results;
      })());
      minor_coords[i] = new Float64Array((function() {
        var len, m, ref4, results;
        ref4 = minor_coords[i];
        results = [];
        for (m = 0, len = ref4.length; m < len; m++) {
          coord = ref4[m];
          results.push(scale_length - coord);
        }
        return results;
      })());
    }
    return {
      "major": major_coords,
      "minor": minor_coords,
      "major_labels": major_labels
    };
  };

  return ColorBar;

})(Annotation.Model);

module.exports = {
  Model: ColorBar,
  View: ColorBarView
};

},{"../../core/properties":"core/properties","../../core/util/text":"core/util/text","../formatters/basic_tick_formatter":"models/formatters/basic_tick_formatter","../mappers/linear_color_mapper":"models/mappers/linear_color_mapper","../mappers/linear_mapper":"models/mappers/linear_mapper","../mappers/log_mapper":"models/mappers/log_mapper","../ranges/range1d":"models/ranges/range1d","../tickers/basic_ticker":"models/tickers/basic_ticker","./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) {
    LabelView.__super__.initialize.call(this, options);
    this.canvas = this.plot_model.canvas;
    this.xmapper = this.plot_view.frame.x_mappers[this.model.x_range_name];
    this.ymapper = this.plot_view.frame.y_mappers[this.model.y_range_name];
    return this.visuals.warm_cache(null);
  };

  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.model.text).ascent;
      return height;
    }
    if (side === 'left' || side === 'right') {
      width = ctx.measureText(this.model.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.model.angle_units) {
      case "rad":
        angle = -1 * this.model.angle;
        break;
      case "deg":
        angle = -1 * this.model.angle * Math.PI / 180.0;
    }
    if (this.model.x_units === "data") {
      vx = this.xmapper.map_to_target(this.model.x);
    } else {
      vx = this.model.x;
    }
    sx = this.canvas.vx_to_sx(vx);
    if (this.model.y_units === "data") {
      vy = this.ymapper.map_to_target(this.model.y);
    } else {
      vy = this.model.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.model.render_mode === 'canvas') {
      return this._canvas_text(ctx, this.model.text, sx + this.model.x_offset, sy - this.model.y_offset, angle);
    } else {
      return this._css_text(ctx, this.model.text, sx + this.model.x_offset, sy - this.model.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.x_mappers[this.model.x_range_name];
    this.ymapper = this.plot_view.frame.y_mappers[this.model.y_range_name];
    this.set_data(this.model.source);
    if (this.model.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.model.render_mode === 'css') {
      this.listenTo(this.model, 'change', function() {
        this.set_data(this.model.source);
        return this.render();
      });
      return this.listenTo(this.model.source, 'change', function() {
        this.set_data(this.model.source);
        return this.render();
      });
    } else {
      this.listenTo(this.model, 'change', function() {
        this.set_data(this.model.source);
        return this.plot_view.request_render();
      });
      return this.listenTo(this.model.source, 'change', function() {
        this.set_data(this.model.source);
        return this.plot_view.request_render();
      });
    }
  };

  LabelSetView.prototype.set_data = function(source) {
    LabelSetView.__super__.set_data.call(this, source);
    return this.visuals.warm_cache(source);
  };

  LabelSetView.prototype._map_data = function() {
    var sx, sy, vx, vy;
    if (this.model.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.model.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.model.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.define({
    x: [p.NumberSpec],
    y: [p.NumberSpec],
    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, GlyphRenderer, 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");

GlyphRenderer = require("../renderers/glyph_renderer");

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, h_range, i, label_height, label_standoff, label_width, legend_height, legend_margin, legend_names, legend_padding, legend_spacing, legend_width, len, location, max_label_width, name, ref, v_range, width, x, y;
    legend_names = this.model.get_legend_names();
    glyph_height = this.model.glyph_height;
    glyph_width = this.model.glyph_width;
    label_height = this.model.label_height;
    label_width = this.model.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.model.margin;
    legend_padding = this.model.padding;
    legend_spacing = this.model.spacing;
    label_standoff = this.model.label_standoff;
    if (this.model.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.model.location;
    h_range = this.plot_view.frame.h_range;
    v_range = this.plot_view.frame.v_range;
    if (_.isString(location)) {
      switch (location) {
        case 'top_left':
          x = h_range.start + legend_margin;
          y = v_range.end - legend_margin;
          break;
        case 'top_center':
          x = (h_range.end + h_range.start) / 2 - legend_width / 2;
          y = v_range.end - legend_margin;
          break;
        case 'top_right':
          x = h_range.end - legend_margin - legend_width;
          y = v_range.end - legend_margin;
          break;
        case 'right_center':
          x = h_range.end - legend_margin - legend_width;
          y = (v_range.end + v_range.start) / 2 + legend_height / 2;
          break;
        case 'bottom_right':
          x = h_range.end - legend_margin - legend_width;
          y = v_range.start + legend_margin + legend_height;
          break;
        case 'bottom_center':
          x = (h_range.end + h_range.start) / 2 - legend_width / 2;
          y = v_range.start + legend_margin + legend_height;
          break;
        case 'bottom_left':
          x = h_range.start + legend_margin;
          y = v_range.start + legend_margin + legend_height;
          break;
        case 'left_center':
          x = h_range.start + legend_margin;
          y = (v_range.end + v_range.start) / 2 + legend_height / 2;
          break;
        case 'center':
          x = (h_range.end + h_range.start) / 2 - legend_width / 2;
          y = (v_range.end + v_range.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 bbox, ctx;
    if (this.model.items.length === 0) {
      return;
    }
    ctx = this.plot_view.canvas_view.ctx;
    bbox = this.compute_legend_bbox();
    ctx.save();
    this._draw_legend_box(ctx, bbox);
    this._draw_legend_items(ctx, bbox);
    return ctx.restore();
  };

  LegendView.prototype._draw_legend_box = function(ctx, bbox) {
    var panel_offset;
    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);
      return ctx.stroke();
    }
  };

  LegendView.prototype._draw_legend_items = function(ctx, bbox) {
    var field, glyph_height, glyph_width, i, item, label, label_standoff, labels, legend_spacing, len, r, ref, results, view, x1, x2, xoffset, y1, y2, yoffset;
    glyph_height = this.model.glyph_height;
    glyph_width = this.model.glyph_width;
    legend_spacing = this.model.spacing;
    label_standoff = this.model.label_standoff;
    xoffset = yoffset = this.model.padding;
    ref = this.model.items;
    results = [];
    for (i = 0, len = ref.length; i < len; i++) {
      item = ref[i];
      labels = item.get_labels_list_from_label_prop();
      field = item.get_field_from_label_prop();
      if (labels.length === 0) {
        continue;
      }
      results.push((function() {
        var j, len1, results1;
        results1 = [];
        for (j = 0, len1 = labels.length; j < len1; j++) {
          label = labels[j];
          x1 = bbox.x + xoffset;
          y1 = bbox.y + yoffset;
          x2 = x1 + glyph_width;
          y2 = y1 + glyph_height;
          if (this.model.orientation === "vertical") {
            yoffset += this.max_label_height + legend_spacing;
          } else {
            xoffset += this.text_widths[label] + glyph_width + label_standoff + legend_spacing;
          }
          this.visuals.label_text.set_value(ctx);
          ctx.fillText(label, x2 + label_standoff, y1 + this.max_label_height / 2.0);
          results1.push((function() {
            var k, len2, ref1, results2;
            ref1 = item.renderers;
            results2 = [];
            for (k = 0, len2 = ref1.length; k < len2; k++) {
              r = ref1[k];
              view = this.plot_view.renderer_views[r.id];
              results2.push(view.draw_legend(ctx, x1, x2, y1, y2, field, label));
            }
            return results2;
          }).call(this));
        }
        return results1;
      }).call(this));
    }
    return results;
  };

  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.prototype.get_legend_names = function() {
    var i, item, labels, legend_names, len, ref;
    legend_names = [];
    ref = this.items;
    for (i = 0, len = ref.length; i < len; i++) {
      item = ref[i];
      labels = item.get_labels_list_from_label_prop();
      legend_names = legend_names.concat(labels);
    }
    return legend_names;
  };

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

  Legend.define({
    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],
    margin: [p.Number, 10],
    padding: [p.Number, 10],
    spacing: [p.Number, 3],
    items: [p.Array, []]
  });

  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","../renderers/glyph_renderer":"models/renderers/glyph_renderer","./annotation":"models/annotations/annotation","underscore":"underscore"}],"models/annotations/legend_item":[function(require,module,exports){
var ColumnDataSource, LegendItem, Model, _, 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,
  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");

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

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

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

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

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

  function LegendItem() {
    this.get_labels_list_from_label_prop = bind(this.get_labels_list_from_label_prop, this);
    this.get_field_from_label_prop = bind(this.get_field_from_label_prop, this);
    return LegendItem.__super__.constructor.apply(this, arguments);
  }

  LegendItem.prototype.type = "LegendItem";

  LegendItem.prototype._check_data_sources_on_renderers = function() {
    var field, i, len, r, ref, source;
    field = this.get_field_from_label_prop();
    if (field != null) {
      if (this.renderers.length < 1) {
        return false;
      }
      source = this.renderers[0].data_source;
      if (source != null) {
        ref = this.renderers;
        for (i = 0, len = ref.length; i < len; i++) {
          r = ref[i];
          if (r.data_source !== source) {
            return false;
          }
        }
      }
    }
    return true;
  };

  LegendItem.prototype._check_field_label_on_data_source = function() {
    var field, source;
    field = this.get_field_from_label_prop();
    if (field != null) {
      if (this.renderers.length < 1) {
        return false;
      }
      source = this.renderers[0].data_source;
      if ((source != null) && indexOf.call(source.columns(), field) < 0) {
        return false;
      }
    }
    return true;
  };

  LegendItem.prototype.initialize = function(attrs, options) {
    var data_source_validation, field_validation;
    LegendItem.__super__.initialize.call(this, attrs, options);
    data_source_validation = this._check_data_sources_on_renderers();
    if (!data_source_validation) {
      logger.error("Non matching data sources on legend item renderers");
    }
    field_validation = this._check_field_label_on_data_source();
    if (!field_validation) {
      return logger.error("Bad column name on label: " + this.label);
    }
  };

  LegendItem.define({
    label: [p.StringSpec, null],
    renderers: [p.Array, []]
  });

  LegendItem.prototype.get_field_from_label_prop = function() {
    if ((this.label != null) && (this.label.field != null)) {
      return this.label.field;
    }
  };

  LegendItem.prototype.get_labels_list_from_label_prop = function() {
    var data, field, source;
    if ((this.label != null) && (this.label.value != null)) {
      return [this.label.value];
    }
    field = this.get_field_from_label_prop();
    if (field != null) {
      if (this.renderers[0] && (this.renderers[0].data_source != null)) {
        source = this.renderers[0].data_source;
      } else {
        return ["No source found"];
      }
      if (source instanceof ColumnDataSource.Model) {
        data = source.get_column(field);
        if (data != null) {
          return _.unique(data);
        } else {
          return ["Invalid field"];
        }
      }
    }
    return [];
  };

  return LegendItem;

})(Model);

module.exports = {
  Model: LegendItem
};

},{"../../core/logging":"core/logging","../../core/properties":"core/properties","../../model":"model","../../models/sources/column_data_source":"models/sources/column_data_source","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.model.xs;
    ys = this.model.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.model.xs_units === 'screen') {
        vx = xs[i];
      }
      if (this.model.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.setv({
      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.model.for_hover) {
      return this.listenTo(this.model, 'change:computed_location', this._draw_span);
    } else {
      if (this.model.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.model.for_hover) {
      loc = this.model.computed_location;
    } else {
      loc = this.model.location;
    }
    if (loc == null) {
      this.$el.hide();
      return;
    }
    frame = this.plot_model.frame;
    canvas = this.plot_model.canvas;
    xmapper = this.plot_view.frame.x_mappers[this.model.x_range_name];
    ymapper = this.plot_view.frame.y_mappers[this.model.y_range_name];
    if (this.model.dimension === 'width') {
      stop = canvas.vy_to_sy(this._calc_dim(loc, ymapper));
      sleft = canvas.vx_to_sx(frame.left);
      width = frame.width;
      height = this.model.properties.line_width.value();
    } else {
      stop = canvas.vy_to_sy(frame.top);
      sleft = canvas.vx_to_sx(this._calc_dim(loc, xmapper));
      width = this.model.properties.line_width.value();
      height = frame.height;
    }
    if (this.model.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.model.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.model.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.model.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.canvas;
    this.frame = this.plot_model.frame;
    if (this.model.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.model.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.model.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("../../core/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(this.model);
    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.model.align, this.frame.v_range) + this.model.offset;
        break;
      case 'right':
        vx = this.canvas.right - 1;
        vy = this.canvas.height - this._get_text_location(this.model.align, this.frame.v_range) - this.model.offset;
        break;
      case 'above':
        vx = this._get_text_location(this.model.align, this.frame.h_range) + this.model.offset;
        vy = this.canvas.top - 10;
        break;
      case 'below':
        vx = this._get_text_location(this.model.align, this.frame.h_range) + this.model.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.start;
        break;
      case 'center':
        text_location = (range.end + range.start) / 2;
        break;
      case 'right':
        text_location = range.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","../../core/visuals":"core/visuals","./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.model.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.model.inner_only && !this.plot_view.frame.contains(vx, vy)) {
        continue;
      }
      tip = $('<div />').appendTo(this.$el);
      tip.append(content);
    }
    sx = this.plot_view.model.canvas.vx_to_sx(vx);
    sy = this.plot_view.model.canvas.vy_to_sy(vy);
    attachment = this.model.attachment;
    switch (attachment) {
      case "horizontal":
        width = this.plot_view.frame.width;
        left = this.plot_view.frame.left;
        if (vx - left < width / 2) {
          side = 'right';
        } else {
          side = 'left';
        }
        break;
      case "vertical":
        height = this.plot_view.frame.height;
        bottom = this.plot_view.frame.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.model.show_arrow) {
      this.$el.addClass("bk-tooltip-arrow");
    }
    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],
    show_arrow: [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.model.x_range_name;
    return this._y_range_name = this.model.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.model.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.model.normals, nx = ref2[0], ny = ref2[1];
    ref3 = this.model.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.model.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.model.normals, nx = ref2[0], ny = ref2[1];
    ref3 = this.model.offsets, xoff = ref3[0], yoff = ref3[1];
    tin = this.model.major_tick_in;
    tout = this.model.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.model.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.model.normals, nx = ref2[0], ny = ref2[1];
    ref3 = this.model.offsets, xoff = ref3[0], yoff = ref3[1];
    tin = this.model.minor_tick_in;
    tout = this.model.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.model.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.model.normals, nx = ref2[0], ny = ref2[1];
    ref3 = this.model.offsets, xoff = ref3[0], yoff = ref3[1];
    dim = this.model.dimension;
    side = this.model.panel_side;
    orient = this.model.major_label_orientation;
    if (_.isString(orient)) {
      angle = this.model.panel.get_label_angle_heuristic(orient);
    } else {
      angle = -orient;
    }
    standoff = this._tick_extent() + this.model.major_label_standoff;
    labels = this.model.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.model.axis_label;
    if (label == null) {
      return;
    }
    ref = this.model.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.model.normals, nx = ref2[0], ny = ref2[1];
    ref3 = this.model.offsets, xoff = ref3[0], yoff = ref3[1];
    side = this.model.panel_side;
    orient = 'parallel';
    angle = this.model.panel.get_label_angle_heuristic(orient);
    standoff = this._tick_extent() + this._tick_label_extent() + this.model.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.model.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.model.dimension;
    coords = this.model.tick_coords.major;
    side = this.model.panel_side;
    orient = this.model.major_label_orientation;
    labels = this.model.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.model.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.model.panel_side;
    axis_label = this.model.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.model.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']);
    return this.add_dependencies('computed_bounds', this.plot, ['x_range', 'y_range']);
  };

  Axis.getters({
    computed_bounds: function() {
      return this._get_computed('computed_bounds');
    },
    rule_coords: function() {
      return this._rule_coords();
    },
    tick_coords: function() {
      return this._tick_coords();
    },
    ranges: function() {
      return this._ranges();
    },
    normals: function() {
      return this.panel._normals;
    },
    dimension: function() {
      return this.panel._dim;
    },
    offsets: function() {
      return this._offsets();
    }
  });

  Axis.prototype.add_panel = function(side) {
    this.panel = new SidePanel.Model({
      side: side
    });
    this.panel.attach_document(this.document);
    return this.panel_side = side;
  };

  Axis.prototype._offsets = function() {
    var frame, ref, side, xoff, yoff;
    side = this.panel_side;
    ref = [0, 0], xoff = ref[0], yoff = ref[1];
    frame = this.plot.plot_canvas.frame;
    switch (side) {
      case "below":
        yoff = Math.abs(this.panel.top - frame.bottom);
        break;
      case "above":
        yoff = Math.abs(this.panel.bottom - frame.top);
        break;
      case "right":
        xoff = Math.abs(this.panel.left - frame.right);
        break;
      case "left":
        xoff = Math.abs(this.panel.right - frame.left);
    }
    return [xoff, yoff];
  };

  Axis.prototype._ranges = function() {
    var frame, i, j, ranges;
    i = this.dimension;
    j = (i + 1) % 2;
    frame = this.plot.plot_canvas.frame;
    ranges = [frame.x_ranges[this.x_range_name], frame.y_ranges[this.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.ranges, range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.bounds) != null ? ref1 : 'auto';
    range_bounds = [range.min, range.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.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];
    xs = new Array(2);
    ys = new Array(2);
    coords = [xs, ys];
    loc = this._get_loc(cross_range);
    coords[i][0] = Math.max(start, range.min);
    coords[i][1] = Math.min(end, range.max);
    if (coords[i][0] > coords[i][1]) {
      coords[i][0] = coords[i][1] = 0/0;
    }
    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.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];
    ticks = this.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.min, range.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, side;
    cstart = cross_range.start;
    cend = cross_range.end;
    side = this.panel_side;
    switch (side) {
      case 'left':
      case 'below':
        return cross_range.start;
      case 'right':
      case 'above':
        return cross_range.end;
    }
  };

  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.ranges, range = ref[0], cross_range = ref[1];
    user_bounds = (ref1 = this.bounds) != null ? ref1 : 'auto';
    range_bounds = [range.min, range.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, '']
  });

  CustomJS.getters({
    values: function() {
      return this._make_values();
    },
    func: function() {
      return this._make_func();
    }
  });

  CustomJS.prototype.execute = function(cb_obj, cb_data) {
    return this.func.apply(this, slice.call(this.values).concat([cb_obj], [cb_data], [require]));
  };

  CustomJS.prototype._make_values = function() {
    return _.values(this.args);
  };

  CustomJS.prototype._make_func = function() {
    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.args)).concat(["cb_obj"], ["cb_data"], ["require"], [this.code]), function(){});
  };

  return CustomJS;

})(Model);

module.exports = {
  Model: CustomJS
};

},{"../../core/properties":"core/properties","../../model":"model","underscore":"underscore"}],"models/callbacks/open_url":[function(require,module,exports){
var Model, OpenURL, _, get_indices, p, replace_placeholders,
  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");

get_indices = require("../../core/util/selection").get_indices;

replace_placeholders = require("../../core/util/templating").replace_placeholders;

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 = get_indices(data_source);
    for (j = 0, len = ref.length; j < len; j++) {
      i = ref[j];
      url = replace_placeholders(this.url, data_source, i);
      window.open(url);
    }
    return null;
  };

  return OpenURL;

})(Model);

module.exports = {
  Model: OpenURL
};

},{"../../core/properties":"core/properties","../../core/util/selection":"core/util/selection","../../core/util/templating":"core/util/templating","../../model":"model","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.model.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.model.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) {
    return new Float64Array(xx);
  };

  Canvas.prototype.v_vy_to_sy = function(yy) {
    var _yy, height, i, idx, len, y;
    _yy = new Float64Array(yy.length);
    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._height._value - (y + 1);
  };

  Canvas.prototype.v_sx_to_vx = function(xx) {
    return new Float64Array(xx);
  };

  Canvas.prototype.v_sy_to_vy = function(yy) {
    var _yy, height, i, idx, len, y;
    _yy = new Float64Array(yy.length);
    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._configure_mappers();
    this.listenTo(this, 'change', (function(_this) {
      return function() {
        return _this._configure_mappers();
      };
    })(this));
    return null;
  };

  CartesianFrame.prototype._doc_attached = function() {
    this.listenTo(this.document.solver(), 'layout_update', (function(_this) {
      return function() {
        return _this._update_mappers();
      };
    })(this));
    return null;
  };

  CartesianFrame.prototype.contains = function(vx, vy) {
    return vx >= this.left && vx <= this.right && vy >= this.bottom && vy <= this.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.x_mappers[x_name].v_map_to_target(x);
    sx = canvas.v_vx_to_sx(vx);
    vy = this.y_mappers[y_name].v_map_to_target(y);
    sy = canvas.v_vy_to_sy(vy);
    return [sx, sy];
  };

  CartesianFrame.prototype._get_ranges = function(range, extra_ranges) {
    var extra_range, name, ranges;
    ranges = {};
    ranges['default'] = range;
    if (extra_ranges != null) {
      for (name in extra_ranges) {
        extra_range = extra_ranges[name];
        ranges[name] = extra_range;
      }
    }
    return ranges;
  };

  CartesianFrame.prototype._get_mappers = function(mapper_type, ranges, frame_range) {
    var mapper_model, mappers, name, range;
    mappers = {};
    for (name in ranges) {
      range = ranges[name];
      if (range.type === "Range1d" || range.type === "DataRange1d") {
        if (mapper_type === "log") {
          mapper_model = LogMapper.Model;
        } else {
          mapper_model = LinearMapper.Model;
        }
      } else if (range.type === "FactorRange") {
        mapper_model = CategoricalMapper.Model;
      } else {
        logger.warn("unknown range type for range '" + name + "': " + range);
        return null;
      }
      mappers[name] = new mapper_model({
        source_range: range,
        target_range: frame_range
      });
    }
    return mappers;
  };

  CartesianFrame.prototype._configure_frame_ranges = function() {
    this._h_range = new Range1d.Model({
      start: this.left,
      end: this.left + this.width
    });
    return this._v_range = new Range1d.Model({
      start: this.bottom,
      end: this.bottom + this.height
    });
  };

  CartesianFrame.prototype._configure_mappers = function() {
    this._configure_frame_ranges();
    this._x_ranges = this._get_ranges(this.x_range, this.extra_x_ranges);
    this._y_ranges = this._get_ranges(this.y_range, this.extra_y_ranges);
    this._x_mappers = this._get_mappers(this.x_mapper_type, this._x_ranges, this._h_range);
    return this._y_mappers = this._get_mappers(this.y_mapper_type, this._y_ranges, this._v_range);
  };

  CartesianFrame.prototype._update_mappers = function() {
    var mapper, name, ref1, ref2;
    this._configure_frame_ranges();
    ref1 = this._x_mappers;
    for (name in ref1) {
      mapper = ref1[name];
      mapper.target_range = this._h_range;
    }
    ref2 = this._y_mappers;
    for (name in ref2) {
      mapper = ref2[name];
      mapper.target_range = this._v_range;
    }
    return null;
  };

  CartesianFrame.getters({
    h_range: function() {
      return this._h_range;
    },
    v_range: function() {
      return this._v_range;
    },
    x_ranges: function() {
      return this._x_ranges;
    },
    y_ranges: function() {
      return this._y_ranges;
    },
    x_mappers: function() {
      return this._x_mappers;
    },
    y_mappers: function() {
      return this._y_mappers;
    }
  });

  CartesianFrame.internal({
    extra_x_ranges: [p.Any, {}],
    extra_y_ranges: [p.Any, {}],
    x_range: [p.Instance],
    y_range: [p.Instance],
    x_mapper_type: [p.String, 'auto'],
    y_mapper_type: [p.String, 'auto']
  });

  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.getters({
    scientific_limit_low: function() {
      return Math.pow(10.0, this.power_limit_low);
    },
    scientific_limit_high: function() {
      return Math.pow(10.0, this.power_limit_high);
    }
  });

  BasicTickFormatter.prototype.initialize = function(attrs, options) {
    BasicTickFormatter.__super__.initialize.call(this, attrs, options);
    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.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.scientific_limit_high || tick_abs <= this.scientific_limit_low)) {
          need_sci = true;
          break;
        }
      }
    }
    precision = this.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 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);
  }
};

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

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

  DatetimeTickFormatter.prototype.type = 'DatetimeTickFormatter';

  DatetimeTickFormatter.define({
    microseconds: [p.Array, ['%fus']],
    milliseconds: [p.Array, ['%3Nms', '%S.%3Ns']],
    seconds: [p.Array, ['%Ss']],
    minsec: [p.Array, [':%M:%S']],
    minutes: [p.Array, [':%M', '%Mm']],
    hourmin: [p.Array, ['%H:%M']],
    hours: [p.Array, ['%Hh', '%H:%M']],
    days: [p.Array, ['%m/%d', '%a%d']],
    months: [p.Array, ['%m/%Y', '%b%y']],
    years: [p.Array, ['%Y']]
  });

  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 _widths, now;
    now = tz(new Date());
    _widths = function(fmt_strings) {
      var fmt_string, sizes, sorted;
      sizes = (function() {
        var j, len, results;
        results = [];
        for (j = 0, len = fmt_strings.length; j < len; j++) {
          fmt_string = fmt_strings[j];
          results.push(_strftime(now, fmt_string).length);
        }
        return results;
      })();
      sorted = _.sortBy(_.zip(sizes, fmt_strings), function(arg) {
        var fmt, size;
        size = arg[0], fmt = arg[1];
        return size;
      });
      return _.zip.apply(_, sorted);
    };
    return this._width_formats = {
      microseconds: _widths(this.microseconds),
      milliseconds: _widths(this.milliseconds),
      seconds: _widths(this.seconds),
      minsec: _widths(this.minsec),
      minutes: _widths(this.minutes),
      hourmin: _widths(this.hourmin),
      hours: _widths(this.hours),
      days: _widths(this.days),
      months: _widths(this.months),
      years: _widths(this.years)
    };
  };

  DatetimeTickFormatter.prototype._get_resolution_str = function(resolution_secs, span_secs) {
    var adjusted_secs;
    adjusted_secs = resolution_secs * 1.1;
    switch (false) {
      case !(adjusted_secs < 1e-3):
        return "microseconds";
      case !(adjusted_secs < 1.0):
        return "milliseconds";
      case !(adjusted_secs < 60):
        if (span_secs >= 60) {
          return "minsec";
        } else {
          return "seconds";
        }
      case !(adjusted_secs < 3600):
        if (span_secs >= 3600) {
          return "hourmin";
        } else {
          return "minutes";
        }
      case !(adjusted_secs < 24 * 3600):
        return "hours";
      case !(adjusted_secs < 31 * 24 * 3600):
        return "days";
      case !(adjusted_secs < 365 * 24 * 3600):
        return "months";
      default:
        return "years";
    }
  };

  DatetimeTickFormatter.prototype.doFormat = function(ticks, num_labels, char_width, fill_ratio, ticker) {
    var error, 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,
  slice = [].slice;

_ = 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({
    args: [p.Any, {}],
    code: [p.String, '']
  });

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

  FuncTickFormatter.prototype._make_func = function() {
    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, ["tick"].concat(slice.call(_.keys(this.args)), ["require"], [this.code]), function(){});
  };

  FuncTickFormatter.prototype.doFormat = function(ticks) {
    var func, tick;
    func = this._make_func();
    return (function() {
      var i, len, results;
      results = [];
      for (i = 0, len = ticks.length; i < len; i++) {
        tick = ticks[i];
        results.push(func.apply(null, [tick].concat(slice.call(_.values(this.args)), [require])));
      }
      return results;
    }).call(this);
  };

  return FuncTickFormatter;

})(TickFormatter.Model);

module.exports = {
  Model: FuncTickFormatter
};

},{"../../core/properties":"core/properties","../formatters/tick_formatter":"models/formatters/tick_formatter","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.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.ticker != null) {
      base = this.ticker.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.format;
    language = this.language;
    rounding = (function() {
      switch (this.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","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.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("../../core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/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("../../core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    var data, indices, r, sinner_radius, souter_radius, sx, sy;
    indices = [index];
    sx = {};
    sx[index] = (x0 + x1) / 2;
    sy = {};
    sy[index] = (y0 + y1) / 2;
    r = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.5;
    sinner_radius = {};
    sinner_radius[index] = r * 0.4;
    souter_radius = {};
    souter_radius[index] = 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
};

},{"../../core/hittest":"core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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("../../core/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.h_range;
    vr = this.renderer.plot_view.frame.v_range;
    if ((this._radius != null) && this.model.properties.radius.units === "data") {
      sx0 = hr.start;
      sx1 = hr.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.start;
      sy1 = vr.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.start - this.max_size;
      sx1 = hr.end + this.max_size;
      ref2 = this.renderer.xmapper.v_map_from_target([sx0, sx1], true), x0 = ref2[0], x1 = ref2[1];
      sy0 = vr.start - this.max_size;
      sy1 = vr.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 = [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;
  };

  CircleView.prototype.draw_legend_for_index = function(ctx, x0, x1, y0, y1, index) {
    var data, indices, sradius, sx, sy;
    indices = [index];
    sx = {};
    sx[index] = (x0 + x1) / 2;
    sy = {};
    sy[index] = (y0 + y1) / 2;
    sradius = {};
    sradius[index] = 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
};

},{"../../core/hittest":"core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    var d, data, indices, scale, sh, sw, sx, sy;
    indices = [index];
    sx = {};
    sx[index] = (x0 + x1) / 2;
    sy = {};
    sy[index] = (y0 + y1) / 2;
    scale = this.sw[index] / this.sh[index];
    d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
    sw = {};
    sh = {};
    if (scale > 1) {
      sw[index] = d;
      sh[index] = d / scale;
    } else {
      sw[index] = d * scale;
      sh[index] = 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/glyph":[function(require,module,exports){
var BokehView, CategoricalMapper, Glyph, GlyphView, Model, Visuals, _, bbox, bokehgl, logger, p, proj, 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");

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

bbox = require("../../core/util/bbox");

proj = require("../../core/util/projections");

BokehView = require("../../core/bokeh_view");

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

Visuals = require("../../core/visuals").Visuals;

bokehgl = require("./webgl/main");

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

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._nohit_warned = {};
    this.renderer = options.renderer;
    this.visuals = new Visuals(this.model);
    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.set_visuals = function(source) {
    this.visuals.warm_cache(source);
    if (this.glglyph != null) {
      return this.glglyph.set_visuals_changed();
    }
  };

  GlyphView.prototype.render = function(ctx, indices, data) {
    if (this.model.visible) {
      ctx.beginPath();
      if (this.glglyph != null) {
        if (this.glglyph.render(ctx, indices, data)) {
          return;
        }
      }
      this._render(ctx, indices, data);
    }
  };

  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.draw_legend_for_index = function(ctx, x0, x1, y0, y1, index) {
    return null;
  };

  GlyphView.prototype._generic_line_legend = function(ctx, x0, x1, y0, y1, index) {
    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, index);
      ctx.stroke();
    }
    return ctx.restore();
  };

  GlyphView.prototype._generic_area_legend = function(ctx, x0, x1, y0, y1, index) {
    var dh, dw, h, indices, sx0, sx1, sy0, sy1, w;
    indices = [index];
    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, index);
      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, index);
      return ctx.stroke();
    }
  };

  GlyphView.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;
  };

  GlyphView.prototype.set_data = function(source) {
    var data, ref, ref1;
    data = this.model.materialize_dataspecs(source);
    _.extend(this, data);
    if (this.renderer.plot_view.model.use_map) {
      if (this._x != null) {
        ref = proj.project_xy(this._x, this._y), this._x = ref[0], this._y = ref[1];
      }
      if (this._xs != null) {
        ref1 = proj.project_xsys(this._xs, this._ys), this._xs = ref1[0], this._ys = ref1[1];
      }
    }
    if (this.glglyph != null) {
      this.glglyph.set_data_changed(this._x.length);
    }
    this._set_data();
    return this.index = this._index_data();
  };

  GlyphView.prototype._set_data = function() {};

  GlyphView.prototype._index_data = function() {};

  GlyphView.prototype.mask_data = function(indices) {
    if (this.glglyph != null) {
      return indices;
    } else {
      return this._mask_data(indices);
    }
  };

  GlyphView.prototype._mask_data = function(indices) {
    return indices;
  };

  GlyphView.prototype._bounds = function(bounds) {
    return bounds;
  };

  GlyphView.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();
  };

  GlyphView.prototype._map_data = function() {};

  GlyphView.prototype.map_to_screen = function(x, y) {
    return this.renderer.plot_view.map_to_screen(x, y, this.model.x_range_name, this.model.y_range_name);
  };

  return GlyphView;

})(BokehView);

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

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

  Glyph.prototype._coords = [];

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

  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/bokeh_view":"core/bokeh_view","../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/util/bbox":"core/util/bbox","../../core/util/projections":"core/util/projections","../../core/visuals":"core/visuals","../../model":"model","../mappers/categorical_mapper":"models/mappers/categorical_mapper","./webgl/main":"models/glyphs/webgl/main","rbush":"rbush","underscore":"underscore"}],"models/glyphs/hbar":[function(require,module,exports){
var CategoricalMapper, 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");

CategoricalMapper = require("../mappers/categorical_mapper");

hittest = require("../../core/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.renderer.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.renderer.plot_view.canvas.v_vx_to_sx(vright);
    this.sleft = this.renderer.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._index_data = function() {
    var b, height, i, index, j, l, left, map_to_synthetic, pts, r, ref, right, t, y;
    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);
    y = map_to_synthetic(this.renderer.ymapper, this._y);
    height = map_to_synthetic(this.renderer.ymapper, this._height);
    index = rbush();
    pts = [];
    for (i = j = 0, ref = y.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      l = left[i];
      r = right[i];
      t = y[i] + 0.5 * height[i];
      b = y[i] - 0.5 * height[i];
      if (isNaN(l + r + t + b) || !isFinite(l + r + t + b)) {
        continue;
      }
      pts.push({
        minX: l,
        minY: b,
        maxX: r,
        maxY: t,
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  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;
  };

  HBarView.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;
  };

  HBarView.prototype.scx = function(i) {
    return (this.sleft[i] + this.sright[i]) / 2;
  };

  HBarView.prototype.draw_legend_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/hittest","../../core/properties":"core/properties","../mappers/categorical_mapper":"models/mappers/categorical_mapper","./glyph":"models/glyphs/glyph","./quad":"models/glyphs/quad","rbush":"rbush","underscore":"underscore"}],"models/glyphs/image":[function(require,module,exports){
var Glyph, Greys9, 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");

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

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

  ImageView.prototype.initialize = function(options) {
    ImageView.__super__.initialize.call(this, options);
    return this.listenTo(this.model.color_mapper, 'change', this._update_image);
  };

  ImageView.prototype._update_image = function() {
    if (this.image_data != null) {
      this._set_data();
      return this.renderer.plot_view.request_render();
    }
  };

  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.model.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() {
    switch (this.model.properties.dw.units) {
      case "data":
        this.sw = this.sdist(this.renderer.xmapper, this._x, this._dw, 'edge', this.model.dilate);
        break;
      case "screen":
        this.sw = this._dw;
    }
    switch (this.model.properties.dh.units) {
      case "data":
        return this.sh = this.sdist(this.renderer.ymapper, this._y, this._dh, 'edge', this.model.dilate);
      case "screen":
        return this.sh = this._dh;
    }
  };

  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);

Greys9 = function() {
  return [0x000000, 0x252525, 0x525252, 0x737373, 0x969696, 0xbdbdbd, 0xd9d9d9, 0xf0f0f0, 0xffffff];
};

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.DistanceSpec],
    dh: [p.DistanceSpec],
    dilate: [p.Bool, false],
    color_mapper: [
      p.Instance, function() {
        return new LinearColorMapper.Model({
          palette: Greys9()
        });
      }
    ]
  });

  return Image;

})(Glyph.Model);

module.exports = {
  Model: Image,
  View: ImageView
};

},{"../../core/properties":"core/properties","../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() {
    switch (this.model.properties.dw.units) {
      case "data":
        this.sw = this.sdist(this.renderer.xmapper, this._x, this._dw, 'edge', this.model.dilate);
        break;
      case "screen":
        this.sw = this._dw;
    }
    switch (this.model.properties.dh.units) {
      case "data":
        return this.sh = this.sdist(this.renderer.ymapper, this._y, this._dh, 'edge', this.model.dilate);
      case "screen":
        return this.sh = this._dh;
    }
  };

  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.DistanceSpec],
    dh: [p.DistanceSpec],
    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.model.retry_attempts;
    retry_timeout = this.model.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(0/0);
        }
        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(0/0);
        }
        return results;
      }
    }).call(this));
    switch (this.model.properties.w.units) {
      case "data":
        this.sw = this.sdist(this.renderer.xmapper, this._x, ws, 'edge', this.model.dilate);
        break;
      case "screen":
        this.sw = ws;
    }
    switch (this.model.properties.h.units) {
      case "data":
        return this.sh = this.sdist(this.renderer.ymapper, this._y, hs, 'edge', this.model.dilate);
      case "screen":
        return this.sh = hs;
    }
  };

  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.left + 1, frame.bottom + 1, frame.width - 2, frame.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.model.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.model.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.DistanceSpec],
    h: [p.DistanceSpec],
    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("../../core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/hittest","./glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/glyphs/multi_line":[function(require,module,exports){
var Glyph, MultiLine, MultiLineView, _, 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");

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

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._hit_point = function(geometry) {
    var dist, hits, i, j, k, l, p0, p1, point, points, ref, ref1, ref2, 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);
    hits = {};
    for (i = k = 0, ref = this.sxs.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) {
      points = null;
      for (j = l = 0, ref1 = this.sxs[i].length - 1; 0 <= ref1 ? l < ref1 : l > ref1; j = 0 <= ref1 ? ++l : --l) {
        ref2 = [
          {
            x: this.sxs[i][j],
            y: this.sys[i][j]
          }, {
            x: this.sxs[i][j + 1],
            y: this.sys[i][j + 1]
          }
        ], p0 = ref2[0], p1 = ref2[1];
        dist = hittest.dist_to_segment(point, p0, p1);
        if (dist < threshold && dist < shortest) {
          shortest = dist;
          points = [j];
        }
      }
      if (points) {
        hits[i] = points;
      }
    }
    result['1d'].indices = _.keys(hits);
    result['2d'] = hits;
    return result;
  };

  MultiLineView.prototype._hit_span = function(geometry) {
    var hits, i, j, k, l, points, ref, ref1, ref2, 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._ys;
    } else {
      val = this.renderer.xmapper.map_from_target(vx);
      values = this._xs;
    }
    hits = {};
    for (i = k = 0, ref1 = values.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
      points = [];
      for (j = l = 0, ref2 = values[i].length - 1; 0 <= ref2 ? l < ref2 : l > ref2; j = 0 <= ref2 ? ++l : --l) {
        if ((values[i][j] <= val && val <= values[i][j + 1])) {
          points.push(j);
        }
      }
      if (points.length > 0) {
        hits[i] = points;
      }
    }
    result['1d'].indices = _.keys(hits);
    result['2d'] = hits;
    return result;
  };

  MultiLineView.prototype.get_interpolation_hit = function(i, point_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._xs[i][point_i], this._ys[i][point_i], this._xs[i][point_i + 1], this._ys[i][point_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];
  };

  MultiLineView.prototype.draw_legend_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/hittest","./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_for_index = function(ctx, x0, x1, y0, y1, index) {
    var d, data, indices, scale, sh, sw, sx, sy;
    indices = [index];
    sx = {};
    sx[index] = (x0 + x1) / 2;
    sy = {};
    sy[index] = (y0 + y1) / 2;
    scale = this.sw[index] / this.sh[index];
    d = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.8;
    sw = {};
    sh = {};
    if (scale > 1) {
      sw[index] = d;
      sh[index] = d / scale;
    } else {
      sw[index] = d * scale;
      sh[index] = 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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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("../../core/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.min, xr.max], x0 = ref[0], x1 = ref[1];
    yr = this.renderer.plot_view.y_range;
    ref1 = [yr.min, yr.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.renderer.sxss = this._build_discontinuous_object(sxs);
    this.renderer.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.renderer.sxss[idx];
      sys = this.renderer.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.renderer.sxss[i].length === 1) {
      return this._get_snap_coord(this.sxs[i]);
    } else {
      sxs = this.renderer.sxss[i];
      sys = this.renderer.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.renderer.syss[i].length === 1) {
      return this._get_snap_coord(this.sys[i]);
    } else {
      sxs = this.renderer.sxss[i];
      sys = this.renderer.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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/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("../../core/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];
      r = right[i];
      t = top[i];
      b = bottom[i];
      if (isNaN(l + r + t + b) || !isFinite(l + r + t + 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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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.width;
      height = this.renderer.plot_view.frame.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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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("../../core/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.model.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.model.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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_line_legend(ctx, x0, x1, y0, y1, index);
  };

  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_for_index = function(ctx, x0, x1, y0, y1, index) {
    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 CategoricalMapper, 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");

CategoricalMapper = require("../mappers/categorical_mapper");

hittest = require("../../core/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.renderer.plot_view.canvas.v_vy_to_sy(vtop);
    this.sbottom = this.renderer.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._index_data = function() {
    var b, bottom, i, index, j, l, map_to_synthetic, pts, r, ref, t, top, width, x;
    map_to_synthetic = function(mapper, array) {
      if (mapper instanceof CategoricalMapper.Model) {
        return mapper.v_map_to_target(array, true);
      } else {
        return array;
      }
    };
    x = map_to_synthetic(this.renderer.xmapper, this._x);
    width = map_to_synthetic(this.renderer.xmapper, this._width);
    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 = x.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      l = x[i] - width[i] / 2;
      r = x[i] + width[i] / 2;
      t = top[i];
      b = bottom[i];
      if (isNaN(l + r + t + b) || !isFinite(l + r + t + b)) {
        continue;
      }
      pts.push({
        minX: l,
        minY: b,
        maxX: r,
        maxY: t,
        i: i
      });
    }
    index.load(pts);
    return index;
  };

  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;
  };

  VBarView.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;
  };

  VBarView.prototype.scy = function(i) {
    return (this.stop[i] + this.sbottom[i]) / 2;
  };

  VBarView.prototype.draw_legend_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/hittest","../../core/properties":"core/properties","../mappers/categorical_mapper":"models/mappers/categorical_mapper","./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;
  };

  BaseGLGlyph.prototype.render = function(ctx, indices, mainglyph) {
    var dx, dy, ref, ref1, ref2, sx, sy, trans, wx, wy;
    wx = wy = 1;
    ref = this.glyph.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.glyph.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.draw(indices, mainglyph, trans);
    return 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, i, i1, 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 = i1 = 0, ref8 = n; 0 <= ref8 ? i1 < ref8 : i1 > ref8; i = 0 <= ref8 ? ++i1 : --i1) {
      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("../../core/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_for_index = function(ctx, x0, x1, y0, y1, index) {
    return this._generic_area_legend(ctx, x0, x1, y0, y1, index);
  };

  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
};

},{"../../core/hittest":"core/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.model.x_range_name;
    return this._y_range_name = this.model.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.dimension;
    j = (i + 1) % 2;
    frame = this.plot.plot_canvas.frame;
    ranges = [frame.x_ranges[this.x_range_name], frame.y_ranges[this.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.bounds;
    range_bounds = [range.min, range.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.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.ticker.get_ticks(start, end, range, {})[location];
    min = range.min;
    max = range.max;
    cmin = cross_range.min;
    cmax = cross_range.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/index":[function(require,module,exports){
module.exports = {
  Arrow: require('./annotations/arrow'),
  BoxAnnotation: require('./annotations/box_annotation'),
  ColorBar: require('./annotations/color_bar'),
  Label: require('./annotations/label'),
  LabelSet: require('./annotations/label_set'),
  Legend: require('./annotations/legend'),
  LegendItem: require('./annotations/legend_item'),
  PolyAnnotation: require('./annotations/poly_annotation'),
  Span: require('./annotations/span'),
  Title: require('./annotations/title'),
  Tooltip: require('./annotations/tooltip'),
  OpenHead: require('./annotations/arrow_head').OpenHead,
  NormalHead: require('./annotations/arrow_head').NormalHead,
  VeeHead: require('./annotations/arrow_head').VeeHead,
  CategoricalAxis: require('./axes/categorical_axis'),
  DatetimeAxis: require('./axes/datetime_axis'),
  LinearAxis: require('./axes/linear_axis'),
  LogAxis: require('./axes/log_axis'),
  CustomJS: require('./callbacks/customjs'),
  OpenURL: require('./callbacks/open_url'),
  BasicTickFormatter: require('./formatters/basic_tick_formatter'),
  CategoricalTickFormatter: require('./formatters/categorical_tick_formatter'),
  DatetimeTickFormatter: require('./formatters/datetime_tick_formatter'),
  LogTickFormatter: require('./formatters/log_tick_formatter'),
  FuncTickFormatter: require('./formatters/func_tick_formatter'),
  NumeralTickFormatter: require('./formatters/numeral_tick_formatter'),
  PrintfTickFormatter: require('./formatters/printf_tick_formatter'),
  AnnularWedge: require('./glyphs/annular_wedge'),
  Annulus: require('./glyphs/annulus'),
  Arc: require('./glyphs/arc'),
  Bezier: require('./glyphs/bezier'),
  Circle: require('./glyphs/circle'),
  Ellipse: require('./glyphs/ellipse'),
  HBar: require('./glyphs/hbar'),
  Image: require('./glyphs/image'),
  ImageRGBA: require('./glyphs/image_rgba'),
  ImageURL: require('./glyphs/image_url'),
  Line: require('./glyphs/line'),
  MultiLine: require('./glyphs/multi_line'),
  Oval: require('./glyphs/oval'),
  Patch: require('./glyphs/patch'),
  Patches: require('./glyphs/patches'),
  Quad: require('./glyphs/quad'),
  Quadratic: require('./glyphs/quadratic'),
  Ray: require('./glyphs/ray'),
  Rect: require('./glyphs/rect'),
  Segment: require('./glyphs/segment'),
  Text: require('./glyphs/text'),
  VBar: require('./glyphs/vbar'),
  Wedge: require('./glyphs/wedge'),
  Grid: require('./grids/grid'),
  Column: require('./layouts/column'),
  Row: require('./layouts/row'),
  Spacer: require('./layouts/spacer'),
  WidgetBox: require('./layouts/widget_box'),
  CategoricalMapper: require('./mappers/categorical_mapper'),
  CategoricalColorMapper: require('./mappers/categorical_color_mapper'),
  GridMapper: require('./mappers/grid_mapper'),
  LinearColorMapper: require('./mappers/linear_color_mapper'),
  LinearMapper: require('./mappers/linear_mapper'),
  LogColorMapper: require('./mappers/log_color_mapper'),
  LogMapper: require('./mappers/log_mapper'),
  Transform: require('./transforms/transform'),
  Jitter: require('./transforms/jitter'),
  Interpolator: require('./transforms/interpolator'),
  LinearInterpolator: require('./transforms/linear_interpolator'),
  StepInterpolator: require('./transforms/step_interpolator'),
  Asterisk: require('./markers/index').Asterisk,
  CircleCross: require('./markers/index').CircleCross,
  CircleX: require('./markers/index').CircleX,
  Cross: require('./markers/index').Cross,
  Diamond: require('./markers/index').Diamond,
  DiamondCross: require('./markers/index').DiamondCross,
  InvertedTriangle: require('./markers/index').InvertedTriangle,
  Square: require('./markers/index').Square,
  SquareCross: require('./markers/index').SquareCross,
  SquareX: require('./markers/index').SquareX,
  Triangle: require('./markers/index').Triangle,
  X: require('./markers/index').X,
  Plot: require('./plots/plot'),
  GMapPlot: require('./plots/gmap_plot'),
  DataRange1d: require('./ranges/data_range1d'),
  FactorRange: require('./ranges/factor_range'),
  Range1d: require('./ranges/range1d'),
  GlyphRenderer: require('./renderers/glyph_renderer'),
  AjaxDataSource: require('./sources/ajax_data_source'),
  ColumnDataSource: require('./sources/column_data_source'),
  GeoJSONDataSource: require('./sources/geojson_data_source'),
  AdaptiveTicker: require('./tickers/adaptive_ticker'),
  BasicTicker: require('./tickers/basic_ticker'),
  CategoricalTicker: require('./tickers/categorical_ticker'),
  CompositeTicker: require('./tickers/composite_ticker'),
  ContinuousTicker: require('./tickers/continuous_ticker'),
  DatetimeTicker: require('./tickers/datetime_ticker'),
  DaysTicker: require('./tickers/days_ticker'),
  FixedTicker: require('./tickers/fixed_ticker'),
  LogTicker: require('./tickers/log_ticker'),
  MonthsTicker: require('./tickers/months_ticker'),
  SingleIntervalTicker: require('./tickers/single_interval_ticker'),
  YearsTicker: require('./tickers/years_ticker'),
  TileRenderer: require('./tiles/tile_renderer'),
  TileSource: require('./tiles/tile_source'),
  TMSTileSource: require('./tiles/tms_tile_source'),
  WMTSTileSource: require('./tiles/wmts_tile_source'),
  QUADKEYTileSource: require('./tiles/quadkey_tile_source'),
  BBoxTileSource: require('./tiles/bbox_tile_source'),
  DynamicImageRenderer: require('./tiles/dynamic_image_renderer'),
  ImageSource: require('./tiles/image_source'),
  ToolEvents: require('./tools/tool_events'),
  Toolbar: require('./tools/toolbar'),
  ToolbarBox: require('./tools/toolbar_box'),
  ButtonTool: require('./tools/button_tool'),
  ActionTool: require('./tools/actions/action_tool'),
  ZoomInTool: require('./tools/actions/zoom_in_tool'),
  ZoomOutTool: require('./tools/actions/zoom_out_tool'),
  SaveTool: require('./tools/actions/save_tool'),
  UndoTool: require('./tools/actions/undo_tool'),
  RedoTool: require('./tools/actions/redo_tool'),
  ResetTool: require('./tools/actions/reset_tool'),
  HelpTool: require('./tools/actions/help_tool'),
  BoxSelectTool: require('./tools/gestures/box_select_tool'),
  BoxZoomTool: require('./tools/gestures/box_zoom_tool'),
  GestureTool: require('./tools/gestures/gesture_tool'),
  LassoSelectTool: require('./tools/gestures/lasso_select_tool'),
  PanTool: require('./tools/gestures/pan_tool'),
  PolySelectTool: require('./tools/gestures/poly_select_tool'),
  SelectTool: require('./tools/gestures/select_tool'),
  ResizeTool: require('./tools/gestures/resize_tool'),
  TapTool: require('./tools/gestures/tap_tool'),
  WheelPanTool: require('./tools/gestures/wheel_pan_tool'),
  WheelZoomTool: require('./tools/gestures/wheel_zoom_tool'),
  CrosshairTool: require('./tools/inspectors/crosshair_tool'),
  HoverTool: require('./tools/inspectors/hover_tool'),
  InspectTool: require('./tools/inspectors/inspect_tool')
};

},{"./annotations/arrow":"models/annotations/arrow","./annotations/arrow_head":"models/annotations/arrow_head","./annotations/box_annotation":"models/annotations/box_annotation","./annotations/color_bar":"models/annotations/color_bar","./annotations/label":"models/annotations/label","./annotations/label_set":"models/annotations/label_set","./annotations/legend":"models/annotations/legend","./annotations/legend_item":"models/annotations/legend_item","./annotations/poly_annotation":"models/annotations/poly_annotation","./annotations/span":"models/annotations/span","./annotations/title":"models/annotations/title","./annotations/tooltip":"models/annotations/tooltip","./axes/categorical_axis":"models/axes/categorical_axis","./axes/datetime_axis":"models/axes/datetime_axis","./axes/linear_axis":"models/axes/linear_axis","./axes/log_axis":"models/axes/log_axis","./callbacks/customjs":"models/callbacks/customjs","./callbacks/open_url":"models/callbacks/open_url","./formatters/basic_tick_formatter":"models/formatters/basic_tick_formatter","./formatters/categorical_tick_formatter":"models/formatters/categorical_tick_formatter","./formatters/datetime_tick_formatter":"models/formatters/datetime_tick_formatter","./formatters/func_tick_formatter":"models/formatters/func_tick_formatter","./formatters/log_tick_formatter":"models/formatters/log_tick_formatter","./formatters/numeral_tick_formatter":"models/formatters/numeral_tick_formatter","./formatters/printf_tick_formatter":"models/formatters/printf_tick_formatter","./glyphs/annular_wedge":"models/glyphs/annular_wedge","./glyphs/annulus":"models/glyphs/annulus","./glyphs/arc":"models/glyphs/arc","./glyphs/bezier":"models/glyphs/bezier","./glyphs/circle":"models/glyphs/circle","./glyphs/ellipse":"models/glyphs/ellipse","./glyphs/hbar":"models/glyphs/hbar","./glyphs/image":"models/glyphs/image","./glyphs/image_rgba":"models/glyphs/image_rgba","./glyphs/image_url":"models/glyphs/image_url","./glyphs/line":"models/glyphs/line","./glyphs/multi_line":"models/glyphs/multi_line","./glyphs/oval":"models/glyphs/oval","./glyphs/patch":"models/glyphs/patch","./glyphs/patches":"models/glyphs/patches","./glyphs/quad":"models/glyphs/quad","./glyphs/quadratic":"models/glyphs/quadratic","./glyphs/ray":"models/glyphs/ray","./glyphs/rect":"models/glyphs/rect","./glyphs/segment":"models/glyphs/segment","./glyphs/text":"models/glyphs/text","./glyphs/vbar":"models/glyphs/vbar","./glyphs/wedge":"models/glyphs/wedge","./grids/grid":"models/grids/grid","./layouts/column":"models/layouts/column","./layouts/row":"models/layouts/row","./layouts/spacer":"models/layouts/spacer","./layouts/widget_box":"models/layouts/widget_box","./mappers/categorical_color_mapper":"models/mappers/categorical_color_mapper","./mappers/categorical_mapper":"models/mappers/categorical_mapper","./mappers/grid_mapper":"models/mappers/grid_mapper","./mappers/linear_color_mapper":"models/mappers/linear_color_mapper","./mappers/linear_mapper":"models/mappers/linear_mapper","./mappers/log_color_mapper":"models/mappers/log_color_mapper","./mappers/log_mapper":"models/mappers/log_mapper","./markers/index":"models/markers/index","./plots/gmap_plot":"models/plots/gmap_plot","./plots/plot":"models/plots/plot","./ranges/data_range1d":"models/ranges/data_range1d","./ranges/factor_range":"models/ranges/factor_range","./ranges/range1d":"models/ranges/range1d","./renderers/glyph_renderer":"models/renderers/glyph_renderer","./sources/ajax_data_source":"models/sources/ajax_data_source","./sources/column_data_source":"models/sources/column_data_source","./sources/geojson_data_source":"models/sources/geojson_data_source","./tickers/adaptive_ticker":"models/tickers/adaptive_ticker","./tickers/basic_ticker":"models/tickers/basic_ticker","./tickers/categorical_ticker":"models/tickers/categorical_ticker","./tickers/composite_ticker":"models/tickers/composite_ticker","./tickers/continuous_ticker":"models/tickers/continuous_ticker","./tickers/datetime_ticker":"models/tickers/datetime_ticker","./tickers/days_ticker":"models/tickers/days_ticker","./tickers/fixed_ticker":"models/tickers/fixed_ticker","./tickers/log_ticker":"models/tickers/log_ticker","./tickers/months_ticker":"models/tickers/months_ticker","./tickers/single_interval_ticker":"models/tickers/single_interval_ticker","./tickers/years_ticker":"models/tickers/years_ticker","./tiles/bbox_tile_source":"models/tiles/bbox_tile_source","./tiles/dynamic_image_renderer":"models/tiles/dynamic_image_renderer","./tiles/image_source":"models/tiles/image_source","./tiles/quadkey_tile_source":"models/tiles/quadkey_tile_source","./tiles/tile_renderer":"models/tiles/tile_renderer","./tiles/tile_source":"models/tiles/tile_source","./tiles/tms_tile_source":"models/tiles/tms_tile_source","./tiles/wmts_tile_source":"models/tiles/wmts_tile_source","./tools/actions/action_tool":"models/tools/actions/action_tool","./tools/actions/help_tool":"models/tools/actions/help_tool","./tools/actions/redo_tool":"models/tools/actions/redo_tool","./tools/actions/reset_tool":"models/tools/actions/reset_tool","./tools/actions/save_tool":"models/tools/actions/save_tool","./tools/actions/undo_tool":"models/tools/actions/undo_tool","./tools/actions/zoom_in_tool":"models/tools/actions/zoom_in_tool","./tools/actions/zoom_out_tool":"models/tools/actions/zoom_out_tool","./tools/button_tool":"models/tools/button_tool","./tools/gestures/box_select_tool":"models/tools/gestures/box_select_tool","./tools/gestures/box_zoom_tool":"models/tools/gestures/box_zoom_tool","./tools/gestures/gesture_tool":"models/tools/gestures/gesture_tool","./tools/gestures/lasso_select_tool":"models/tools/gestures/lasso_select_tool","./tools/gestures/pan_tool":"models/tools/gestures/pan_tool","./tools/gestures/poly_select_tool":"models/tools/gestures/poly_select_tool","./tools/gestures/resize_tool":"models/tools/gestures/resize_tool","./tools/gestures/select_tool":"models/tools/gestures/select_tool","./tools/gestures/tap_tool":"models/tools/gestures/tap_tool","./tools/gestures/wheel_pan_tool":"models/tools/gestures/wheel_pan_tool","./tools/gestures/wheel_zoom_tool":"models/tools/gestures/wheel_zoom_tool","./tools/inspectors/crosshair_tool":"models/tools/inspectors/crosshair_tool","./tools/inspectors/hover_tool":"models/tools/inspectors/hover_tool","./tools/inspectors/inspect_tool":"models/tools/inspectors/inspect_tool","./tools/tool_events":"models/tools/tool_events","./tools/toolbar":"models/tools/toolbar","./tools/toolbar_box":"models/tools/toolbar_box","./transforms/interpolator":"models/transforms/interpolator","./transforms/jitter":"models/transforms/jitter","./transforms/linear_interpolator":"models/transforms/linear_interpolator","./transforms/step_interpolator":"models/transforms/step_interpolator","./transforms/transform":"models/transforms/transform"}],"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.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("../../core/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
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/build_views":"core/build_views","../../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("../../core/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
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/build_views":"core/build_views","../../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_color_mapper":[function(require,module,exports){
var CategoricalColorMapper, ColorMapper, _, 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");

ColorMapper = require("./color_mapper");

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

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

  CategoricalColorMapper.prototype.type = "CategoricalColorMapper";

  CategoricalColorMapper.define({
    factors: [p.Array]
  });

  CategoricalColorMapper.prototype._get_values = function(data, palette) {
    var color, d, i, key, len, values;
    values = [];
    for (i = 0, len = data.length; i < len; i++) {
      d = data[i];
      key = this.factors.indexOf(d);
      if (key < 0 || key >= palette.length) {
        color = this.nan_color;
      } else {
        color = palette[key];
      }
      values.push(color);
    }
    return values;
  };

  return CategoricalColorMapper;

})(ColorMapper.Model);

module.exports = {
  Model: CategoricalColorMapper
};

},{"../../core/properties":"core/properties","./color_mapper":"models/mappers/color_mapper","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.source_range;
    factors = range.factors;
    if (x.indexOf(':') >= 0) {
      ref = x.split(':'), factor = ref[0], percent = ref[1];
      percent = parseFloat(percent);
      result = factors.indexOf(factor) + 0.5 + range.offset + percent;
    } else {
      result = factors.indexOf(x) + 1 + range.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.source_range;
    factors = range.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.offset + percent;
      } else {
        results[i] = factors.indexOf(x) + 1 + range.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.source_range;
    factors = range.factors;
    return factors[Math.floor(xprime - 0.5 - range.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.source_range;
    factors = range.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.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, _, 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");

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

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

  ColorMapper.prototype.type = "ColorMapper";

  ColorMapper.define({
    palette: [p.Any],
    nan_color: [p.Color, "gray"]
  });

  ColorMapper.prototype.initialize = function(attrs, options) {
    ColorMapper.__super__.initialize.call(this, attrs, options);
    this._little_endian = this._is_little_endian();
    this._palette = this._build_palette(this.palette);
    return this.listenTo(this, 'change', function() {
      return this._palette = this._build_palette(this.palette);
    });
  };

  ColorMapper.prototype.v_map_screen = function(data) {
    var buf, color, i, j, k, ref, ref1, value, values;
    values = this._get_values(data, this._palette);
    buf = new ArrayBuffer(data.length * 4);
    color = new Uint32Array(buf);
    if (this._little_endian) {
      for (i = j = 0, ref = data.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
        value = values[i];
        color[i] = (0xff << 24) | ((value & 0xff0000) >> 16) | (value & 0xff00) | ((value & 0xff) << 16);
      }
    } else {
      for (i = k = 0, ref1 = data.length; 0 <= ref1 ? k < ref1 : k > ref1; i = 0 <= ref1 ? ++k : --k) {
        value = values[i];
        color[i] = (value << 8) | 0xff;
      }
    }
    return buf;
  };

  ColorMapper.prototype.compute = function(x) {
    return null;
  };

  ColorMapper.prototype.v_compute = function(xs) {
    var values;
    values = this._get_values(xs, this.palette);
    return values;
  };

  ColorMapper.prototype._get_values = function(data, palette) {
    return [];
  };

  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);
    _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]);
    }
    return new_palette;
  };

  return ColorMapper;

})(Model);

module.exports = {
  Model: ColorMapper
};

},{"../../core/properties":"core/properties","../../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.domain_mapper.map_to_target(x);
    yprime = this.codomain_mapper.map_to_target(y);
    return [xprime, yprime];
  };

  GridMapper.prototype.v_map_to_target = function(xs, ys) {
    var xprimes, yprimes;
    xprimes = this.domain_mapper.v_map_to_target(xs);
    yprimes = this.codomain_mapper.v_map_to_target(ys);
    return [xprimes, yprimes];
  };

  GridMapper.prototype.map_from_target = function(xprime, yprime) {
    var x, y;
    x = this.domain_mapper.map_from_target(xprime);
    y = this.codomain_mapper.map_from_target(yprime);
    return [x, y];
  };

  GridMapper.prototype.v_map_from_target = function(xprimes, yprimes) {
    var xs, ys;
    xs = this.domain_mapper.v_map_from_target(xprimes);
    ys = this.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");

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

ColorMapper = require("./color_mapper");

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],
    high_color: [p.Color],
    low_color: [p.Color]
  });

  LinearColorMapper.prototype._get_values = function(data, palette) {
    var d, high, i, key, len, low, max_key, norm_factor, normed_d, normed_interval, ref, ref1, values;
    low = (ref = this.low) != null ? ref : _.min(data);
    high = (ref1 = this.high) != null ? ref1 : _.max(data);
    max_key = palette.length - 1;
    values = [];
    norm_factor = 1 / (high - low);
    normed_interval = 1 / palette.length;
    for (i = 0, len = data.length; i < len; i++) {
      d = data[i];
      if (isNaN(d)) {
        values.push(this.nan_color);
        continue;
      }
      if (d === high) {
        values.push(palette[max_key]);
        continue;
      }
      normed_d = (d - low) * norm_factor;
      key = Math.floor(normed_d / normed_interval);
      if (key < 0) {
        if (this.low_color != null) {
          values.push(this.low_color);
        } else {
          values.push(palette[0]);
        }
      } else if (key > max_key) {
        if (this.high_color != null) {
          values.push(this.high_color);
        } else {
          values.push(palette[max_key]);
        }
      } else {
        values.push(palette[key]);
      }
    }
    return values;
  };

  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.source_range, ['start', 'end']);
    return this.add_dependencies('mapper_state', this.target_range, ['start', 'end']);
  };

  LinearMapper.getters({
    mapper_state: function() {
      return this._get_computed('mapper_state');
    }
  });

  LinearMapper.prototype.map_to_target = function(x) {
    var offset, ref, scale;
    ref = this.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.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.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.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.source_range.start;
    source_end = this.source_range.end;
    target_start = this.target_range.start;
    target_end = this.target_range.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, _, log1p, 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");

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

ColorMapper = require("./color_mapper");

log1p = (ref = Math.log1p) != null ? ref : function(x) {
  return Math.log(1 + x);
};

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],
    high_color: [p.Color],
    low_color: [p.Color]
  });

  LogColorMapper.prototype._get_values = function(data, palette) {
    var d, high, i, key, len, log, low, max_key, n, ref1, ref2, scale, values;
    n = palette.length;
    low = (ref1 = this.low) != null ? ref1 : _.min(data);
    high = (ref2 = this.high) != null ? ref2 : _.max(data);
    scale = n / (log1p(high) - log1p(low));
    max_key = palette.length - 1;
    values = [];
    for (i = 0, len = data.length; i < len; i++) {
      d = data[i];
      if (isNaN(d)) {
        values.push(this.nan_color);
        continue;
      }
      if (d > high) {
        if (this.high_color != null) {
          values.push(this.high_color);
        } else {
          values.push(palette[max_key]);
        }
        continue;
      }
      if (d === high) {
        values.push(palette[max_key]);
        continue;
      }
      if (d < low) {
        if (this.low_color != null) {
          values.push(this.low_color);
        } else {
          values.push(palette[0]);
        }
        continue;
      }
      log = log1p(d) - log1p(low);
      key = Math.floor(log * scale);
      if (key > max_key) {
        key = max_key;
      }
      values.push(palette[key]);
    }
    return values;
  };

  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.source_range, ['start', 'end']);
    return this.add_dependencies('mapper_state', this.target_range, ['start', 'end']);
  };

  LogMapper.getters({
    mapper_state: function() {
      return this._get_computed('mapper_state');
    }
  });

  LogMapper.prototype.map_to_target = function(x) {
    var inter_offset, inter_scale, intermediate, offset, ref, result, scale;
    ref = this.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.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.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.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.source_range.start;
    source_end = this.source_range.end;
    target_start = this.target_range.start;
    target_end = this.target_range.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/index":[function(require,module,exports){
var M, SQ3, _one_cross, _one_diamond, _one_tri, _one_x, asterisk, circle_cross, circle_x, cross, diamond, diamond_cross, generate_marker, inverted_triangle, square, square_cross, square_x, triangle, x,
  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;

M = require("./marker");

SQ3 = Math.sqrt(3);

generate_marker = function(type, f) {
  var Model, View;
  View = (function(superClass) {
    extend(View, superClass);

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

    View.prototype._render_one = f;

    return View;

  })(M.View);
  Model = (function(superClass) {
    extend(Model, superClass);

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

    Model.prototype.default_view = View;

    Model.prototype.type = type;

    return Model;

  })(M.Model);
  return {
    Model: Model,
    View: View
  };
};

_one_x = function(ctx, r) {
  ctx.moveTo(-r, r);
  ctx.lineTo(r, -r);
  ctx.moveTo(-r, -r);
  return ctx.lineTo(r, r);
};

_one_cross = function(ctx, r) {
  ctx.moveTo(0, r);
  ctx.lineTo(0, -r);
  ctx.moveTo(-r, 0);
  return ctx.lineTo(r, 0);
};

_one_diamond = function(ctx, r) {
  ctx.moveTo(0, r);
  ctx.lineTo(r / 1.5, 0);
  ctx.lineTo(0, -r);
  ctx.lineTo(-r / 1.5, 0);
  return ctx.closePath();
};

_one_tri = function(ctx, r) {
  var a, h;
  h = r * SQ3;
  a = h / 3;
  ctx.moveTo(-r, a);
  ctx.lineTo(r, a);
  ctx.lineTo(0, a - h);
  return ctx.closePath();
};

asterisk = function(ctx, i, sx, sy, r, line, fill) {
  var r2;
  r2 = r * 0.65;
  _one_cross(ctx, r);
  _one_x(ctx, r2);
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

circle_cross = function(ctx, i, sx, sy, r, line, fill) {
  ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    _one_cross(ctx, r);
    ctx.stroke();
  }
};

circle_x = function(ctx, i, sx, sy, r, line, fill) {
  ctx.arc(0, 0, r, 0, 2 * Math.PI, false);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    _one_x(ctx, r);
    ctx.stroke();
  }
};

cross = function(ctx, i, sx, sy, r, line, fill) {
  _one_cross(ctx, r);
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

diamond = function(ctx, i, sx, sy, r, line, fill) {
  _one_diamond(ctx, r);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

diamond_cross = function(ctx, i, sx, sy, r, line, fill) {
  _one_diamond(ctx, r);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    _one_cross(ctx, r);
    ctx.stroke();
  }
};

inverted_triangle = function(ctx, i, sx, sy, r, line, fill) {
  ctx.rotate(Math.PI);
  _one_tri(ctx, r);
  ctx.rotate(-Math.PI);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

square = function(ctx, i, sx, sy, r, line, fill) {
  var size;
  size = 2 * r;
  ctx.rect(-r, -r, size, size);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

square_cross = function(ctx, i, sx, sy, r, line, fill) {
  var size;
  size = 2 * r;
  ctx.rect(-r, -r, size, size);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    _one_cross(ctx, r);
    ctx.stroke();
  }
};

square_x = function(ctx, i, sx, sy, r, line, fill) {
  var size;
  size = 2 * r;
  ctx.rect(-r, -r, size, size);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    _one_x(ctx, r);
    ctx.stroke();
  }
};

triangle = function(ctx, i, sx, sy, r, line, fill) {
  _one_tri(ctx, r);
  if (fill.doit) {
    fill.set_vectorize(ctx, i);
    ctx.fill();
  }
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

x = function(ctx, i, sx, sy, r, line, fill) {
  _one_x(ctx, r);
  if (line.doit) {
    line.set_vectorize(ctx, i);
    ctx.stroke();
  }
};

module.exports = {
  Asterisk: generate_marker('Asterisk', asterisk),
  CircleCross: generate_marker('CircleCross', circle_cross),
  CircleX: generate_marker('CircleX', circle_x),
  Cross: generate_marker('Cross', cross),
  Diamond: generate_marker('Diamond', diamond),
  DiamondCross: generate_marker('DiamondCross', diamond_cross),
  InvertedTriangle: generate_marker('InvertedTriangle', inverted_triangle),
  Square: generate_marker('Square', square),
  SquareCross: generate_marker('SquareCross', square_cross),
  SquareX: generate_marker('SquareX', square_x),
  Triangle: generate_marker('Triangle', triangle),
  X: generate_marker('X', x)
};

},{"./marker":"models/markers/marker"}],"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("../../core/hittest");

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

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

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

  MarkerView.prototype.draw_legend_for_index = function(ctx, x0, x1, y0, y1, index) {
    var angle, data, indices, size, sx, sy;
    indices = [index];
    sx = {};
    sx[index] = (x0 + x1) / 2;
    sy = {};
    sy[index] = (y0 + y1) / 2;
    size = {};
    size[index] = Math.min(Math.abs(x1 - x0), Math.abs(y1 - y0)) * 0.4;
    angle = {};
    angle[index] = 0;
    data = {
      sx: sx,
      sy: sy,
      _size: size,
      _angle: angle
    };
    return this._render(ctx, indices, data);
  };

  MarkerView.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]);
      }
      this._render_one(ctx, i, sx[i], sy[i], r, this.visuals.line, this.visuals.fill);
      if (_angle[i]) {
        ctx.rotate(-_angle[i]);
      }
      results.push(ctx.translate(-sx[i], -sy[i]));
    }
    return results;
  };

  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.h_range;
    vx0 = hr.start - this.max_size;
    vx1 = hr.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.v_range;
    vy0 = vr.start - this.max_size;
    vy1 = vr.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
};

},{"../../core/hittest":"core/hittest","../../core/properties":"core/properties","../glyphs/glyph":"models/glyphs/glyph","underscore":"underscore"}],"models/plots/gmap_plot":[function(require,module,exports){
var GMapPlot, GMapPlotCanvas, GMapPlotView, Plot, _, 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;

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","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("../../core/util/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.setv({
      start: proj_xstart,
      end: proj_xend
    });
    return this.y_range.setv({
      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.width;
    height = this.frame.height;
    left = this.canvas.vx_to_sx(this.frame.left);
    top = this.canvas.vy_to_sy(this.frame.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.width;
    oh = this.canvas.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","../../core/util/proj4":"core/util/proj4","./plot_canvas":"models/plots/plot_canvas","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("../tools/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.plots;
      if (_.isArray(plots)) {
        plots = plots.concat(this);
        xr.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.plots;
      if (_.isArray(plots)) {
        plots = plots.concat(this);
        yr.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;
    }
  };

  Plot.getter("plot_canvas", 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.getv(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.renderers;
    renderers = renderers.concat(new_renderers);
    return this.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.getv(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"
  });

  Plot.getters({
    all_renderers: function() {
      var i, len, ref1, renderers, tool;
      renderers = this.renderers;
      ref1 = this.toolbar.tools;
      for (i = 0, len = ref1.length; i < len; i++) {
        tool = ref1[i];
        renderers = renderers.concat(tool.synthetic_renderers);
      }
      return renderers;
    }
  });

  return Plot;

})(LayoutDOM.Model);

module.exports = {
  View: PlotView,
  Model: Plot
};

},{"../../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/tool_events":"models/tools/tool_events","../tools/toolbar":"models/tools/toolbar","./plot_canvas":"models/plots/plot_canvas","underscore":"underscore"}],"models/plots/plot_canvas":[function(require,module,exports){
var $, BokehView, Canvas, CartesianFrame, DataRange1d, EQ, GE, GlyphRenderer, LayoutCanvas, LayoutDOM, PlotCanvas, PlotCanvasView, UIEvents, Visuals, _, 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");

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

UIEvents = require("../../core/ui_events").UIEvents;

LayoutCanvas = require("../../core/layout/layout_canvas");

Visuals = require("../../core/visuals").Visuals;

BokehView = require("../../core/bokeh_view");

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

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

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

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_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, len, level, ref1;
    PlotCanvasView.__super__.initialize.call(this, options);
    this.pause();
    this.visuals = new Visuals(this.model.plot);
    this._initial_state_info = {
      range: null,
      selection: {},
      dimensions: {
        width: this.model.canvas.width,
        height: this.model.canvas.height
      }
    };
    this.frame = this.model.frame;
    this.x_range = this.frame.x_ranges['default'];
    this.y_range = this.frame.y_ranges['default'];
    this.xmapper = this.frame.x_mappers['default'];
    this.ymapper = this.frame.y_mappers['default'];
    this.canvas = this.model.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(this.model.toolbar, this.canvas_view.$el);
    this.levels = {};
    ref1 = enums.RenderLevel;
    for (j = 0, len = ref1.length; j < len; j++) {
      level = ref1[j];
      this.levels[level] = {};
    }
    this.renderer_views = {};
    this.tool_views = {};
    this.build_levels();
    this.build_tools();
    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.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.follow) {
          follow_enabled = true;
        }
      }
      if (xr.bounds != null) {
        has_bounds = true;
      }
    }
    ref4 = _.values(frame.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.follow) {
          follow_enabled = true;
        }
      }
      if (yr.bounds != null) {
        has_bounds = true;
      }
    }
    if (follow_enabled && has_bounds) {
      logger.warn('Follow enabled so bounds are unset.');
      ref5 = _.values(frame.x_ranges);
      for (m = 0, len2 = ref5.length; m < len2; m++) {
        xr = ref5[m];
        xr.bounds = null;
      }
      ref6 = _.values(frame.y_ranges);
      for (n = 0, len3 = ref6.length; n < len3; n++) {
        yr = ref6[n];
        yr.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.data_source.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.data_source;
      if (selection != null) {
        if (ref2 = renderer.id, indexOf.call(selection, ref2) >= 0) {
          results.push(ds.selected = selection[renderer.id]);
        } else {
          results.push(void 0);
        }
      } else {
        results.push(ds.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.start;
        results.push(range_info['end'] = weight * range_info['end'] + (1 - weight) * rng.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.start > rng.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.start;
          range_info['end'] = weight * range_info['end'] + (1 - weight) * rng.end;
        }
      }
      if (rng.bounds != null) {
        min = rng.bounds[0];
        max = rng.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.start !== range_info['start'] || rng.end !== range_info['end']) {
        rng.setv(range_info);
        results.push((ref3 = rng.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.min_interval;
    max_interval = rng.max_interval;
    weight = 1.0;
    if (rng.bounds != null) {
      ref1 = rng.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.end - rng.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.x_ranges;
      for (name in ref1) {
        rng = ref1[name];
        rng.reset();
        if ((ref2 = rng.callback) != null) {
          ref2.execute(rng);
        }
      }
      ref3 = this.frame.y_ranges;
      for (name in ref3) {
        rng = ref3[name];
        rng.reset();
        if ((ref4 = rng.callback) != null) {
          ref4.execute(rng);
        }
      }
      this.update_dataranges();
    } else {
      range_info_iter = [];
      ref5 = this.frame.x_ranges;
      for (name in ref5) {
        rng = ref5[name];
        range_info_iter.push([rng, range_info.xrs[name]]);
      }
      ref6 = this.frame.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, new_renderer_views, old_renderers, renderer_models, renderers_to_remove, view;
    renderer_models = this.model.plot.all_renderers;
    old_renderers = _.keys(this.renderer_views);
    new_renderer_views = build_views(this.renderer_views, renderer_models, this.view_options());
    renderers_to_remove = _.difference(old_renderers, _.pluck(renderer_models, 'id'));
    for (j = 0, len = renderers_to_remove.length; j < len; j++) {
      id_ = renderers_to_remove[j];
      delete this.levels.glyph[id_];
    }
    for (l = 0, len1 = new_renderer_views.length; l < len1; l++) {
      view = new_renderer_views[l];
      this.levels[view.model.level][view.model.id] = view;
      view.bind_bokeh_events();
    }
    return this;
  };

  PlotCanvasView.prototype.build_tools = function() {
    var j, len, new_tool_views, results, tool_models, tool_view;
    tool_models = this.model.plot.toolbar.tools;
    new_tool_views = build_views(this.tool_views, tool_models, this.view_options());
    results = [];
    for (j = 0, len = new_tool_views.length; j < len; j++) {
      tool_view = new_tool_views[j];
      tool_view.bind_bokeh_events();
      results.push(this.ui_event_bus.register_tool(tool_view));
    }
    return results;
  };

  PlotCanvasView.prototype.bind_bokeh_events = function() {
    var name, ref1, ref2, rng;
    ref1 = this.model.frame.x_ranges;
    for (name in ref1) {
      rng = ref1[name];
      this.listenTo(rng, 'change', this.request_render);
    }
    ref2 = this.model.frame.y_ranges;
    for (name in ref2) {
      rng = ref2[name];
      this.listenTo(rng, 'change', this.request_render);
    }
    this.listenTo(this.model.plot, 'change:renderers', (function(_this) {
      return function() {
        return _this.build_levels();
      };
    })(this));
    this.listenTo(this.model.plot.toolbar, 'change:tools', (function(_this) {
      return function() {
        _this.build_levels();
        return _this.build_tools();
      };
    })(this));
    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.x_ranges;
    for (name in ref1) {
      rng = ref1[name];
      if ((rng.start == null) || (rng.end == null) || _.isNaN(rng.start + rng.end)) {
        good_vals = false;
        break;
      }
      xrs[name] = {
        start: rng.start,
        end: rng.end
      };
    }
    if (good_vals) {
      yrs = {};
      ref2 = this.frame.y_ranges;
      for (name in ref2) {
        rng = ref2[name];
        if ((rng.start == null) || (rng.end == null) || _.isNaN(rng.start + rng.end)) {
          good_vals = false;
          break;
        }
        yrs[name] = {
          start: rng.start,
          end: rng.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.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.left), this.canvas.vy_to_sy(this.frame.top), this.frame.width, this.frame.height];
    this._map_hook(ctx, frame_box);
    this._paint_empty(ctx, frame_box);
    this.prepare_webgl(ratio, frame_box);
    ctx.save();
    if (this.visuals.outline_line.doit) {
      this.visuals.outline_line.set_value(ctx);
      ctx.strokeRect.apply(ctx, frame_box);
    }
    ctx.restore();
    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']);
    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 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.width - 1);
    s.suggest_value(this.frame._height, this.canvas.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) {
    ctx.clearRect(0, 0, this.canvas_view.model.width, this.canvas_view.model.height);
    if (this.visuals.border_fill.doit) {
      this.visuals.border_fill.set_value(ctx);
      ctx.fillRect(0, 0, this.canvas_view.model.width, this.canvas_view.model.height);
      ctx.clearRect.apply(ctx, frame_box);
    }
    if (this.visuals.background_fill.doit) {
      this.visuals.background_fill.set_value(ctx);
      return ctx.fillRect.apply(ctx, frame_box);
    }
  };

  return PlotCanvasView;

})(BokehView);

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, collect_panels;
    children = [this.above_panel, this.below_panel, this.left_panel, this.right_panel, this.canvas, this.frame];
    collect_panels = function(layout_renderers) {
      var j, len, r, results;
      results = [];
      for (j = 0, len = layout_renderers.length; j < len; j++) {
        r = layout_renderers[j];
        if (r.panel != null) {
          results.push(children.push(r.panel));
        } else {
          results.push(void 0);
        }
      }
      return results;
    };
    collect_panels(this.plot.above);
    collect_panels(this.plot.below);
    collect_panels(this.plot.left);
    collect_panels(this.plot.right);
    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 constraint, constraints, j, l, last, layout_renderers, len, len1, r, ref1, side, sides;
    constraints = [];
    sides = [['above', this.plot.above], ['below', this.plot.below], ['left', this.plot.left], ['right', this.plot.right]];
    for (j = 0, len = sides.length; j < len; j++) {
      ref1 = sides[j], side = ref1[0], layout_renderers = ref1[1];
      last = this.frame;
      for (l = 0, len1 = layout_renderers.length; l < len1; l++) {
        r = layout_renderers[l];
        constraint = (function() {
          switch (side) {
            case "above":
              return EQ(last.panel._top, [-1, r.panel._bottom]);
            case "below":
              return EQ(last.panel._bottom, [-1, r.panel._top]);
            case "left":
              return EQ(last.panel._left, [-1, r.panel._right]);
            case "right":
              return EQ(last.panel._right, [-1, r.panel._left]);
          }
        })();
        constraints.push(constraint);
        last = r;
      }
      if (layout_renderers.length !== 0) {
        constraint = (function() {
          switch (side) {
            case "above":
              return EQ(last.panel._top, [-1, this.above_panel._top]);
            case "below":
              return EQ(last.panel._bottom, [-1, this.below_panel._bottom]);
            case "left":
              return EQ(last.panel._left, [-1, this.left_panel._left]);
            case "right":
              return EQ(last.panel._right, [-1, this.right_panel._right]);
          }
        }).call(this);
        constraints.push(constraint);
      }
    }
    return constraints;
  };

  PlotCanvas.prototype.plot_canvas = function() {
    return this;
  };

  return PlotCanvas;

})(LayoutDOM.Model);

module.exports = {
  Model: PlotCanvas,
  View: PlotCanvasView
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/build_views":"core/build_views","../../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/ui_events":"core/ui_events","../../core/util/throttle":"core/util/throttle","../../core/visuals":"core/visuals","../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","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.plot_bounds = {};
    this.have_updated_interactively = false;
    this._initial_start = this.start;
    this._initial_end = this.end;
    this._initial_range_padding = this.range_padding;
    this._initial_follow = this.follow;
    this._initial_follow_interval = this.follow_interval;
    return this._initial_default_span = this.default_span;
  };

  DataRange1d.getters({
    min: function() {
      return Math.min(this.start, this.end);
    },
    max: function() {
      return Math.max(this.start, this.end);
    }
  });

  DataRange1d.prototype.computed_renderers = function() {
    var all_renderers, i, j, len, len1, names, plot, r, ref, renderers, rs;
    names = this.names;
    renderers = this.renderers;
    if (renderers.length === 0) {
      ref = this.plots;
      for (i = 0, len = ref.length; i < len; i++) {
        plot = ref[i];
        all_renderers = plot.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.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.range_padding;
    if ((range_padding != null) && range_padding > 0) {
      if (max === min) {
        span = this.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.flipped) {
      ref2 = [end, start], start = ref2[0], end = ref2[1];
      follow_sign = -1;
    }
    follow_interval = this.follow_interval;
    if ((follow_interval != null) && Math.abs(start - end) > follow_interval) {
      if (this.follow === 'start') {
        end = start + follow_sign * follow_interval;
      } else if (this.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.start, this.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.setv(new_range);
    }
    if (this.bounds === 'auto') {
      return this.bounds = [start, end];
    }
  };

  DataRange1d.prototype.reset = function() {
    this.have_updated_interactively = false;
    return this.setv({
      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.bounds != null) && this.bounds !== 'auto') {
      this._bounds_as_factors = this.bounds;
    } else {
      this._bounds_as_factors = this.factors;
    }
    this._init();
    this.listenTo(this, 'change:factors', this._update_factors);
    return this.listenTo(this, 'change:offset', this._init);
  };

  FactorRange.getters({
    min: function() {
      return this.start;
    },
    max: function() {
      return this.end;
    }
  });

  FactorRange.prototype.reset = function() {
    return this._init();
  };

  FactorRange.prototype._update_factors = function() {
    this._bounds_as_factors = this.factors;
    return this._init();
  };

  FactorRange.prototype._init = function() {
    var end, factors, start;
    factors = this.factors;
    if ((this.bounds != null) && this.bounds !== 'auto') {
      factors = this._bounds_as_factors;
      this.factors = factors;
    }
    start = 0.5 + this.offset;
    end = factors.length + start;
    this.start = start;
    this.end = end;
    if (this.bounds != null) {
      return this.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.bounds === 'auto') {
      min = Math.min(this._initial_start, this._initial_end);
      max = Math.max(this._initial_start, this._initial_end);
      return this.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._initial_start = this.start;
    this._initial_end = this.end;
    return this._set_auto_bounds();
  };

  Range1d.getters({
    min: function() {
      return Math.min(this.start, this.end);
    },
    max: function() {
      return Math.max(this.start, this.end);
    }
  });

  Range1d.prototype.reset = function() {
    this.setv({
      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.model.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.model.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.model.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.model.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.x_mappers[this.model.x_range_name];
    this.ymapper = this.plot_view.frame.y_mappers[this.model.y_range_name];
    this.set_data(false);
    if (this.model.data_source instanceof RemoteDataSource.Model) {
      return this.model.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
    });
  };

  GlyphRendererView.prototype.bind_bokeh_events = function() {
    this.listenTo(this.model, 'change', this.request_render);
    this.listenTo(this.model.data_source, 'change', this.set_data);
    this.listenTo(this.model.data_source, 'patch', this.set_data);
    this.listenTo(this.model.data_source, 'stream', this.set_data);
    this.listenTo(this.model.data_source, 'select', this.request_render);
    if (this.hover_glyph != null) {
      this.listenTo(this.model.data_source, 'inspect', this.request_render);
    }
    return this.listenTo(this.model.glyph, 'propchange', function() {
      this.glyph.set_visuals(this.model.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.model.data_source;
    this.glyph.model.setv({
      x_range_name: this.model.x_range_name,
      y_range_name: this.model.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();
    indices = this.glyph.mask_data(this.all_indices);
    dtmask = Date.now() - tmask;
    ctx = this.plot_view.canvas_view.ctx;
    ctx.save();
    selected = this.model.data_source.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 {
        selected = [];
      }
    }
    inspected = this.model.data_source.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 {
        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.model.x_range_name, this.model.y_range_name);
  };

  GlyphRendererView.prototype.draw_legend = function(ctx, x0, x1, y0, y1, field, label) {
    var index;
    index = this.model.get_reference_point(field, label);
    return this.glyph.draw_legend_for_index(ctx, x0, x1, y0, y1, index);
  };

  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.prototype.get_reference_point = function(field, value) {
    var data, i, index;
    index = 0;
    if ((field != null) && (this.data_source.get_column != null)) {
      data = this.data_source.get_column(field);
      if (data) {
        i = data.indexOf(value);
        if (i > 0) {
          index = i;
        }
      }
    }
    return index;
  };

  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 BokehView, Model, Renderer, RendererView, Visuals, _, logger, p, proj,
  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");

BokehView = require("../../core/bokeh_view");

Visuals = require("../../core/visuals").Visuals;

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

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

proj = require("../../core/util/projections");

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

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

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

  RendererView.prototype.initialize = function(options) {
    RendererView.__super__.initialize.call(this, options);
    this.plot_view = options.plot_view;
    return this.visuals = new Visuals(this.model);
  };

  RendererView.getters({
    plot_model: function() {
      return this.plot_view.model;
    }
  });

  RendererView.prototype.request_render = function() {
    return this.plot_view.request_render();
  };

  RendererView.prototype.set_data = function(source) {
    var data, ref, ref1;
    data = this.model.materialize_dataspecs(source);
    _.extend(this, data);
    if (this.plot_model.use_map) {
      if (this._x != null) {
        ref = proj.project_xy(this._x, this._y), this._x = ref[0], this._y = ref[1];
      }
      if (this._xs != null) {
        return ref1 = proj.project_xsys(this._xs, this._ys), this._xs = ref1[0], this._ys = ref1[1], ref1;
      }
    }
  };

  RendererView.prototype.map_to_screen = function(x, y) {
    return this.plot_view.map_to_screen(x, y, this.model.x_range_name, this.model.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
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/util/projections":"core/util/projections","../../core/visuals":"core/visuals","../../model":"model","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.mode);
    if (this.polling_interval) {
      return this.interval = setInterval(this.get_data, this.polling_interval, this.mode, this.max_size, this.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.data_url,
      xhrField: {
        withCredentials: true
      },
      method: this.method,
      contentType: this.content_type,
      headers: this.http_headers
    }).done((function(_this) {
      return function(data) {
        var column, i, len, original_data, ref;
        if (mode === 'replace') {
          _this.data = data;
        } else if (mode === 'append') {
          original_data = _this.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.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("../../core/hittest");

SelectionManager = require("../../core/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.data[colname]) != null ? ref : null;
  };

  ColumnDataSource.prototype.get_length = function() {
    var data, key, lengths, val;
    data = this.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.data);
  };

  ColumnDataSource.prototype.stream = function(new_data, rollover) {
    var data, k, v;
    data = this.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.setv('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.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.setv('data', data, {
      silent: true
    });
    return this.trigger('patch');
  };

  return ColumnDataSource;

})(DataSource.Model);

module.exports = {
  Model: ColumnDataSource
};

},{"../../core/hittest":"core/hittest","../../core/logging":"core/logging","../../core/properties":"core/properties","../../core/selection_manager":"core/selection_manager","./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("../../core/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.callback;
        if (callback != null) {
          if (_.isFunction(callback)) {
            return callback(_this);
          } else {
            return callback.execute(_this);
          }
        }
      };
    })(this));
  };

  return DataSource;

})(Model);

module.exports = {
  Model: DataSource
};

},{"../../core/hittest":"core/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._update_data();
    return this.listenTo(this, 'change:geojson', (function(_this) {
      return function() {
        return _this._update_data();
      };
    })(this));
  };

  GeoJSONDataSource.prototype._update_data = function() {
    return this.data = this.geojson_to_column_data();
  };

  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 0/0;
    });
    return nan_array;
  };

  GeoJSONDataSource.prototype._flatten_function = function(accumulator, currentItem) {
    return accumulator.concat([[0/0, 0/0, 0/0]]).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 : 0/0;
      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 : 0/0);
        }
        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 : 0/0);
        }
        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 : 0/0);
        }
        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 : 0/0);
        }
        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.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.mantissas) / this.base;
    suffix_mantissa = _.first(this.mantissas) * this.base;
    this.extended_mantissas = _.flatten([prefix_mantissa, this.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.base));
    ideal_magnitude = Math.pow(this.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.factors;
    for (i = j = 0, ref = factors.length; 0 <= ref ? j < ref : j > ref; i = 0 <= ref ? ++j : --j) {
      ii = i + range.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.getters({
    min_intervals: function() {
      return _.invoke(this.tickers, 'get_min_interval');
    },
    max_intervals: function() {
      return _.invoke(this.tickers, 'get_max_interval');
    },
    min_interval: function() {
      return _.first(this.min_intervals);
    },
    max_interval: function() {
      return _.first(this.max_intervals);
    }
  });

  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.min_intervals, ideal_interval) - 1, _.sortedIndex(this.max_intervals, ideal_interval)];
    intervals = [this.min_intervals[ticker_ndxs[0]], this.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 === 2e308) {
      return this.tickers[0];
    }
    best_ticker_ndx = ticker_ndxs[best_index];
    best_ticker = this.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.min_interval;
  };

  ContinuousTicker.prototype.get_max_interval = function() {
    var ref;
    return (ref = this.max_interval) != null ? ref : 2e308;
  };

  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.days;
    interval = days.length > 1 ? (days[1] - days[0]) * ONE_DAY : 31 * ONE_DAY;
    return this.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.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.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.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.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.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.months;
    interval = months.length > 1 ? (months[1] - months[0]) * ONE_MONTH : 12 * ONE_MONTH;
    return this.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.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.getters({
    min_interval: function() {
      return this.interval;
    },
    max_interval: function() {
      return this.interval;
    }
  });

  SingleIntervalTicker.prototype.get_interval = function(data_low, data_high, n_desired_ticks) {
    return this.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.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.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.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.url, this.extra_url_vars);
    if (this.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.start, this.y_range.start, this.x_range.end, this.y_range.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.x_range;
    this.x_mapper = this.map_frame.x_mappers['default'];
    this.y_range = this.map_plot.y_range;
    this.y_mapper = this.map_frame.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.model.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.model.image_source.add_image(image.image_data);
    image.src = this.model.image_source.get_image_url(bounds[0], bounds[1], bounds[2], bounds[3], Math.ceil(this.map_frame.height), Math.ceil(this.map_frame.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.model.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.model.image_source.images[image_key];
    if (image_obj != null) {
      this.map_canvas.save();
      this._set_rect();
      this.map_canvas.globalAlpha = this.model.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.left) + (outline_width / 2);
    t = this.plot_view.canvas.vy_to_sy(this.map_frame.top) + (outline_width / 2);
    w = this.map_frame.width - outline_width;
    h = this.map_frame.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.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.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.url, this.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.initial_resolution != null) {
      return this.initial_resolution;
    } else {
      return 2 * Math.PI * 6378137 / this.tile_size;
    }
  };

  MercatorTileSource.prototype.is_valid_tile = function(x, y, z) {
    if (!this.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.x_origin_offset;
    my = py * res - this.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.x_origin_offset) / res;
    py = (my + this.y_origin_offset) / res;
    return [px, py];
  };

  MercatorTileSource.prototype.pixels_to_tile = function(px, py) {
    var tx, ty;
    tx = Math.ceil(px / parseFloat(this.tile_size));
    tx = tx === 0 ? tx : tx - 1;
    ty = Math.max(Math.ceil(py / parseFloat(this.tile_size)) - 1, 0);
    return [tx, ty];
  };

  MercatorTileSource.prototype.pixels_to_raster = function(px, py, level) {
    var mapSize;
    mapSize = this.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.tile_size, ty * this.tile_size, level), xmin = ref[0], ymin = ref[1];
    ref1 = this.pixels_to_meters((tx + 1) * this.tile_size, (ty + 1) * this.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);
      switch (value) {
        case '0':
          continue;
        case '1':
          tileX |= mask;
          break;
        case '2':
          tileY |= mask;
          break;
        case '3':
          tileX |= mask;
          tileY |= mask;
          break;
        default:
          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.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.url, this.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.start, this.y_range.start, this.x_range.end, this.y_range.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.x_range;
    this.x_mapper = this.map_frame.x_mappers['default'];
    this.y_range = this.map_plot.y_range;
    this.y_mapper = this.map_frame.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.model.tile_source.attribution;
    if (_.isString(attribution) && attribution.length > 0) {
      if (this.attributionEl != null) {
        return this.attributionEl.html(attribution);
      } else {
        border_width = this.map_plot.outline_line_width;
        bottom_offset = this.map_plot.min_border_bottom + border_width;
        right_offset = this.map_frame.right - this.map_frame.width;
        max_width = this.map_frame.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.model.tile_source.get_level_by_extent(this.initial_extent, this.map_frame.height, this.map_frame.width);
    new_extent = this.model.tile_source.snap_to_zoom(this.initial_extent, this.map_frame.height, this.map_frame.width, zoom_level);
    this.x_range.start = new_extent[0];
    this.y_range.start = new_extent[1];
    this.x_range.end = new_extent[2];
    this.y_range.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.model.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.model.tile_source.tile_xyz_to_quadkey(x, y, z),
      cache_key: this.model.tile_source.tile_xyz_to_key(x, y, z),
      bounds: bounds,
      loaded: false,
      x_coord: bounds[0],
      y_coord: bounds[3]
    };
    this.model.tile_source.tiles[tile.tile_data.cache_key] = tile.tile_data;
    tile.src = (ref = this.model.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.height || this._last_width !== this.map_frame.width) {
      extent = this.get_extent();
      zoom_level = this.model.tile_source.get_level_by_extent(extent, this.map_frame.height, this.map_frame.width);
      new_extent = this.model.tile_source.snap_to_zoom(extent, this.map_frame.height, this.map_frame.width, zoom_level);
      this.x_range.setv({
        start: new_extent[0],
        end: new_extent[2]
      });
      this.y_range.setv({
        start: new_extent[1],
        end: new_extent[3]
      });
      this.extent = new_extent;
      this._last_height = this.map_frame.height;
      this._last_width = this.map_frame.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.model.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.left) + (outline_width / 2);
    t = this.plot_view.canvas.vy_to_sy(this.map_frame.top) + (outline_width / 2);
    w = this.map_frame.width - outline_width;
    h = this.map_frame.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.model.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.model.tile_source;
    extent = this.get_extent();
    h = this.map_frame.height;
    w = this.map_frame.width;
    zoom_level = this.model.tile_source.get_level_by_extent(extent, h, w);
    tiles = this.model.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.model.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.model.tile_source;
    min_zoom = tile_source.min_zoom;
    max_zoom = tile_source.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.height;
    w = this.map_frame.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.setv({
        x_range: {
          start: extent[0],
          end: extent[2]
        }
      });
      this.y_range.setv({
        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.model.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.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.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.url, this.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("../../core/util/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
};

},{"../../core/util/proj4":"core/util/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.url, this.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.url, this.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.model.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.getters({
    tooltip: function() {
      return this.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.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.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/actions/zoom_in_tool":[function(require,module,exports){
var ActionTool, ZoomInTool, ZoomInToolView, logger, p, scale_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;

ActionTool = require("./action_tool");

scale_range = require("../../../core/util/zoom").scale_range;

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

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

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

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

  ZoomInToolView.prototype["do"] = function() {
    var dims, frame, h_axis, v_axis, zoom_info;
    frame = this.plot_model.frame;
    dims = this.model.dimensions;
    h_axis = dims === 'width' || dims === 'both';
    v_axis = dims === 'height' || dims === 'both';
    zoom_info = scale_range(frame, this.model.factor, h_axis, v_axis);
    this.plot_view.push_state('zoom_out', {
      range: zoom_info
    });
    this.plot_view.update_range(zoom_info, false, true);
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  return ZoomInToolView;

})(ActionTool.View);

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

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

  ZoomInTool.prototype.default_view = ZoomInToolView;

  ZoomInTool.prototype.type = "ZoomInTool";

  ZoomInTool.prototype.tool_name = "Zoom In";

  ZoomInTool.prototype.icon = "bk-tool-icon-zoom-in";

  ZoomInTool.getters({
    tooltip: function() {
      return this._get_dim_tooltip(this.tool_name, this.dimensions);
    }
  });

  ZoomInTool.define({
    factor: [p.Percent, 0.1],
    dimensions: [p.Dimensions, "both"]
  });

  return ZoomInTool;

})(ActionTool.Model);

module.exports = {
  Model: ZoomInTool,
  View: ZoomInToolView
};

},{"../../../core/logging":"core/logging","../../../core/properties":"core/properties","../../../core/util/zoom":"core/util/zoom","./action_tool":"models/tools/actions/action_tool"}],"models/tools/actions/zoom_out_tool":[function(require,module,exports){
var ActionTool, ZoomOutTool, ZoomOutToolView, logger, p, scale_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;

ActionTool = require("./action_tool");

scale_range = require("../../../core/util/zoom").scale_range;

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

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

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

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

  ZoomOutToolView.prototype["do"] = function() {
    var dims, frame, h_axis, v_axis, zoom_info;
    frame = this.plot_model.frame;
    dims = this.model.dimensions;
    h_axis = dims === 'width' || dims === 'both';
    v_axis = dims === 'height' || dims === 'both';
    zoom_info = scale_range(frame, -this.model.factor, h_axis, v_axis);
    this.plot_view.push_state('zoom_out', {
      range: zoom_info
    });
    this.plot_view.update_range(zoom_info, false, true);
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  return ZoomOutToolView;

})(ActionTool.View);

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

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

  ZoomOutTool.prototype.default_view = ZoomOutToolView;

  ZoomOutTool.prototype.type = "ZoomOutTool";

  ZoomOutTool.prototype.tool_name = "Zoom Out";

  ZoomOutTool.prototype.icon = "bk-tool-icon-zoom-out";

  ZoomOutTool.getters({
    tooltip: function() {
      return this._get_dim_tooltip(this.tool_name, this.dimensions);
    }
  });

  ZoomOutTool.define({
    factor: [p.Percent, 0.1],
    dimensions: [p.Dimensions, "both"]
  });

  return ZoomOutTool;

})(ActionTool.Model);

module.exports = {
  Model: ZoomOutTool,
  View: ZoomOutToolView
};

},{"../../../core/logging":"core/logging","../../../core/properties":"core/properties","../../../core/util/zoom":"core/util/zoom","./action_tool":"models/tools/actions/action_tool"}],"models/tools/button_tool":[function(require,module,exports){
var BokehView, 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");

BokehView = require("../../core/bokeh_view");

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.disabled).toggleClass('active', this.model.active);
    return this;
  };

  ButtonToolButtonView.prototype._clicked = function(e) {};

  return ButtonToolButtonView;

})(BokehView);

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.getters({
    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/bokeh_view":"core/bokeh_view","../../core/properties":"core/properties","./button_tool_template":"models/tools/button_tool_template","./tool":"models/tools/tool","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.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.frame;
    dims = this.model.dimensions;
    ref = this.model._get_dim_limits(this._baseboint, curpoint, frame, dims), vxlim = ref[0], vylim = ref[1];
    this.model.overlay.update({
      left: vxlim[0],
      right: vxlim[1],
      top: vylim[1],
      bottom: vylim[0]
    });
    if (this.model.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.frame;
    dims = this.model.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.model.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.model.computed_renderers;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.data_source;
      sm = ds.selection_manager;
      sm.select(this, this.plot_view.renderer_views[r.id], geometry, final, append);
    }
    if (this.model.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.model.computed_renderers[0];
    canvas = this.plot_model.canvas;
    frame = this.plot_model.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.x_mappers[r.x_range_name];
    ymapper = frame.y_mappers[r.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.model.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.Dimensions, "both"],
    select_every_mousemove: [p.Bool, false],
    callback: [p.Instance],
    overlay: [p.Instance, DEFAULT_BOX_OVERLAY]
  });

  BoxSelectTool.getters({
    tooltip: function() {
      return this._get_dim_tooltip(this.tool_name, 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.h_range.end;
    hstart = frame.h_range.start;
    vend = frame.v_range.end;
    vstart = frame.v_range.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.frame;
    dims = this.model.dimensions;
    if (this.model.match_aspect && dims === 'both') {
      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.model.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.frame;
    dims = this.model.dimensions;
    if (this.model.match_aspect && dims === 'both') {
      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.model.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.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.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.getters({
    tooltip: function() {
      return this._get_dim_tooltip(this.tool_name, this.dimensions);
    }
  });

  BoxZoomTool.define({
    dimensions: [p.Dimensions, "both"],
    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.active;
    return this.model.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.model.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.frame.h_range;
    v_range = this.plot_model.frame.v_range;
    if (vx > h_range.end) {
      vx = h_range.end;
    }
    if (vx < h_range.start) {
      vx = h_range.start;
    }
    if (vy > v_range.end) {
      vy = v_range.end;
    }
    if (vy < v_range.start) {
      vy = v_range.start;
    }
    this.data.vx.push(vx);
    this.data.vy.push(vy);
    overlay = this.model.overlay;
    overlay.update({
      xs: this.data.vx,
      ys: this.data.vy
    });
    if (this.model.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.model.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.model.computed_renderers;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.data_source;
      sm = ds.selection_manager;
      sm.select(this, this.plot_view.renderer_views[r.id], geometry, final, append);
    }
    if (this.model.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.model.computed_renderers[0];
    canvas = this.plot_model.canvas;
    frame = this.plot_model.frame;
    geometry['sx'] = canvas.v_vx_to_sx(geometry.vx);
    geometry['sy'] = canvas.v_vy_to_sy(geometry.vy);
    xmapper = frame.x_mappers[r.x_range_name];
    ymapper = frame.y_mappers[r.y_range_name];
    geometry['x'] = xmapper.v_map_from_target(geometry.vx);
    geometry['y'] = ymapper.v_map_from_target(geometry.vy);
    this.model.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.h_range;
      vr = frame.v_range;
      if (vx < hr.start || vx > hr.end) {
        this.v_axis_only = true;
      }
      if (vy < vr.start || vy > vr.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 = frame.h_range;
    sx_low = hr.start - new_dx;
    sx_high = hr.end - new_dx;
    vr = frame.v_range;
    sy_low = vr.start - new_dy;
    sy_high = vr.end - new_dy;
    dims = this.model.dimensions;
    if ((dims === 'width' || dims === 'both') && !this.v_axis_only) {
      sx0 = sx_low;
      sx1 = sx_high;
      sdx = -new_dx;
    } else {
      sx0 = hr.start;
      sx1 = hr.end;
      sdx = 0;
    }
    if ((dims === 'height' || dims === 'both') && !this.h_axis_only) {
      sy0 = sy_low;
      sy1 = sy_high;
      sdy = new_dy;
    } else {
      sy0 = vr.start;
      sy1 = vr.end;
      sdy = 0;
    }
    this.last_dx = dx;
    this.last_dy = dy;
    xrs = {};
    ref = frame.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.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.Dimensions, "both"]
  });

  PanTool.getters({
    tooltip: function() {
      return this._get_dim_tooltip("Pan", 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.model.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.model.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.model.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.model.computed_renderers;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.data_source;
      sm = ds.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.h_range.end - 40);
      top = canvas.vy_to_sy(frame.v_range.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.height;
    this.cw = canvas.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.width,
        height: this.plot_view.canvas.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.model.computed_renderers;
      results = [];
      for (j = 0, len = ref.length; j < len; j++) {
        r = ref[j];
        ds = r.data_source;
        sm = ds.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.x_mappers['default'];
    ym = this.plot_view.frame.y_mappers['default'];
    switch (g.type) {
      case 'point':
        g.x = xm.map_from_target(g.vx);
        g.y = ym.map_from_target(g.vy);
        break;
      case '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);
        break;
      case '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]);
        }
        break;
      default:
        logger.debug("Unrecognized selection geometry type: '" + g.type + "'");
    }
    if (final) {
      tool_events = this.plot_model.plot.tool_events;
      if (append) {
        geoms = tool_events.geometries;
        geoms.push(g);
      } else {
        geoms = [g];
      }
      tool_events.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.renderers;
      names = this.names;
      if (renderers.length === 0) {
        all_renderers = this.plot.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.name) >= 0) {
              results.push(r);
            }
          }
          return results;
        })();
      }
      return renderers;
    }, true);
    this.add_dependencies('computed_renderers', this, ['renderers', 'names', 'plot']);
    return this.add_dependencies('computed_renderers', this.plot, ['renderers']);
  };

  SelectTool.getters({
    computed_renderers: function() {
      return this._get_computed('computed_renderers');
    }
  });

  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.model.callback;
    this._save_geometry(geometry, final, append);
    cb_data = {
      geometries: this.plot_model.plot.tool_events.geometries
    };
    ref = this.model.computed_renderers;
    for (i = 0, len = ref.length; i < len; i++) {
      r = ref[i];
      ds = r.data_source;
      sm = ds.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_pan_tool":[function(require,module,exports){
var GestureTool, WheelPanTool, WheelPanToolView, _, 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");

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

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

  WheelPanToolView.prototype._scroll = function(e) {
    var delta, factor, multiplier, ref;
    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.model.speed * delta;
    if (factor > 0.9) {
      factor = 0.9;
    } else if (factor < -0.9) {
      factor = -0.9;
    }
    return this._update_ranges(factor);
  };

  WheelPanToolView.prototype._update_ranges = function(factor) {
    var end, frame, hr, mapper, name, pan_info, ref, ref1, ref2, ref3, ref4, ref5, start, sx0, sx1, sy0, sy1, vr, vx_high, vx_low, vx_range, vy_high, vy_low, vy_range, xrs, yrs;
    frame = this.plot_model.frame;
    hr = frame.h_range;
    vr = frame.v_range;
    ref = [hr.start, hr.end], vx_low = ref[0], vx_high = ref[1];
    ref1 = [vr.start, vr.end], vy_low = ref1[0], vy_high = ref1[1];
    switch (this.model.dimension) {
      case "height":
        vy_range = Math.abs(vy_high - vy_low);
        sx0 = vx_low;
        sx1 = vx_high;
        sy0 = vy_low + vy_range * factor;
        sy1 = vy_high + vy_range * factor;
        break;
      case "width":
        vx_range = Math.abs(vx_high - vx_low);
        sx0 = vx_low - vx_range * factor;
        sx1 = vx_high - vx_range * factor;
        sy0 = vy_low;
        sy1 = vy_high;
    }
    xrs = {};
    ref2 = frame.x_mappers;
    for (name in ref2) {
      mapper = ref2[name];
      ref3 = mapper.v_map_from_target([sx0, sx1], true), start = ref3[0], end = ref3[1];
      xrs[name] = {
        start: start,
        end: end
      };
    }
    yrs = {};
    ref4 = frame.y_mappers;
    for (name in ref4) {
      mapper = ref4[name];
      ref5 = mapper.v_map_from_target([sy0, sy1], true), start = ref5[0], end = ref5[1];
      yrs[name] = {
        start: start,
        end: end
      };
    }
    pan_info = {
      xrs: xrs,
      yrs: yrs,
      factor: factor
    };
    this.plot_view.push_state('wheel_pan', {
      range: pan_info
    });
    this.plot_view.update_range(pan_info, false, true);
    this.plot_view.interactive_timestamp = Date.now();
    return null;
  };

  return WheelPanToolView;

})(GestureTool.View);

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

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

  WheelPanTool.prototype.type = 'WheelPanTool';

  WheelPanTool.prototype.default_view = WheelPanToolView;

  WheelPanTool.prototype.tool_name = "Wheel Pan";

  WheelPanTool.prototype.icon = "bk-tool-icon-wheel-pan";

  WheelPanTool.prototype.event_type = 'scroll';

  WheelPanTool.prototype.default_order = 12;

  WheelPanTool.getters({
    tooltip: function() {
      return this._get_dim_tooltip(this.tool_name, this.dimension);
    }
  });

  WheelPanTool.define({
    dimension: [p.Dimension, "width"]
  });

  WheelPanTool.internal({
    speed: [p.Number, 1 / 1000]
  });

  return WheelPanTool;

})(GestureTool.Model);

module.exports = {
  Model: WheelPanTool,
  View: WheelPanToolView
};

},{"../../../core/properties":"core/properties","./gesture_tool":"models/tools/gestures/gesture_tool","underscore":"underscore"}],"models/tools/gestures/wheel_zoom_tool":[function(require,module,exports){
var GestureTool, WheelZoomTool, WheelZoomToolView, _, document, p, scale_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");

GestureTool = require("./gesture_tool");

scale_range = require("../../../core/util/zoom").scale_range;

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, factor, frame, h_axis, hr, multiplier, ref, v_axis, vr, vx, vy, zoom_info;
    frame = this.plot_model.frame;
    hr = frame.h_range;
    vr = frame.v_range;
    vx = this.plot_view.canvas.sx_to_vx(e.bokeh.sx);
    vy = this.plot_view.canvas.sy_to_vy(e.bokeh.sy);
    dims = this.model.dimensions;
    h_axis = (dims === 'width' || dims === 'both') && (hr.min < vx && vx < hr.max);
    v_axis = (dims === 'height' || dims === 'both') && (vr.min < vy && vy < vr.max);
    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.model.speed * delta;
    zoom_info = scale_range(frame, factor, h_axis, v_axis, {
      x: vx,
      y: vy
    });
    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.getters({
    tooltip: function() {
      return this._get_dim_tooltip(this.tool_name, this.dimensions);
    }
  });

  WheelZoomTool.define({
    dimensions: [p.Dimensions, "both"]
  });

  WheelZoomTool.internal({
    speed: [p.Number, 1 / 600]
  });

  return WheelZoomTool;

})(GestureTool.Model);

module.exports = {
  Model: WheelZoomTool,
  View: WheelZoomToolView
};

},{"../../../core/properties":"core/properties","../../../core/util/zoom":"core/util/zoom","./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, frame, vx, vy;
    if (!this.model.active) {
      return;
    }
    frame = this.plot_model.frame;
    canvas = this.plot_model.canvas;
    vx = canvas.sx_to_vx(e.bokeh.sx);
    vy = canvas.sy_to_vy(e.bokeh.sy);
    if (!frame.contains(vx, vy)) {
      vx = vy = null;
    }
    return this._update_spans(vx, vy);
  };

  CrosshairToolView.prototype._move_exit = function(e) {
    return this._update_spans(null, null);
  };

  CrosshairToolView.prototype._update_spans = function(x, y) {
    var dims;
    dims = this.model.dimensions;
    if (dims === 'width' || dims === 'both') {
      this.model.spans.width.computed_location = y;
    }
    if (dims === 'height' || dims === 'both') {
      return this.model.spans.height.computed_location = x;
    }
  };

  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.Dimensions, "both"],
    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.getters({
    tooltip: function() {
      return this._get_dim_tooltip("Crosshair", this.dimensions);
    },
    synthetic_renderers: function() {
      return _.values(this.spans);
    }
  });

  CrosshairTool.prototype.initialize = function(attrs, options) {
    CrosshairTool.__super__.initialize.call(this, attrs, options);
    return this.spans = {
      width: new Span.Model({
        for_hover: true,
        dimension: "width",
        render_mode: this.render_mode,
        location_units: this.location_units,
        line_color: this.line_color,
        line_width: this.line_width,
        line_alpha: this.line_alpha
      }),
      height: new Span.Model({
        for_hover: true,
        dimension: "height",
        render_mode: this.render_mode,
        location_units: this.location_units,
        line_color: this.line_color,
        line_width: this.line_width,
        line_alpha: this.line_alpha
      })
    };
  };

  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, _, _color_to_hex, hittest, logger, p, replace_placeholders,
  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("../../../core/hittest");

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

replace_placeholders = require("../../../core/util/templating").replace_placeholders;

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

_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 k, len, r, ref;
    ref = this.model.computed_renderers;
    for (k = 0, len = ref.length; k < len; k++) {
      r = ref[k];
      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(2e308, 2e308);
    ref = this.model.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.model.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, k, 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.model.computed_renderers;
    for (k = 0, len = ref.length; k < len; k++) {
      r = ref[k];
      sm = r.data_source.selection_manager;
      sm.inspect(this, this.plot_view.renderer_views[r.id], geometry, {
        "geometry": geometry
      });
    }
    if (this.model.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, j, k, l, len, len1, len2, m, pair, pt, ref, ref1, ref10, ref11, ref12, ref13, ref14, ref15, 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.model.ttmodels[renderer.model.id]) != null ? ref : null;
    if (tooltip == null) {
      return;
    }
    tooltip.clear();
    if (indices['0d'].glyph === null && indices['1d'].indices.length === 0) {
      return;
    }
    vx = geometry.vx;
    vy = geometry.vy;
    canvas = this.plot_model.canvas;
    frame = this.plot_model.frame;
    sx = canvas.vx_to_sx(vx);
    sy = canvas.vy_to_sy(vy);
    xmapper = frame.x_mappers[renderer.model.x_range_name];
    ymapper = frame.y_mappers[renderer.model.y_range_name];
    x = xmapper.map_from_target(vx);
    y = ymapper.map_from_target(vy);
    ref1 = indices['0d'].indices;
    for (k = 0, len = ref1.length; k < len; k++) {
      i = ref1[k];
      data_x = renderer.glyph._x[i + 1];
      data_y = renderer.glyph._y[i + 1];
      switch (this.model.line_policy) {
        case "interp":
          ref2 = renderer.glyph.get_interpolation_hit(i, geometry), data_x = ref2[0], data_y = ref2[1];
          rx = xmapper.map_to_target(data_x);
          ry = ymapper.map_to_target(data_y);
          break;
        case "prev":
          rx = canvas.sx_to_vx(renderer.glyph.sx[i]);
          ry = canvas.sy_to_vy(renderer.glyph.sy[i]);
          break;
        case "next":
          rx = canvas.sx_to_vx(renderer.glyph.sx[i + 1]);
          ry = canvas.sy_to_vy(renderer.glyph.sy[i + 1]);
          break;
        case "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) {
            ref3 = [d1x, d1y], sdatax = ref3[0], sdatay = ref3[1];
          } else {
            ref4 = [d2x, d2y], sdatax = ref4[0], sdatay = ref4[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);
          break;
        default:
          ref5 = [vx, vy], rx = ref5[0], ry = ref5[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));
    }
    ref6 = indices['1d'].indices;
    for (l = 0, len1 = ref6.length; l < len1; l++) {
      i = ref6[l];
      if (!_.isEmpty(indices['2d'])) {
        ref7 = _.pairs(indices['2d']);
        for (m = 0, len2 = ref7.length; m < len2; m++) {
          pair = ref7[m];
          ref8 = [pair[0], pair[1][0]], i = ref8[0], j = ref8[1];
          data_x = renderer.glyph._xs[i][j];
          data_y = renderer.glyph._ys[i][j];
          switch (this.model.line_policy) {
            case "interp":
              ref9 = renderer.glyph.get_interpolation_hit(i, j, geometry), data_x = ref9[0], data_y = ref9[1];
              rx = xmapper.map_to_target(data_x);
              ry = ymapper.map_to_target(data_y);
              break;
            case "prev":
              rx = canvas.sx_to_vx(renderer.glyph.sxs[i][j]);
              ry = canvas.sy_to_vy(renderer.glyph.sys[i][j]);
              break;
            case "next":
              rx = canvas.sx_to_vx(renderer.glyph.sxs[i][j + 1]);
              ry = canvas.sy_to_vy(renderer.glyph.sys[i][j + 1]);
              break;
            case "nearest":
              d1x = renderer.glyph.sx[i][j];
              d1y = renderer.glyph.sy[i][j];
              dist1 = hittest.dist_2_pts(d1x, d1y, sx, sy);
              d2x = renderer.glyph.sx[i][j + 1];
              d2y = renderer.glyph.sy[i][j + 1];
              dist2 = hittest.dist_2_pts(d2x, d2y, sx, sy);
              if (dist1 < dist2) {
                ref10 = [d1x, d1y], sdatax = ref10[0], sdatay = ref10[1];
              } else {
                ref11 = [d2x, d2y], sdatax = ref11[0], sdatay = ref11[1];
                j = j + 1;
              }
              data_x = renderer.glyph._x[i][j];
              data_y = renderer.glyph._y[i][j];
              rx = canvas.sx_to_vx(sdatax);
              ry = canvas.sy_to_vy(sdatay);
          }
          vars = {
            index: i,
            segment_index: j,
            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));
        }
      } else {
        data_x = (ref12 = renderer.glyph._x) != null ? ref12[i] : void 0;
        data_y = (ref13 = renderer.glyph._y) != null ? ref13[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 {
            ref14 = renderer.glyph.get_anchor_point("center", i, [sx, sy]), x = ref14.x, y = ref14.y;
          }
          rx = canvas.sx_to_vx(x);
          ry = canvas.sy_to_vy(y);
        } else {
          ref15 = [vx, vy], rx = ref15[0], ry = ref15[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.model.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.x_mappers[r.x_range_name];
    ymapper = frame.y_mappers[r.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, k, label, len, match, opts, ref, ref1, row, span, swatch, table, td, tooltips, value;
    tooltips = this.model.tooltips;
    if (_.isString(tooltips)) {
      return $('<div>').html(replace_placeholders(tooltips, ds, i, vars));
    } else if (_.isFunction(tooltips)) {
      return tooltips(ds, vars);
    } else {
      table = $('<table></table>');
      for (k = 0, len = tooltips.length; k < len; k++) {
        ref = tooltips[k], 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 = 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'],
    show_arrow: [p.Boolean, true],
    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.renderers;
      names = this.names;
      if (renderers.length === 0) {
        all_renderers = this.plot.renderers;
        renderers = (function() {
          var k, len, results;
          results = [];
          for (k = 0, len = all_renderers.length; k < len; k++) {
            r = all_renderers[k];
            if (r instanceof GlyphRenderer.Model) {
              results.push(r);
            }
          }
          return results;
        })();
      }
      if (names.length > 0) {
        renderers = (function() {
          var k, len, results;
          results = [];
          for (k = 0, len = renderers.length; k < len; k++) {
            r = renderers[k];
            if (names.indexOf(r.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.plot, ['renderers']);
    this.define_computed_property('ttmodels', function() {
      var k, len, r, ref, tooltip, tooltips, ttmodels;
      ttmodels = {};
      tooltips = this.tooltips;
      if (tooltips != null) {
        ref = this.computed_renderers;
        for (k = 0, len = ref.length; k < len; k++) {
          r = ref[k];
          tooltip = new Tooltip.Model({
            custom: _.isString(tooltips) || _.isFunction(tooltips),
            attachment: this.attachment,
            show_arrow: this.show_arrow
          });
          ttmodels[r.id] = tooltip;
        }
      }
      return ttmodels;
    });
    return this.add_dependencies('ttmodels', this, ['computed_renderers', 'tooltips']);
  };

  HoverTool.getters({
    computed_renderers: function() {
      return this._get_computed('computed_renderers');
    },
    ttmodels: function() {
      return this._get_computed('ttmodels');
    },
    synthetic_renderers: function() {
      return _.values(this.ttmodels);
    }
  });

  return HoverTool;

})(InspectTool.Model);

module.exports = {
  Model: HoverTool,
  View: HoverToolView
};

},{"../../../core/hittest":"core/hittest","../../../core/logging":"core/logging","../../../core/properties":"core/properties","../../../core/util/templating":"core/util/templating","../../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 BokehView, 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");

BokehView = require("../../../core/bokeh_view");

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.active;
    return this.model.active = !active;
  };

  return InspectToolListItemView;

})(BokehView);

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
};

},{"../../../core/bokeh_view":"core/bokeh_view","../tool":"models/tools/tool","./inspect_tool_list_item_template":"models/tools/inspectors/inspect_tool_list_item_template","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 BokehView, Model, 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");

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

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

BokehView = require("../../core/bokeh_view");

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

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

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

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

  ToolView.getters({
    plot_model: function() {
      return this.plot_view.model;
    }
  });

  ToolView.prototype.bind_bokeh_events = function() {
    return this.listenTo(this.model, 'change:active', (function(_this) {
      return function() {
        if (_this.model.active) {
          return _this.activate();
        } else {
          return _this.deactivate();
        }
      };
    })(this));
  };

  ToolView.prototype.activate = function() {};

  ToolView.prototype.deactivate = function() {};

  return ToolView;

})(BokehView);

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

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

  Tool.getters({
    synthetic_renderers: function() {
      return [];
    }
  });

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

  Tool.internal({
    active: [p.Boolean, false]
  });

  Tool.prototype._get_dim_tooltip = function(name, dims) {
    switch (dims) {
      case 'width':
        return name + " (x-axis)";
      case 'height':
        return name + " (y-axis)";
      case 'both':
        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.h_range;
    if (dims === 'width' || dims === 'both') {
      vxlim = [_.min([vx0, vx1]), _.max([vx0, vx1])];
      vxlim = [_.max([vxlim[0], hr.min]), _.min([vxlim[1], hr.max])];
    } else {
      vxlim = [hr.min, hr.max];
    }
    vr = frame.v_range;
    if (dims === 'height' || dims === 'both') {
      vylim = [_.min([vy0, vy1]), _.max([vy0, vy1])];
      vylim = [_.max([vylim[0], vr.min]), _.min([vylim[1], vr.max])];
    } else {
      vylim = [vr.min, vr.max];
    }
    return [vxlim, vylim];
  };

  return Tool;

})(Model);

module.exports = {
  Model: Tool,
  View: ToolView
};

},{"../../core/bokeh_view":"core/bokeh_view","../../core/logging":"core/logging","../../core/properties":"core/properties","../../model":"model","underscore":"underscore"}],"models/tools/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"}],"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.active;
    return this.model.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.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.model.logo,
      location: location,
      sticky: sticky
    }));
    inspectors = this.model.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.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.actions, function(item) {
      return button_bar_list.append(new ActionTool.ButtonView({
        model: item
      }).el);
    });
    gestures = this.model.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.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.active = false;
    }
    gestures[event_type].active = tool;
    this.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.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].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.on('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.x !== typeof this.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.x === 'string' && this.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.x === 'string') {
      data = this.data;
      column_names = data.columns();
      if (ref = this.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.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.x);
      tsy = data.get_column(this.y);
    } else {
      tsx = this.x;
      tsy = this.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.distribution === 'uniform') {
      return x + this.mean + ((bokeh_math.random() - 0.5) * this.width);
    }
    if (this.distribution === 'normal') {
      return x + bokeh_math.rnorm(this.mean, this.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.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.mode === "after") {
      ind = _.findLastIndex(this._x_sorted, function(num) {
        return x >= num;
      });
    }
    if (this.mode === "before") {
      ind = _.findIndex(this._x_sorted, function(num) {
        return x <= num;
      });
    }
    if (this.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);
  }

  return Transform;

})(Model);

module.exports = {
  Model: Transform
};

},{"../../model":"model","underscore":"underscore"}],"safely":[function(require,module,exports){
var _burst_into_flames, safely;

_burst_into_flames = function(error) {
  var body, box, button, message, ref, title;
  box = document.createElement("div");
  box.style["background-color"] = "#f2dede";
  box.style["border"] = "1px solid #a94442";
  box.style["border-radius"] = "4px";
  box.style["display"] = "inline-block";
  box.style["font-family"] = "sans-serif";
  box.style["margin-top"] = "5px";
  box.style["min-width"] = "200px";
  box.style["padding"] = "5px 5px 5px 10px";
  button = document.createElement("span");
  button.style["background-color"] = "#a94442";
  button.style["border-radius"] = "0px 4px 0px 0px";
  button.style["color"] = "white";
  button.style["cursor"] = "pointer";
  button.style["float"] = "right";
  button.style["font-size"] = "0.8em";
  button.style["margin"] = "-6px -6px 0px 0px";
  button.style["padding"] = "2px 5px 4px 5px";
  button.title = "close";
  button.setAttribute("aria-label", "close");
  button.appendChild(document.createTextNode("x"));
  button.addEventListener("click", function() {
    return body.removeChild(box);
  });
  title = document.createElement("h3");
  title.style["color"] = "#a94442";
  title.style["margin"] = "8px 0px 0px 0px";
  title.style["padding"] = "0px";
  title.appendChild(document.createTextNode("Bokeh Error"));
  message = document.createElement("pre");
  message.style["white-space"] = "unset";
  message.appendChild(document.createTextNode((ref = error.message) != null ? ref : error));
  box.appendChild(button);
  box.appendChild(title);
  box.appendChild(message);
  body = document.getElementsByTagName("body")[0];
  return body.insertBefore(box, body.firstChild);
};

safely = function(fn, silent) {
  var error;
  if (silent == null) {
    silent = false;
  }
  try {
    return fn();
  } catch (error1) {
    error = error1;
    _burst_into_flames(error);
    if (!silent) {
      throw error;
    }
  }
};

module.exports = safely;

},{}],"version":[function(require,module,exports){
var version;

version = '0.12.3';

module.exports = version;

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


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



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

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

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

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

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

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

function noop() {}

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

process.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":[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;
}));

},{}],"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/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_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/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/sign":[function(require,module,exports){
module.exports = function(x) {
  return x<0 ? -1 : 1;
};
},{}],"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/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/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/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"}],"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 "1.0.6";

    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"}],"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
